##// END OF EJS Templates
Reorganized the directory for ipython/ to have its own dir, which is a bit...
fperez -
r0:6f629fcc
parent child Browse files
Show More
@@ -0,0 +1,155 b''
1 # -*- coding: utf-8 -*-
2 """Tools for coloring text in ANSI terminals.
3
4 $Id: ColorANSI.py 410 2004-11-04 07:58:17Z fperez $"""
5
6 #*****************************************************************************
7 # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
8 #
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
12
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
16
17 __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
18
19 import os
20 from UserDict import UserDict
21
22 from IPython.Struct import Struct
23
24 def make_color_table(in_class):
25 """Build a set of color attributes in a class.
26
27 Helper function for building the *TermColors classes."""
28
29 color_templates = (
30 ("Black" , "0;30"),
31 ("Red" , "0;31"),
32 ("Green" , "0;32"),
33 ("Brown" , "0;33"),
34 ("Blue" , "0;34"),
35 ("Purple" , "0;35"),
36 ("Cyan" , "0;36"),
37 ("LightGray" , "0;37"),
38 ("DarkGray" , "1;30"),
39 ("LightRed" , "1;31"),
40 ("LightGreen" , "1;32"),
41 ("Yellow" , "1;33"),
42 ("LightBlue" , "1;34"),
43 ("LightPurple" , "1;35"),
44 ("LightCyan" , "1;36"),
45 ("White" , "1;37"), )
46
47 for name,value in color_templates:
48 setattr(in_class,name,in_class._base % value)
49
50 class TermColors:
51 """Color escape sequences.
52
53 This class defines the escape sequences for all the standard (ANSI?)
54 colors in terminals. Also defines a NoColor escape which is just the null
55 string, suitable for defining 'dummy' color schemes in terminals which get
56 confused by color escapes.
57
58 This class should be used as a mixin for building color schemes."""
59
60 NoColor = '' # for color schemes in color-less terminals.
61 Normal = '\033[0m' # Reset normal coloring
62 _base = '\033[%sm' # Template for all other colors
63
64 # Build the actual color table as a set of class attributes:
65 make_color_table(TermColors)
66
67 class InputTermColors:
68 """Color escape sequences for input prompts.
69
70 This class is similar to TermColors, but the escapes are wrapped in \001
71 and \002 so that readline can properly know the length of each line and
72 can wrap lines accordingly. Use this class for any colored text which
73 needs to be used in input prompts, such as in calls to raw_input().
74
75 This class defines the escape sequences for all the standard (ANSI?)
76 colors in terminals. Also defines a NoColor escape which is just the null
77 string, suitable for defining 'dummy' color schemes in terminals which get
78 confused by color escapes.
79
80 This class should be used as a mixin for building color schemes."""
81
82 NoColor = '' # for color schemes in color-less terminals.
83 Normal = '\001\033[0m\002' # Reset normal coloring
84 _base = '\001\033[%sm\002' # Template for all other colors
85
86 # Build the actual color table as a set of class attributes:
87 make_color_table(InputTermColors)
88
89 class ColorScheme:
90 """Generic color scheme class. Just a name and a Struct."""
91 def __init__(self,__scheme_name_,colordict=None,**colormap):
92 self.name = __scheme_name_
93 if colordict is None:
94 self.colors = Struct(**colormap)
95 else:
96 self.colors = Struct(colordict)
97
98 class ColorSchemeTable(UserDict):
99 """General class to handle tables of color schemes.
100
101 It's basically a dict of color schemes with a couple of shorthand
102 attributes and some convenient methods.
103
104 active_scheme_name -> obvious
105 active_colors -> actual color table of the active scheme"""
106
107 def __init__(self,scheme_list=None,default_scheme=''):
108 """Create a table of color schemes.
109
110 The table can be created empty and manually filled or it can be
111 created with a list of valid color schemes AND the specification for
112 the default active scheme.
113 """
114
115 UserDict.__init__(self)
116 if scheme_list is None:
117 self.active_scheme_name = ''
118 self.active_colors = None
119 else:
120 if default_scheme == '':
121 raise ValueError,'you must specify the default color scheme'
122 for scheme in scheme_list:
123 self.add_scheme(scheme)
124 self.set_active_scheme(default_scheme)
125
126 def add_scheme(self,new_scheme):
127 """Add a new color scheme to the table."""
128 if not isinstance(new_scheme,ColorScheme):
129 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
130 self[new_scheme.name] = new_scheme
131
132 def set_active_scheme(self,scheme,case_sensitive=0):
133 """Set the currently active scheme.
134
135 Names are by default compared in a case-insensitive way, but this can
136 be changed by setting the parameter case_sensitive to true."""
137
138 scheme_list = self.keys()
139 if case_sensitive:
140 valid_schemes = scheme_list
141 scheme_test = scheme
142 else:
143 valid_schemes = [s.lower() for s in scheme_list]
144 scheme_test = scheme.lower()
145 try:
146 scheme_idx = valid_schemes.index(scheme_test)
147 except ValueError:
148 raise ValueError,'Unrecognized color scheme: ' + scheme + \
149 '\nValid schemes: '+str(scheme_list).replace("'', ",'')
150 else:
151 active = scheme_list[scheme_idx]
152 self.active_scheme_name = active
153 self.active_colors = self[active].colors
154 # Now allow using '' as an index for the current active scheme
155 self[''] = self[active]
@@ -0,0 +1,116 b''
1 # -*- coding: utf-8 -*-
2 """Configuration loader
3
4 $Id: ConfigLoader.py 525 2005-02-19 10:53:12Z fperez $"""
5
6 #*****************************************************************************
7 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
8 #
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
12
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
16
17 import os
18 from pprint import pprint
19 import exceptions
20
21 from IPython import ultraTB
22 from IPython.Struct import Struct
23 from IPython.genutils import *
24
25 class ConfigLoaderError(exceptions.Exception):
26 """Exception for ConfigLoader class."""
27
28 def __init__(self,args=None):
29 self.args = args
30
31 class ConfigLoader:
32
33 """Configuration file loader capable of handling recursive inclusions and
34 with parametrized conflict resolution for multiply found keys."""
35
36 def __init__(self,conflict=None,field_sep=None,reclimit=15):
37
38 """The reclimit parameter controls the number of recursive
39 configuration file inclusions. This way we can stop early on (before
40 python's own recursion limit is hit) if there is a circular
41 inclusion.
42
43 - conflict: dictionary for conflict resolutions (see Struct.merge())
44
45 """
46 self.conflict = conflict
47 self.field_sep = field_sep
48 self.reset(reclimit)
49
50 def reset(self,reclimit=15):
51 self.reclimit = reclimit
52 self.recdepth = 0
53 self.included = []
54
55 def load(self,fname,convert=None,recurse_key='',incpath = '.',**kw):
56 """Load a configuration file, return the resulting Struct.
57
58 Call: load_config(fname,convert=None,conflict=None,recurse_key='')
59
60 - fname: file to load from.
61 - convert: dictionary of type conversions (see read_dict())
62 - recurse_key: keyword in dictionary to trigger recursive file
63 inclusions.
64 """
65
66 if self.recdepth > self.reclimit:
67 raise ConfigLoaderError, 'maximum recursive inclusion of rcfiles '+\
68 'exceeded: ' + `self.recdepth` + \
69 '.\nMaybe you have a circular chain of inclusions?'
70 self.recdepth += 1
71 fname = filefind(fname,incpath)
72 data = Struct()
73 # avoid including the same file more than once
74 if fname in self.included:
75 return data
76 Xinfo = ultraTB.AutoFormattedTB()
77 if convert==None and recurse_key : convert = {qwflat:recurse_key}
78 # for production, change warn to 0:
79 data.merge(read_dict(fname,convert,fs=self.field_sep,strip=1,
80 warn=0,no_empty=0,**kw))
81 # keep track of successfully loaded files
82 self.included.append(fname)
83 if recurse_key in data.keys():
84 for incfilename in data[recurse_key]:
85 found=0
86 try:
87 incfile = filefind(incfilename,incpath)
88 except IOError:
89 if os.name in ['nt','dos']:
90 try:
91 # Try again with '.ini' extension
92 incfilename += '.ini'
93 incfile = filefind(incfilename,incpath)
94 except IOError:
95 found = 0
96 else:
97 found = 1
98 else:
99 found = 0
100 else:
101 found = 1
102 if found:
103 try:
104 data.merge(self.load(incfile,convert,recurse_key,
105 incpath,**kw),
106 self.conflict)
107 except:
108 Xinfo()
109 warn('Problem loading included file: '+
110 `incfilename` + '. Ignoring it...')
111 else:
112 warn('File `%s` not found. Included by %s' % (incfilename,fname))
113
114 return data
115
116 # end ConfigLoader
@@ -0,0 +1,109 b''
1 # -*- coding: utf-8 -*-
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
4 $Id: CrashHandler.py 410 2004-11-04 07:58:17Z fperez $"""
5
6 #*****************************************************************************
7 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
8 #
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
12
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
16 __version__ = Release.version
17
18 #****************************************************************************
19 # Required modules
20
21 # From the standard library
22 import os,sys
23 from pprint import pprint,pformat
24
25 # Homebrewed
26 from IPython.genutils import *
27 from IPython.Itpl import Itpl,itpl,printpl
28 from IPython import ultraTB
29 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
30
31 #****************************************************************************
32 class CrashHandler:
33 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
34
35 def __init__(self,IP):
36 self.IP = IP # IPython instance
37 self.bug_contact = Release.authors['Fernando'][0]
38 self.mailto = Release.authors['Fernando'][1]
39
40 def __call__(self,etype, evalue, etb):
41
42 # Report tracebacks shouldn't use color in general (safer for users)
43 color_scheme = 'NoColor'
44
45 # Use this ONLY for developer debugging (keep commented out for release)
46 #color_scheme = 'Linux' # dbg
47
48 try:
49 rptdir = self.IP.rc.ipythondir
50 except:
51 rptdir = os.getcwd()
52 if not os.path.isdir(rptdir):
53 rptdir = os.getcwd()
54 self.report_name = os.path.join(rptdir,'IPython_crash_report.txt')
55 self.TBhandler = ultraTB.VerboseTB(color_scheme=color_scheme,long_header=1)
56 traceback = self.TBhandler.text(etype,evalue,etb,context=31)
57
58 # print traceback to screen
59 print >> sys.stderr, traceback
60
61 # and generate a complete report on disk
62 try:
63 report = open(self.report_name,'w')
64 except:
65 print >> sys.stderr, 'Could not create crash report on disk.'
66 return
67
68 msg = itpl('\n'+'*'*70+'\n'
69 """
70 Oops, IPython crashed. We do our best to make it stable, but...
71
72 A crash report was automatically generated with the following information:
73 - A verbatim copy of the traceback above this text.
74 - A copy of your input history during this session.
75 - Data on your current IPython configuration.
76
77 It was left in the file named:
78 \t'$self.report_name'
79 If you can email this file to the developers, the information in it will help
80 them in understanding and correcting the problem.
81
82 You can mail it to $self.bug_contact at $self.mailto
83 with the subject 'IPython Crash Report'.
84
85 If you want to do it now, the following command will work (under Unix):
86 mail -s 'IPython Crash Report' $self.mailto < $self.report_name
87
88 To ensure accurate tracking of this issue, please file a report about it at:
89 http://www.scipy.net/roundup/ipython (IPython's online bug tracker).
90 """)
91 print >> sys.stderr, msg
92
93 sec_sep = '\n\n'+'*'*75+'\n\n'
94 report.write('*'*75+'\n\n'+'IPython post-mortem report\n\n')
95 report.write('IPython version: %s \n\n' % __version__)
96 report.write('Platform info : os.name -> %s, sys.platform -> %s' %
97 (os.name,sys.platform) )
98 report.write(sec_sep+'Current user configuration structure:\n\n')
99 report.write(pformat(self.IP.rc.dict()))
100 report.write(sec_sep+'Crash traceback:\n\n' + traceback)
101 try:
102 report.write(sec_sep+"History of session input:")
103 for line in self.IP.user_ns['_ih']:
104 report.write(line)
105 report.write('\n*** Last line of input (may not be in above history):\n')
106 report.write(self.IP._last_input_line+'\n')
107 except:
108 pass
109 report.close()
This diff has been collapsed as it changes many lines, (671 lines changed) Show them Hide them
@@ -0,0 +1,671 b''
1 # -*- coding: utf-8 -*-
2 """DPyGetOpt -- Demiurge Python GetOptions Module
3
4 $Id: DPyGetOpt.py 389 2004-10-09 07:59:30Z fperez $
5
6 This module is modeled after perl's Getopt::Long module-- which
7 is, in turn, modeled after GNU's extended getopt() function.
8
9 Upon instantiation, the option specification should be a sequence
10 (list) of option definitions.
11
12 Options that take no arguments should simply contain the name of
13 the option. If a ! is post-pended, the option can be negated by
14 prepending 'no'; ie 'debug!' specifies that -debug and -nodebug
15 should be accepted.
16
17 Mandatory arguments to options are specified using a postpended
18 '=' + a type specifier. '=s' specifies a mandatory string
19 argument, '=i' specifies a mandatory integer argument, and '=f'
20 specifies a mandatory real number. In all cases, the '=' can be
21 substituted with ':' to specify that the argument is optional.
22
23 Dashes '-' in option names are allowed.
24
25 If an option has the character '@' postpended (after the
26 argumentation specification), it can appear multiple times within
27 each argument list that is processed. The results will be stored
28 in a list.
29
30 The option name can actually be a list of names separated by '|'
31 characters; ie-- 'foo|bar|baz=f@' specifies that all -foo, -bar,
32 and -baz options that appear on within the parsed argument list
33 must have a real number argument and that the accumulated list
34 of values will be available under the name 'foo'
35
36 $Id: DPyGetOpt.py 389 2004-10-09 07:59:30Z fperez $"""
37
38 #*****************************************************************************
39 #
40 # Copyright (c) 2001 Bill Bumgarner <bbum@friday.com>
41 #
42 #
43 # Published under the terms of the MIT license, hereby reproduced:
44 #
45 # Permission is hereby granted, free of charge, to any person obtaining a copy
46 # of this software and associated documentation files (the "Software"), to
47 # deal in the Software without restriction, including without limitation the
48 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
49 # sell copies of the Software, and to permit persons to whom the Software is
50 # furnished to do so, subject to the following conditions:
51 #
52 # The above copyright notice and this permission notice shall be included in
53 # all copies or substantial portions of the Software.
54 #
55 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
56 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
57 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
58 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
59 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
60 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
61 # IN THE SOFTWARE.
62 #
63 #*****************************************************************************
64
65 __author__ = 'Bill Bumgarner <bbum@friday.com>'
66 __license__ = 'MIT'
67 __version__ = '1.2'
68
69 # Modified to use re instead of regex and regsub modules.
70 # 2001/5/7, Jonathan Hogg <jonathan@onegoodidea.com>
71
72 import string
73 import re
74 import sys
75 import types
76
77 arg_error = 'DPyGetOpt Argument Error'
78 spec_error = 'DPyGetOpt Specification Error'
79 term_error = 'DPyGetOpt Termination Error'
80
81 specificationExpr = re.compile('(?P<required>.)(?P<type>.)(?P<multi>@?)')
82
83 ArgRequired = 'Requires an Argument'
84 ArgOptional = 'Argument Optional'
85
86 # The types modules is not used for these identifiers because there
87 # is no identifier for 'boolean' or 'generic'
88 StringArgType = 'String Argument Type'
89 IntegerArgType = 'Integer Argument Type'
90 RealArgType = 'Real Argument Type'
91 BooleanArgType = 'Boolean Argument Type'
92 GenericArgType = 'Generic Argument Type'
93
94 # dictionary of conversion functions-- boolean and generic options
95 # do not accept arguments and do not need conversion functions;
96 # the identity function is used purely for convenience.
97 ConversionFunctions = {
98 StringArgType : lambda x: x,
99 IntegerArgType : string.atoi,
100 RealArgType : string.atof,
101 BooleanArgType : lambda x: x,
102 GenericArgType : lambda x: x,
103 }
104
105 class DPyGetOpt:
106
107 def __init__(self, spec = None, terminators = ['--']):
108 """
109 Declare and intialize instance variables
110
111 Yes, declaration is not necessary... but one of the things
112 I sorely miss from C/Obj-C is the concept of having an
113 interface definition that clearly declares all instance
114 variables and methods without providing any implementation
115 details. it is a useful reference!
116
117 all instance variables are initialized to 0/Null/None of
118 the appropriate type-- not even the default value...
119 """
120
121 # sys.stderr.write(string.join(spec) + "\n")
122
123 self.allowAbbreviations = 1 # boolean, 1 if abbreviations will
124 # be expanded
125 self.freeValues = [] # list, contains free values
126 self.ignoreCase = 0 # boolean, YES if ignoring case
127 self.needsParse = 0 # boolean, YES if need to reparse parameter spec
128 self.optionNames = {} # dict, all option names-- value is index of tuple
129 self.optionStartExpr = None # regexp defining the start of an option (ie; '-', '--')
130 self.optionTuples = [] # list o' tuples containing defn of options AND aliases
131 self.optionValues = {} # dict, option names (after alias expansion) -> option value(s)
132 self.orderMixed = 0 # boolean, YES if options can be mixed with args
133 self.posixCompliance = 0 # boolean, YES indicates posix like behaviour
134 self.spec = [] # list, raw specs (in case it must be reparsed)
135 self.terminators = terminators # list, strings that terminate argument processing
136 self.termValues = [] # list, values after terminator
137 self.terminator = None # full name of terminator that ended
138 # option processing
139
140 # set up defaults
141 self.setPosixCompliance()
142 self.setIgnoreCase()
143 self.setAllowAbbreviations()
144
145 # parse spec-- if present
146 if spec:
147 self.parseConfiguration(spec)
148
149 def setPosixCompliance(self, aFlag = 0):
150 """
151 Enables and disables posix compliance.
152
153 When enabled, '+' can be used as an option prefix and free
154 values can be mixed with options.
155 """
156 self.posixCompliance = aFlag
157 self.needsParse = 1
158
159 if self.posixCompliance:
160 self.optionStartExpr = re.compile('(--|-)(?P<option>[A-Za-z0-9_-]+)(?P<arg>=.*)?')
161 self.orderMixed = 0
162 else:
163 self.optionStartExpr = re.compile('(--|-|\+)(?P<option>[A-Za-z0-9_-]+)(?P<arg>=.*)?')
164 self.orderMixed = 1
165
166 def isPosixCompliant(self):
167 """
168 Returns the value of the posix compliance flag.
169 """
170 return self.posixCompliance
171
172 def setIgnoreCase(self, aFlag = 1):
173 """
174 Enables and disables ignoring case during option processing.
175 """
176 self.needsParse = 1
177 self.ignoreCase = aFlag
178
179 def ignoreCase(self):
180 """
181 Returns 1 if the option processor will ignore case when
182 processing options.
183 """
184 return self.ignoreCase
185
186 def setAllowAbbreviations(self, aFlag = 1):
187 """
188 Enables and disables the expansion of abbreviations during
189 option processing.
190 """
191 self.allowAbbreviations = aFlag
192
193 def willAllowAbbreviations(self):
194 """
195 Returns 1 if abbreviated options will be automatically
196 expanded to the non-abbreviated form (instead of causing an
197 unrecognized option error).
198 """
199 return self.allowAbbreviations
200
201 def addTerminator(self, newTerm):
202 """
203 Adds newTerm as terminator of option processing.
204
205 Whenever the option processor encounters one of the terminators
206 during option processing, the processing of options terminates
207 immediately, all remaining options are stored in the termValues
208 instance variable and the full name of the terminator is stored
209 in the terminator instance variable.
210 """
211 self.terminators = self.terminators + [newTerm]
212
213 def _addOption(self, oTuple):
214 """
215 Adds the option described by oTuple (name, (type, mode,
216 default), alias) to optionTuples. Adds index keyed under name
217 to optionNames. Raises spec_error if name already in
218 optionNames
219 """
220 (name, (type, mode, default, multi), realName) = oTuple
221
222 # verify name and add to option names dictionary
223 if self.optionNames.has_key(name):
224 if realName:
225 raise spec_error, 'Alias \'' + name + '\' for \'' + realName + \
226 '\' already used for another option or alias.'
227 else:
228 raise spec_error, 'Option named \'' + name + \
229 '\' specified more than once. Specification: ' + option
230
231 # validated. add to optionNames
232 self.optionNames[name] = self.tupleIndex
233 self.tupleIndex = self.tupleIndex + 1
234
235 # add to optionTuples
236 self.optionTuples = self.optionTuples + [oTuple]
237
238 # if type is boolean, add negation
239 if type == BooleanArgType:
240 alias = 'no' + name
241 specTuple = (type, mode, 0, multi)
242 oTuple = (alias, specTuple, name)
243
244 # verify name and add to option names dictionary
245 if self.optionNames.has_key(alias):
246 if realName:
247 raise spec_error, 'Negated alias \'' + name + '\' for \'' + realName + \
248 '\' already used for another option or alias.'
249 else:
250 raise spec_error, 'Negated option named \'' + name + \
251 '\' specified more than once. Specification: ' + option
252
253 # validated. add to optionNames
254 self.optionNames[alias] = self.tupleIndex
255 self.tupleIndex = self.tupleIndex + 1
256
257 # add to optionTuples
258 self.optionTuples = self.optionTuples + [oTuple]
259
260 def addOptionConfigurationTuple(self, oTuple):
261 (name, argSpec, realName) = oTuple
262 if self.ignoreCase:
263 name = string.lower(name)
264 if realName:
265 realName = string.lower(realName)
266 else:
267 realName = name
268
269 oTuple = (name, argSpec, realName)
270
271 # add option
272 self._addOption(oTuple)
273
274 def addOptionConfigurationTuples(self, oTuple):
275 if type(oTuple) is ListType:
276 for t in oTuple:
277 self.addOptionConfigurationTuple(t)
278 else:
279 self.addOptionConfigurationTuple(oTuple)
280
281 def parseConfiguration(self, spec):
282 # destroy previous stored information + store raw spec
283 self.spec = spec
284 self.optionTuples = []
285 self.optionNames = {}
286 self.tupleIndex = 0
287
288 tupleIndex = 0
289
290 # create some regex's for parsing each spec
291 splitExpr = \
292 re.compile('(?P<names>\w+[-A-Za-z0-9|]*)?(?P<spec>!|[=:][infs]@?)?')
293 for option in spec:
294 # push to lower case (does not negatively affect
295 # specification)
296 if self.ignoreCase:
297 option = string.lower(option)
298
299 # break into names, specification
300 match = splitExpr.match(option)
301 if match is None:
302 raise spec_error, 'Invalid specification {' + option + '}'
303
304 names = match.group('names')
305 specification = match.group('spec')
306
307 # break name into name, aliases
308 nlist = string.split(names, '|')
309
310 # get name
311 name = nlist[0]
312 aliases = nlist[1:]
313
314 # specificationExpr = regex.symcomp('\(<required>.\)\(<type>.\)\(<multi>@?\)')
315 if not specification:
316 #spec tuple is ('type', 'arg mode', 'default value', 'multiple')
317 argType = GenericArgType
318 argMode = None
319 argDefault = 1
320 argMultiple = 0
321 elif specification == '!':
322 argType = BooleanArgType
323 argMode = None
324 argDefault = 1
325 argMultiple = 0
326 else:
327 # parse
328 match = specificationExpr.match(specification)
329 if match is None:
330 # failed to parse, die
331 raise spec_error, 'Invalid configuration for option \'' + option + '\''
332
333 # determine mode
334 required = match.group('required')
335 if required == '=':
336 argMode = ArgRequired
337 elif required == ':':
338 argMode = ArgOptional
339 else:
340 raise spec_error, 'Unknown requirement configuration \'' + required + '\''
341
342 # determine type
343 type = match.group('type')
344 if type == 's':
345 argType = StringArgType
346 argDefault = ''
347 elif type == 'i':
348 argType = IntegerArgType
349 argDefault = 1
350 elif type == 'f' or type == 'n':
351 argType = RealArgType
352 argDefault = 1
353 else:
354 raise spec_error, 'Unknown type specifier \'' + type + '\''
355
356 # determine quantity
357 if match.group('multi') == '@':
358 argMultiple = 1
359 else:
360 argMultiple = 0
361 ## end else (of not specification)
362
363 # construct specification tuple
364 specTuple = (argType, argMode, argDefault, argMultiple)
365
366 # add the option-- option tuple is (name, specTuple, real name)
367 oTuple = (name, specTuple, name)
368 self._addOption(oTuple)
369
370 for alias in aliases:
371 # drop to all lower (if configured to do so)
372 if self.ignoreCase:
373 alias = string.lower(alias)
374 # create configuration tuple
375 oTuple = (alias, specTuple, name)
376 # add
377 self._addOption(oTuple)
378
379 # successfully parsed....
380 self.needsParse = 0
381
382 def _getArgTuple(self, argName):
383 """
384 Returns a list containing all the specification tuples that
385 match argName. If none match, None is returned. If one
386 matches, a list with one tuple is returned. If more than one
387 match, a list containing all the tuples that matched is
388 returned.
389
390 In other words, this function does not pass judgement upon the
391 validity of multiple matches.
392 """
393 # is it in the optionNames dict?
394
395 try:
396 # sys.stderr.write(argName + string.join(self.optionNames.keys()) + "\n")
397
398 # yes, get index
399 tupleIndex = self.optionNames[argName]
400 # and return tuple as element of list
401 return [self.optionTuples[tupleIndex]]
402 except KeyError:
403 # are abbreviations allowed?
404 if not self.allowAbbreviations:
405 # No! terefore, this cannot be valid argument-- nothing found
406 return None
407
408 # argName might be an abbreviation (and, abbreviations must
409 # be allowed... or this would not have been reached!)
410
411 # create regex for argName
412 argExpr = re.compile('^' + argName)
413
414 tuples = filter(lambda x, argExpr=argExpr: argExpr.search(x[0]) is not None,
415 self.optionTuples)
416
417 if not len(tuples):
418 return None
419 else:
420 return tuples
421
422 def _isTerminator(self, optionName):
423 """
424 Returns the full name of the terminator if optionName is a valid
425 terminator. If it is, sets self.terminator to the full name of
426 the terminator.
427
428 If more than one terminator matched, raises a term_error with a
429 string describing the ambiguity.
430 """
431
432 # sys.stderr.write(optionName + "\n")
433 # sys.stderr.write(repr(self.terminators))
434
435 if optionName in self.terminators:
436 self.terminator = optionName
437 elif not self.allowAbbreviations:
438 return None
439
440 # regex thing in bogus
441 # termExpr = regex.compile('^' + optionName)
442
443 terms = filter(lambda x, on=optionName: string.find(x,on) == 0, self.terminators)
444
445 if not len(terms):
446 return None
447 elif len(terms) > 1:
448 raise term_error, 'Ambiguous terminator \'' + optionName + \
449 '\' matches ' + repr(terms)
450
451 self.terminator = terms[0]
452 return self.terminator
453
454 def processArguments(self, args = None):
455 """
456 Processes args, a list of arguments (including options).
457
458 If args is the same as sys.argv, automatically trims the first
459 argument (the executable name/path).
460
461 If an exception is not raised, the argument list was parsed
462 correctly.
463
464 Upon successful completion, the freeValues instance variable
465 will contain all the arguments that were not associated with an
466 option in the order they were encountered. optionValues is a
467 dictionary containing the value of each option-- the method
468 valueForOption() can be used to query this dictionary.
469 terminator will contain the argument encountered that terminated
470 option processing (or None, if a terminator was never
471 encountered) and termValues will contain all of the options that
472 appeared after the Terminator (or an empty list).
473 """
474
475 if hasattr(sys, "argv") and args == sys.argv:
476 args = sys.argv[1:]
477
478 max = len(args) # maximum index + 1
479 self.freeValues = [] # array to hold return values
480 self.optionValues= {}
481 index = 0 # initial index
482 self.terminator = None
483 self.termValues = []
484
485 while index < max:
486 # obtain argument
487 arg = args[index]
488 # increment index -- REMEMBER; it is NOW incremented
489 index = index + 1
490
491 # terminate immediately if option terminator encountered
492 if self._isTerminator(arg):
493 self.freeValues = self.freeValues + args[index:]
494 self.termValues = args[index:]
495 return
496
497 # is this possibly an option?
498 match = self.optionStartExpr.match(arg)
499 if match is None:
500 # not an option-- add to freeValues
501 self.freeValues = self.freeValues + [arg]
502 if not self.orderMixed:
503 # mixing not allowed; add rest of args as freeValues
504 self.freeValues = self.freeValues + args[index:]
505 # return to caller
506 return
507 else:
508 continue
509
510 # grab name
511 optName = match.group('option')
512
513 # obtain next argument-- index has already been incremented
514 nextArg = match.group('arg')
515 if nextArg:
516 nextArg = nextArg[1:]
517 index = index - 1 # put it back
518 else:
519 try:
520 nextArg = args[index]
521 except:
522 nextArg = None
523
524 # transpose to lower case, if necessary
525 if self.ignoreCase:
526 optName = string.lower(optName)
527
528 # obtain defining tuple
529 tuples = self._getArgTuple(optName)
530
531 if tuples == None:
532 raise arg_error, 'Illegal option \'' + arg + '\''
533 elif len(tuples) > 1:
534 raise arg_error, 'Ambiguous option \'' + arg + '\'; matches ' + \
535 repr(map(lambda x: x[0], tuples))
536 else:
537 config = tuples[0]
538
539 # config is now set to the configuration tuple for the
540 # argument
541 (fullName, spec, realName) = config
542 (optType, optMode, optDefault, optMultiple) = spec
543
544 # if opt mode required, but nextArg is none, raise an error
545 if (optMode == ArgRequired):
546 if (not nextArg) or self._isTerminator(nextArg):
547 # print nextArg
548 raise arg_error, 'Option \'' + arg + \
549 '\' requires an argument of type ' + optType
550
551 if (not optMode == None) and nextArg and (not self._isTerminator(nextArg)):
552 # nextArg defined, option configured to possibly consume arg
553 try:
554 # grab conversion function-- the try is more for internal diagnostics
555 func = ConversionFunctions[optType]
556 try:
557 optionValue = func(nextArg)
558 index = index + 1
559 except:
560 # only raise conversion error if REQUIRED to consume argument
561 if optMode == ArgRequired:
562 raise arg_error, 'Invalid argument to option \'' + arg + \
563 '\'; should be \'' + optType + '\''
564 else:
565 optionValue = optDefault
566 except arg_error:
567 raise arg_error, sys.exc_value
568 except:
569 raise arg_error, '(' + arg + \
570 ') Conversion function for \'' + optType + '\' not found.'
571 else:
572 optionValue = optDefault
573
574 # add value to options dictionary
575 if optMultiple:
576 # can be multiple values
577 try:
578 # try to append element
579 self.optionValues[realName] = self.optionValues[realName] + [optionValue]
580 except:
581 # failed-- must not exist; add it
582 self.optionValues[realName] = [optionValue]
583 else:
584 # only one value per
585 if self.isPosixCompliant and self.optionValues.has_key(realName):
586 raise arg_error, 'Argument \'' + arg + '\' occurs multiple times.'
587
588 self.optionValues[realName] = optionValue
589
590 def valueForOption(self, optionName, defaultValue = None):
591 """
592 Return the value associated with optionName. If optionName was
593 not encountered during parsing of the arguments, returns the
594 defaultValue (which defaults to None).
595 """
596 try:
597 optionValue = self.optionValues[optionName]
598 except:
599 optionValue = defaultValue
600
601 return optionValue
602
603 ##
604 ## test/example section
605 ##
606 test_error = 'Test Run Amok!'
607 def _test():
608 """
609 A relatively complete test suite.
610 """
611 try:
612 DPyGetOpt(['foo', 'bar=s', 'foo'])
613 except:
614 print 'EXCEPTION (should be \'foo\' already used..): ' + sys.exc_value
615
616 try:
617 DPyGetOpt(['foo|bar|apple=s@', 'baz|apple!'])
618 except:
619 print 'EXCEPTION (should be duplicate alias/name error): ' + sys.exc_value
620
621 x = DPyGetOpt(['apple|atlas=i@', 'application|executable=f@'])
622 try:
623 x.processArguments(['-app', '29.3'])
624 except:
625 print 'EXCEPTION (should be ambiguous argument): ' + sys.exc_value
626
627 x = DPyGetOpt(['foo'], ['antigravity', 'antithesis'])
628 try:
629 x.processArguments(['-foo', 'anti'])
630 except:
631 print 'EXCEPTION (should be ambiguous terminator): ' + sys.exc_value
632
633 profile = ['plain-option',
634 'boolean-option!',
635 'list-of-integers=i@',
636 'list-real-option|list-real-alias|list-real-pseudonym=f@',
637 'optional-string-option:s',
638 'abbreviated-string-list=s@']
639
640 terminators = ['terminator']
641
642 args = ['-plain-option',
643 '+noboolean-option',
644 '--list-of-integers', '1',
645 '+list-of-integers', '2',
646 '-list-of-integers', '3',
647 'freeargone',
648 '-list-real-option', '1.1',
649 '+list-real-alias', '1.2',
650 '--list-real-pseudonym', '1.3',
651 'freeargtwo',
652 '-abbreviated-string-list', 'String1',
653 '--abbreviated-s', 'String2',
654 '-abbrev', 'String3',
655 '-a', 'String4',
656 '-optional-string-option',
657 'term',
658 'next option should look like an invalid arg',
659 '-a']
660
661
662 print 'Using profile: ' + repr(profile)
663 print 'With terminator: ' + repr(terminators)
664 print 'Processing arguments: ' + repr(args)
665
666 go = DPyGetOpt(profile, terminators)
667 go.processArguments(args)
668
669 print 'Options (and values): ' + repr(go.optionValues)
670 print 'free args: ' + repr(go.freeValues)
671 print 'term args: ' + repr(go.termValues)
@@ -0,0 +1,53 b''
1 # -*- coding: utf-8 -*-
2 """
3 Pdb debugger class.
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
7 damaged.
8
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
15
16 http://www.python.org/2.2.3/license.html
17
18 $Id: Debugger.py 590 2005-05-30 06:26:51Z fperez $"""
19
20 from IPython import Release
21 __author__ = '%s <%s>' % Release.authors['Fernando']
22 __license__ = 'Python'
23
24 import pdb,bdb,cmd,os,sys
25
26 class Pdb(pdb.Pdb):
27 """Modified Pdb class, does not load readline."""
28 def __init__(self):
29 bdb.Bdb.__init__(self)
30 cmd.Cmd.__init__(self,completekey=None) # don't load readline
31 self.prompt = '(Pdb) '
32 self.aliases = {}
33
34 # Read $HOME/.pdbrc and ./.pdbrc
35 self.rcLines = []
36 if os.environ.has_key('HOME'):
37 envHome = os.environ['HOME']
38 try:
39 rcFile = open(os.path.join(envHome, ".pdbrc"))
40 except IOError:
41 pass
42 else:
43 for line in rcFile.readlines():
44 self.rcLines.append(line)
45 rcFile.close()
46 try:
47 rcFile = open(".pdbrc")
48 except IOError:
49 pass
50 else:
51 for line in rcFile.readlines():
52 self.rcLines.append(line)
53 rcFile.close()
@@ -0,0 +1,270 b''
1 # -*- coding: utf-8 -*-
2 """Modified input prompt for executing files.
3
4 We define a special input line filter to allow typing lines which begin with
5 '~', '/' or '.'. If one of those strings is encountered, it is automatically
6 executed.
7
8 $Id: InterpreterExec.py 573 2005-04-08 08:38:09Z fperez $"""
9
10 #*****************************************************************************
11 # Copyright (C) 2004 W.J. van der Laan <gnufnork@hetdigitalegat.nl>
12 # Copyright (C) 2004 Fernando Perez <fperez@colorado.edu>
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
17
18 from IPython import Release
19 __author__ = 'W.J. van der Laan <gnufnork@hetdigitalegat.nl>, '\
20 '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
22
23 def prefilter_shell(self,line,continuation):
24 """Alternate prefilter, modified for shell-like functionality.
25
26 - Execute all lines beginning with '~', '/' or '.'
27 - $var=cmd <=> %sc var=cmd
28 - $$var=cmd <=> %sc -l var=cmd
29 """
30
31 if line:
32 l0 = line[0]
33 if l0 in '~/.':
34 return self._prefilter("!%s"%line,continuation)
35 elif l0=='$':
36 lrest = line[1:]
37 if lrest.startswith('$'):
38 # $$var=cmd <=> %sc -l var=cmd
39 return self._prefilter("%ssc -l %s" % (self.ESC_MAGIC,lrest[1:]),
40 continuation)
41 else:
42 # $var=cmd <=> %sc var=cmd
43 return self._prefilter("%ssc %s" % (self.ESC_MAGIC,lrest),
44 continuation)
45 else:
46 return self._prefilter(line,continuation)
47 else:
48 return self._prefilter(line,continuation)
49
50 # Rebind this to be the new IPython prefilter:
51 from IPython.iplib import InteractiveShell
52 InteractiveShell.prefilter = prefilter_shell
53 # Clean up the namespace.
54 del InteractiveShell,prefilter_shell
55
56 # Provide pysh and further shell-oriented services
57 import os,sys,shutil
58 from IPython.genutils import system,shell,getoutput,getoutputerror
59
60 # Short aliases for getting shell output as a string and a list
61 sout = getoutput
62 lout = lambda cmd: getoutput(cmd,split=1)
63
64 # Empty function, meant as a docstring holder so help(pysh) works.
65 def pysh():
66 """Pysh is a set of modules and extensions to IPython which make shell-like
67 usage with Python syntax more convenient. Keep in mind that pysh is NOT a
68 full-blown shell, so don't try to make it your /etc/passwd entry!
69
70 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
71 you'll suspend pysh itself, not the process you just started.
72
73 Since pysh is really nothing but a customized IPython, you should
74 familiarize yourself with IPython's features. This brief help mainly
75 documents areas in which pysh differs from the normal IPython.
76
77 ALIASES
78 -------
79 All of your $PATH has been loaded as IPython aliases, so you should be
80 able to type any normal system command and have it executed. See %alias?
81 and %unalias? for details on the alias facilities.
82
83 SPECIAL SYNTAX
84 --------------
85 Any lines which begin with '~', '/' and '.' will be executed as shell
86 commands instead of as Python code. The special escapes below are also
87 recognized. !cmd is valid in single or multi-line input, all others are
88 only valid in single-line input:
89
90 !cmd - pass 'cmd' directly to the shell
91 !!cmd - execute 'cmd' and return output as a list (split on '\\n')
92 $var=cmd - capture output of cmd into var, as a string
93 $$var=cmd - capture output of cmd into var, as a list (split on '\\n')
94
95 The $/$$ syntaxes make Python variables from system output, which you can
96 later use for further scripting. The converse is also possible: when
97 executing an alias or calling to the system via !/!!, you can expand any
98 python variable or expression by prepending it with $. Full details of
99 the allowed syntax can be found in Python's PEP 215.
100
101 A few brief examples will illustrate these:
102
103 fperez[~/test]|3> !ls *s.py
104 scopes.py strings.py
105
106 ls is an internal alias, so there's no need to use !:
107 fperez[~/test]|4> ls *s.py
108 scopes.py* strings.py
109
110 !!ls will return the output into a Python variable:
111 fperez[~/test]|5> !!ls *s.py
112 <5> ['scopes.py', 'strings.py']
113 fperez[~/test]|6> print _5
114 ['scopes.py', 'strings.py']
115
116 $ and $$ allow direct capture to named variables:
117 fperez[~/test]|7> $astr = ls *s.py
118 fperez[~/test]|8> astr
119 <8> 'scopes.py\\nstrings.py'
120
121 fperez[~/test]|9> $$alist = ls *s.py
122 fperez[~/test]|10> alist
123 <10> ['scopes.py', 'strings.py']
124
125 alist is now a normal python list you can loop over. Using $ will expand
126 back the python values when alias calls are made:
127 fperez[~/test]|11> for f in alist:
128 |..> print 'file',f,
129 |..> wc -l $f
130 |..>
131 file scopes.py 13 scopes.py
132 file strings.py 4 strings.py
133
134 Note that you may need to protect your variables with braces if you want
135 to append strings to their names. To copy all files in alist to .bak
136 extensions, you must use:
137 fperez[~/test]|12> for f in alist:
138 |..> cp $f ${f}.bak
139
140 If you try using $f.bak, you'll get an AttributeError exception saying
141 that your string object doesn't have a .bak attribute. This is because
142 the $ expansion mechanism allows you to expand full Python expressions:
143 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
144 sys.platform is: linux2
145
146 IPython's input history handling is still active, which allows you to
147 rerun a single block of multi-line input by simply using exec:
148 fperez[~/test]|14> $$alist = ls *.eps
149 fperez[~/test]|15> exec _i11
150 file image2.eps 921 image2.eps
151 file image.eps 921 image.eps
152
153 While these are new special-case syntaxes, they are designed to allow very
154 efficient use of the shell with minimal typing. At an interactive shell
155 prompt, conciseness of expression wins over readability.
156
157 USEFUL FUNCTIONS AND MODULES
158 ----------------------------
159 The os, sys and shutil modules from the Python standard library are
160 automatically loaded. Some additional functions, useful for shell usage,
161 are listed below. You can request more help about them with '?'.
162
163 shell - execute a command in the underlying system shell
164 system - like shell(), but return the exit status of the command
165 sout - capture the output of a command as a string
166 lout - capture the output of a command as a list (split on '\\n')
167 getoutputerror - capture (output,error) of a shell command
168
169 sout/lout are the functional equivalents of $/$$. They are provided to
170 allow you to capture system output in the middle of true python code,
171 function definitions, etc (where $ and $$ are invalid).
172
173 DIRECTORY MANAGEMENT
174 --------------------
175 Since each command passed by pysh to the underlying system is executed in
176 a subshell which exits immediately, you can NOT use !cd to navigate the
177 filesystem.
178
179 Pysh provides its own builtin '%cd' magic command to move in the
180 filesystem (the % is not required with automagic on). It also maintains a
181 list of visited directories (use %dhist to see it) and allows direct
182 switching to any of them. Type 'cd?' for more details.
183
184 %pushd, %popd and %dirs are provided for directory stack handling.
185
186 PROMPT CUSTOMIZATION
187 --------------------
188
189 The supplied ipythonrc-pysh profile comes with an example of a very
190 colored and detailed prompt, mainly to serve as an illustration. The
191 valid escape sequences, besides color names, are:
192
193 \\# - Prompt number.
194 \\D - Dots, as many as there are digits in \\# (so they align).
195 \\w - Current working directory (cwd).
196 \\W - Basename of current working directory.
197 \\XN - Where N=0..5. N terms of the cwd, with $HOME written as ~.
198 \\YN - Where N=0..5. Like XN, but if ~ is term N+1 it's also shown.
199 \\u - Username.
200 \\H - Full hostname.
201 \\h - Hostname up to first '.'
202 \\$ - Root symbol ($ or #).
203 \\t - Current time, in H:M:S format.
204 \\v - IPython release version.
205 \\n - Newline.
206 \\r - Carriage return.
207 \\\\ - An explicitly escaped '\\'.
208
209 You can configure your prompt colors using any ANSI color escape. Each
210 color escape sets the color for any subsequent text, until another escape
211 comes in and changes things. The valid color escapes are:
212
213 \\C_Black
214 \\C_Blue
215 \\C_Brown
216 \\C_Cyan
217 \\C_DarkGray
218 \\C_Green
219 \\C_LightBlue
220 \\C_LightCyan
221 \\C_LightGray
222 \\C_LightGreen
223 \\C_LightPurple
224 \\C_LightRed
225 \\C_Purple
226 \\C_Red
227 \\C_White
228 \\C_Yellow
229 \\C_Normal - Stop coloring, defaults to your terminal settings.
230 """
231 pass
232
233 # Configure a few things. Much of this is fairly hackish, since IPython
234 # doesn't really expose a clean API for it. Be careful if you start making
235 # many modifications here.
236
237 print """\
238 Welcome to pysh, a set of extensions to IPython for shell usage.
239 help(pysh) -> help on the installed shell extensions and syntax.
240 """
241
242 # Set the 'cd' command to quiet mode, a more shell-like behavior
243 __IPYTHON__.default_option('cd','-q')
244
245 # Load all of $PATH as aliases
246 if os.name == 'posix':
247 # %rehash is very fast, but it doesn't check for executability, it simply
248 # dumps everything in $PATH as an alias. Use rehashx if you want more
249 # checks.
250 __IPYTHON__.magic_rehash()
251 else:
252 # Windows users: the list of extensions considered executable is read from
253 # the environment variable 'pathext'. If this is undefined, IPython
254 # defaults to EXE, COM and BAT.
255 # %rehashx is the one which does extension analysis, at the cost of
256 # being much slower than %rehash.
257 __IPYTHON__.magic_rehashx()
258
259 # Remove %sc,%sx if present as aliases
260 __IPYTHON__.magic_unalias('sc')
261 __IPYTHON__.magic_unalias('sx')
262
263 # We need different criteria for line-splitting, so that aliases such as
264 # 'gnome-terminal' are interpreted as a single alias instead of variable
265 # 'gnome' minus variable 'terminal'.
266 import re
267 __IPYTHON__.line_split = re.compile(r'^(\s*)([\?\w\.\-\+]+\w*\s*)(\(?.*$)')
268
269 # Namespace cleanup
270 del re
@@ -0,0 +1,91 b''
1 # -*- coding: utf-8 -*-
2 """Modified input prompt for entering text with >>> or ... at the start.
3
4 We define a special input line filter to allow typing lines which begin with
5 '>>> ' or '... '. These two strings, if present at the start of the input
6 line, are stripped. This allows for direct pasting of code from examples such
7 as those available in the standard Python tutorial.
8
9 Normally pasting such code is one chunk is impossible because of the
10 extraneous >>> and ..., requiring one to do a line by line paste with careful
11 removal of those characters. This module allows pasting that kind of
12 multi-line examples in one pass.
13
14 Here is an 'screenshot' of a section of the tutorial pasted into IPython with
15 this feature enabled:
16
17 In [1]: >>> def fib2(n): # return Fibonacci series up to n
18 ...: ... '''Return a list containing the Fibonacci series up to n.'''
19 ...: ... result = []
20 ...: ... a, b = 0, 1
21 ...: ... while b < n:
22 ...: ... result.append(b) # see below
23 ...: ... a, b = b, a+b
24 ...: ... return result
25 ...:
26
27 In [2]: fib2(10)
28 Out[2]: [1, 1, 2, 3, 5, 8]
29
30 The >>> and ... are stripped from the input so that the python interpreter
31 only sees the real part of the code.
32
33 All other input is processed normally.
34 """
35 #*****************************************************************************
36 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
37 #
38 # Distributed under the terms of the BSD License. The full license is in
39 # the file COPYING, distributed as part of this software.
40 #*****************************************************************************
41
42 from IPython import Release
43 __author__ = '%s <%s>' % Release.authors['Fernando']
44 __license__ = Release.license
45
46 # This file is an example of how to modify IPython's line-processing behavior
47 # without touching the internal code. We'll define an alternate pre-processing
48 # stage which allows a special form of input (which is invalid Python syntax)
49 # for certain quantities, rewrites a line of proper Python in those cases, and
50 # then passes it off to IPython's normal processor for further work.
51
52 # With this kind of customization, IPython can be adapted for many
53 # special-purpose scenarios providing alternate input syntaxes.
54
55 # This file can be imported like a regular module.
56
57 # IPython has a prefilter() function that analyzes each input line. We redefine
58 # it here to first pre-process certain forms of input
59
60 # The prototype of any alternate prefilter must be like this one (the name
61 # doesn't matter):
62 # - line is a string containing the user input line.
63 # - continuation is a parameter which tells us if we are processing a first line of
64 # user input or the second or higher of a multi-line statement.
65
66 def prefilter_paste(self,line,continuation):
67 """Alternate prefilter for input of pasted code from an interpreter.
68 """
69
70 from re import match
71
72 if match(r'^>>> |^\.\.\. ',line):
73 # In the end, always call the default IPython _prefilter() function.
74 # Note that self must be passed explicitly, b/c we're calling the
75 # unbound class method (since this method will overwrite the instance
76 # prefilter())
77 return self._prefilter(line[4:],continuation)
78 elif line.strip() == '...':
79 return self._prefilter('',continuation)
80 else:
81 return self._prefilter(line,continuation)
82
83 # Rebind this to be the new IPython prefilter:
84 from IPython.iplib import InteractiveShell
85 InteractiveShell.prefilter = prefilter_paste
86
87 # Clean up the namespace.
88 del InteractiveShell,prefilter_paste
89
90 # Just a heads up at the console
91 print '*** Pasting of code with ">>>" or "..." has been enabled.'
@@ -0,0 +1,83 b''
1 # -*- coding: utf-8 -*-
2 """Modified input prompt for entering quantities with units.
3
4 Modify the behavior of the interactive interpreter to allow direct input of
5 quantities with units without having to make a function call.
6
7 Now the following forms are accepted:
8
9 x = 4 m
10 y = -.45e3 m/s
11 g = 9.8 m/s**2
12 a = 2.3 m/s^2 # ^ -> ** automatically
13
14 All other input is processed normally.
15 """
16 #*****************************************************************************
17 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
18 #
19 # Distributed under the terms of the BSD License. The full license is in
20 # the file COPYING, distributed as part of this software.
21 #*****************************************************************************
22
23 from IPython import Release
24 __author__ = '%s <%s>' % Release.authors['Fernando']
25 __license__ = Release.license
26
27 # This file is an example of how to modify IPython's line-processing behavior
28 # without touching the internal code. We'll define an alternate pre-processing
29 # stage which allows a special form of input (which is invalid Python syntax)
30 # for certain quantities, rewrites a line of proper Python in those cases, and
31 # then passes it off to IPython's normal processor for further work.
32
33 # With this kind of customization, IPython can be adapted for many
34 # special-purpose scenarios providing alternate input syntaxes.
35
36 # This file can be imported like a regular module.
37
38 # IPython has a prefilter() function that analyzes each input line. We redefine
39 # it here to first pre-process certain forms of input
40
41 # The prototype of any alternate prefilter must be like this one (the name
42 # doesn't matter):
43 # - line is a string containing the user input line.
44 # - continuation is a parameter which tells us if we are processing a first line of
45 # user input or the second or higher of a multi-line statement.
46
47 def prefilter_PQ(self,line,continuation):
48 """Alternate prefilter for input of PhysicalQuantityInteractive objects.
49
50 This assumes that the function PhysicalQuantityInteractive() has been
51 imported."""
52
53 from re import match
54 from IPython.iplib import InteractiveShell
55
56 # This regexp is what does the real work
57 unit_split = match(r'\s*(\w+)\s*=\s*(-?\d*\.?\d*[eE]?-?\d*)\s+([a-zA-Z].*)',
58 line)
59
60 # If special input was ecnountered, process it:
61 if unit_split:
62 var,val,units = unit_split.groups()
63 if var and val and units:
64 units = units.replace('^','**')
65 # Now a valid line needs to be constructed for IPython to process:
66 line = var +" = PhysicalQuantityInteractive(" + val + ", '" + \
67 units + "')"
68 #print 'New line:',line # dbg
69
70 # In the end, always call the default IPython _prefilter() function. Note
71 # that self must be passed explicitly, b/c we're calling the unbound class
72 # method (since this method will overwrite the instance prefilter())
73 return InteractiveShell._prefilter(self,line,continuation)
74
75 # Rebind this to be the new IPython prefilter:
76 from IPython.iplib import InteractiveShell
77 InteractiveShell.prefilter = prefilter_PQ
78
79 # Clean up the namespace.
80 del InteractiveShell,prefilter_PQ
81
82 # Just a heads up at the console
83 print '*** Simplified input for physical quantities enabled.'
@@ -0,0 +1,88 b''
1 # -*- coding: utf-8 -*-
2 """Modify the PhysicalQuantities class for more convenient interactive use.
3
4 Also redefine some math functions to operate on PhysQties with no need for
5 special method syntax. This just means moving them out to the global
6 namespace.
7
8 This module should always be loaded *after* math or Numeric, so it can
9 overwrite math functions with the versions that handle units."""
10
11 #*****************************************************************************
12 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
17
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
21
22 from Scientific.Physics.PhysicalQuantities import PhysicalQuantity
23
24 # This code can be set up to work with Numeric or with math for providing the
25 # mathematical functions. Uncomment the one you prefer to use below.
26
27 # If you use math, sin(x) won't work for x an array, only float or PhysQty
28 import math
29
30 # If you use Numeric, sin(x) works for x a float, PhysQty an array.
31 #import Numeric as math
32
33 class PhysicalQuantityFunction:
34 """Generic function wrapper for PhysicalQuantity instances.
35
36 Calls functions from either the math library or the instance's methods as
37 required. Allows using sin(theta) or sqrt(v**2) syntax irrespective of
38 whether theta is a pure number or a PhysicalQuantity.
39
40 This is *slow*. It's meant for convenient interactive use, not for
41 speed."""
42
43 def __init__(self,name):
44 self.name = name
45
46 def __call__(self,x):
47 if isinstance(x,PhysicalQuantity):
48 return PhysicalQuantity.__dict__[self.name](x)
49 else:
50 return math.__dict__[self.name](x)
51
52 class PhysicalQuantityInteractive(PhysicalQuantity):
53 """Physical quantity with units - modified for Interactive use.
54
55 Basically, the __str__ and __repr__ methods have been swapped for more
56 convenient interactive use. Powers are shown as ^ instead of ** and only 4
57 significant figures are shown.
58
59 Also adds the following aliases for commonly used methods:
60 b = PhysicalQuantity.inBaseUnits
61 u = PhysicalQuantity.inUnitsOf
62
63 These are useful when doing a lot of interactive calculations.
64 """
65
66 # shorthands for the most useful unit conversions
67 b = PhysicalQuantity.inBaseUnits # so you can just type x.b to get base units
68 u = PhysicalQuantity.inUnitsOf
69
70 # This can be done, but it can get dangerous when coupled with IPython's
71 # auto-calling. Everything ends up shown in baseunits and things like x*2
72 # get automatically converted to k(*2), which doesn't work.
73 # Probably not a good idea in general...
74 #__call__ = b
75
76 def __str__(self):
77 return PhysicalQuantity.__repr__(self)
78
79 def __repr__(self):
80 value = '%.4G' % self.value
81 units = self.unit.name().replace('**','^')
82 return value + ' ' + units
83
84 # implement the methods defined in PhysicalQuantity as PhysicalQuantityFunctions
85 sin = PhysicalQuantityFunction('sin')
86 cos = PhysicalQuantityFunction('cos')
87 tan = PhysicalQuantityFunction('tan')
88 sqrt = PhysicalQuantityFunction('sqrt')
@@ -0,0 +1,13 b''
1 # -*- coding: utf-8 -*-
2 """This directory is meant for special-purpose extensions to IPython.
3
4 This can include things which alter the syntax processing stage (see
5 PhysicalQ_Input for an example of how to do this).
6
7 Any file located here can be called with an 'execfile =' option as
8
9 execfile = Extensions/filename.py
10
11 since the IPython directory itself is already part of the search path for
12 files listed as 'execfile ='.
13 """
@@ -0,0 +1,41 b''
1 # -*- coding: utf-8 -*-
2 """
3 Extension for printing Numeric Arrays in flexible ways.
4 """
5
6 def num_display(self,arg):
7 """Display method for printing which treats Numeric arrays specially.
8 """
9
10 # Non-numpy variables are printed using the system default
11 if type(arg) != ArrayType:
12 self._display(arg)
13 return
14 # Otherwise, we do work.
15 format = __IPYTHON__.runtime_rc.numarray_print_format
16 print 'NumPy array, format:',format
17 # Here is where all the printing logic needs to be implemented
18 print arg # nothing yet :)
19
20
21 def magic_format(self,parameter_s=''):
22 """Specifies format of numerical output.
23
24 This command is similar to Ocave's format command.
25 """
26
27 valid_formats = ['long','short']
28
29 if parameter_s in valid_formats:
30 self.runtime_rc.numarray_print_format = parameter_s
31 print 'Numeric output format is now:',parameter_s
32 else:
33 print 'Invalid format:',parameter_s
34 print 'Valid formats:',valid_formats
35
36 # setup default format
37 __IPYTHON__.runtime_rc.numarray_print_format = 'long'
38
39 # Bind our new functions to the interpreter
40 __IPYTHON__.__class__.magic_format = magic_format
41 __IPYTHON__.hooks.display = num_display
@@ -0,0 +1,48 b''
1 # -*- coding: utf-8 -*-
2 """
3 Class which mimics a module.
4
5 Needed to allow pickle to correctly resolve namespaces during IPython
6 sessions.
7
8 $Id: FakeModule.py 410 2004-11-04 07:58:17Z fperez $"""
9
10 #*****************************************************************************
11 # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
12 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
16
17 class FakeModule:
18 """Simple class with attribute access to fake a module.
19
20 This is not meant to replace a module, but to allow inserting a fake
21 module in sys.modules so that systems which rely on run-time module
22 importing (like shelve and pickle) work correctly in interactive IPython
23 sessions.
24
25 Do NOT use this code for anything other than this IPython private hack."""
26
27 def __init__(self,adict):
28
29 # It seems pydoc (and perhaps others) needs any module instance to
30 # implement a __nonzero__ method, so we add it if missing:
31 if '__nonzero__' not in adict:
32 def __nonzero__():
33 return 1
34 adict['__nonzero__'] = __nonzero__
35
36 self.__dict__ = adict
37
38 def __getattr__(self,key):
39 try:
40 return self.__dict__[key]
41 except KeyError, e:
42 raise AttributeError("FakeModule object has no attribute %s" % e)
43
44 def __str__(self):
45 return "<IPython.FakeModule instance>"
46
47 def __repr__(self):
48 return str(self)
@@ -0,0 +1,198 b''
1 # -*- coding: utf-8 -*-
2 """Word completion for GNU readline 2.0.
3
4 ---------------------------------------------------------------------------
5 NOTE: This version is a re-implementation of rlcompleter with selectable
6 namespace.
7
8 The problem with rlcompleter is that it's hardwired to work with
9 __main__.__dict__, and in some cases one may have 'sandboxed' namespaces. So
10 this class is a ripoff of rlcompleter, with the namespace to work in as an
11 optional parameter.
12
13 This class can be used just like rlcompleter, but the Completer class now has
14 a constructor with the optional 'namespace' parameter.
15
16 A patch has been submitted to Python@sourceforge for these changes to go in
17 the standard Python distribution.
18
19 The patch went in for Python 2.3. Once IPython drops support for Python 2.2,
20 this file can be significantly reduced.
21 ---------------------------------------------------------------------------
22
23 Original rlcompleter documentation:
24
25 This requires the latest extension to the readline module (the
26 completes keywords, built-ins and globals in __main__; when completing
27 NAME.NAME..., it evaluates (!) the expression up to the last dot and
28 completes its attributes.
29
30 It's very cool to do "import string" type "string.", hit the
31 completion key (twice), and see the list of names defined by the
32 string module!
33
34 Tip: to use the tab key as the completion key, call
35
36 readline.parse_and_bind("tab: complete")
37
38 Notes:
39
40 - Exceptions raised by the completer function are *ignored* (and
41 generally cause the completion to fail). This is a feature -- since
42 readline sets the tty device in raw (or cbreak) mode, printing a
43 traceback wouldn't work well without some complicated hoopla to save,
44 reset and restore the tty state.
45
46 - The evaluation of the NAME.NAME... form may cause arbitrary
47 application defined code to be executed if an object with a
48 __getattr__ hook is found. Since it is the responsibility of the
49 application (or the user) to enable this feature, I consider this an
50 acceptable risk. More complicated expressions (e.g. function calls or
51 indexing operations) are *not* evaluated.
52
53 - GNU readline is also used by the built-in functions input() and
54 raw_input(), and thus these also benefit/suffer from the completer
55 features. Clearly an interactive application can benefit by
56 specifying its own completer function and using raw_input() for all
57 its input.
58
59 - When the original stdin is not a tty device, GNU readline is never
60 used, and this module (and the readline module) are silently inactive.
61
62 """
63
64 #*****************************************************************************
65 #
66 # Since this file is essentially a minimally modified copy of the rlcompleter
67 # module which is part of the standard Python distribution, I assume that the
68 # proper procedure is to maintain its copyright as belonging to the Python
69 # Software Foundation:
70 #
71 # Copyright (C) 2001 Python Software Foundation, www.python.org
72 #
73 # Distributed under the terms of the Python Software Foundation license.
74 #
75 # Full text available at:
76 #
77 # http://www.python.org/2.1/license.html
78 #
79 #*****************************************************************************
80
81 import readline
82 import __builtin__
83 import __main__
84
85 __all__ = ["Completer"]
86
87 class Completer:
88 def __init__(self, namespace = None):
89 """Create a new completer for the command line.
90
91 Completer([namespace]) -> completer instance.
92
93 If unspecified, the default namespace where completions are performed
94 is __main__ (technically, __main__.__dict__). Namespaces should be
95 given as dictionaries.
96
97 Completer instances should be used as the completion mechanism of
98 readline via the set_completer() call:
99
100 readline.set_completer(Completer(my_namespace).complete)
101 """
102
103 if namespace and type(namespace) != type({}):
104 raise TypeError,'namespace must be a dictionary'
105
106 # Don't bind to namespace quite yet, but flag whether the user wants a
107 # specific namespace or to use __main__.__dict__. This will allow us
108 # to bind to __main__.__dict__ at completion time, not now.
109 if namespace is None:
110 self.use_main_ns = 1
111 else:
112 self.use_main_ns = 0
113 self.namespace = namespace
114
115 def complete(self, text, state):
116 """Return the next possible completion for 'text'.
117
118 This is called successively with state == 0, 1, 2, ... until it
119 returns None. The completion should begin with 'text'.
120
121 """
122 if self.use_main_ns:
123 self.namespace = __main__.__dict__
124
125 if state == 0:
126 if "." in text:
127 self.matches = self.attr_matches(text)
128 else:
129 self.matches = self.global_matches(text)
130 try:
131 return self.matches[state]
132 except IndexError:
133 return None
134
135 def global_matches(self, text):
136 """Compute matches when text is a simple name.
137
138 Return a list of all keywords, built-in functions and names currently
139 defined in self.namespace that match.
140
141 """
142 import keyword
143 matches = []
144 n = len(text)
145 for list in [keyword.kwlist,
146 __builtin__.__dict__.keys(),
147 self.namespace.keys()]:
148 for word in list:
149 if word[:n] == text and word != "__builtins__":
150 matches.append(word)
151 return matches
152
153 def attr_matches(self, text):
154 """Compute matches when text contains a dot.
155
156 Assuming the text is of the form NAME.NAME....[NAME], and is
157 evaluatable in self.namespace, it will be evaluated and its attributes
158 (as revealed by dir()) are used as possible completions. (For class
159 instances, class members are are also considered.)
160
161 WARNING: this can still invoke arbitrary C code, if an object
162 with a __getattr__ hook is evaluated.
163
164 """
165 import re
166
167 # Another option, seems to work great. Catches things like ''.<tab>
168 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
169
170 if not m:
171 return []
172 expr, attr = m.group(1, 3)
173 object = eval(expr, self.namespace)
174 words = dir(object)
175 if hasattr(object,'__class__'):
176 words.append('__class__')
177 words.extend(get_class_members(object.__class__))
178 n = len(attr)
179 matches = []
180 for word in words:
181 try:
182 if word[:n] == attr and word != "__builtins__":
183 matches.append("%s.%s" % (expr, word))
184 except:
185 # some badly behaved objects pollute dir() with non-strings,
186 # which cause the completion to fail. This way we skip the
187 # bad entries and can still continue processing the others.
188 pass
189 return matches
190
191 def get_class_members(klass):
192 ret = dir(klass)
193 if hasattr(klass,'__bases__'):
194 for base in klass.__bases__:
195 ret.extend(get_class_members(base))
196 return ret
197
198 readline.set_completer(Completer().complete)
This diff has been collapsed as it changes many lines, (655 lines changed) Show them Hide them
@@ -0,0 +1,655 b''
1 # -*- coding: utf-8 -*-
2 """Improved replacement for the Gnuplot.Gnuplot class.
3
4 This module imports Gnuplot and replaces some of its functionality with
5 improved versions. They add better handling of arrays for plotting and more
6 convenient PostScript generation, plus some fixes for hardcopy().
7
8 It also adds a convenient plot2 method for plotting dictionaries and
9 lists/tuples of arrays.
10
11 This module is meant to be used as a drop-in replacement to the original
12 Gnuplot, so it should be safe to do:
13
14 import IPython.Gnuplot2 as Gnuplot
15
16 $Id: Gnuplot2.py 392 2004-10-09 22:01:51Z fperez $"""
17
18 import string,os,time,types
19 import cStringIO
20 import sys
21 import tempfile
22 import Numeric
23 import Gnuplot as Gnuplot_ori
24 from IPython.genutils import popkey,xsys
25
26 # needed by hardcopy():
27 gp = Gnuplot_ori.gp
28
29 # Patch for Gnuplot.py 1.6 compatibility.
30 # Thanks to Hayden Callow <h.callow@elec.canterbury.ac.nz>
31 try:
32 OptionException = Gnuplot_ori.PlotItems.OptionException
33 except AttributeError:
34 OptionException = Gnuplot_ori.Errors.OptionError
35
36 # exhibit a similar interface to Gnuplot so it can be somewhat drop-in
37 Data = Gnuplot_ori.Data
38 Func = Gnuplot_ori.Func
39 GridData = Gnuplot_ori.GridData
40 PlotItem = Gnuplot_ori.PlotItem
41 PlotItems = Gnuplot_ori.PlotItems
42
43 # Modify some of Gnuplot's functions with improved versions (or bugfixed, in
44 # hardcopy's case). In order to preserve the docstrings at runtime, I've
45 # copied them from the original code.
46
47 # After some significant changes in v 1.7 of Gnuplot.py, we need to do a bit
48 # of version checking.
49
50 if Gnuplot_ori.__version__ <= '1.6':
51 _BaseFileItem = PlotItems.File
52 _BaseTempFileItem = PlotItems.TempFile
53
54 # Fix the File class to add the 'index' option for Gnuplot versions < 1.7
55 class File(_BaseFileItem):
56
57 _option_list = _BaseFileItem._option_list.copy()
58 _option_list.update({
59 'index' : lambda self, index: self.set_option_index(index),
60 })
61
62 # A new initializer is needed b/c we want to add a modified
63 # _option_sequence list which includes 'index' in the right place.
64 def __init__(self,*args,**kw):
65 self._option_sequence = ['binary', 'index', 'using', 'smooth', 'axes',
66 'title', 'with']
67
68 _BaseFileItem.__init__(self,*args,**kw)
69
70 # Let's fix the constructor docstring
71 __newdoc = \
72 """Additional Keyword arguments added by IPython:
73
74 'index=<int>' -- similar to the `index` keyword in Gnuplot.
75 This allows only some of the datasets in a file to be
76 plotted. Datasets within a file are assumed to be separated
77 by _pairs_ of blank lines, and the first one is numbered as
78 0 (similar to C/Python usage)."""
79 __init__.__doc__ = PlotItems.File.__init__.__doc__ + __newdoc
80
81 def set_option_index(self, index):
82 if index is None:
83 self.clear_option('index')
84 elif type(index) in [type(''), type(1)]:
85 self._options['index'] = (index, 'index %s' % index)
86 elif type(index) is type(()):
87 self._options['index'] = (index,'index %s' %
88 string.join(map(repr, index), ':'))
89 else:
90 raise OptionException('index=%s' % (index,))
91
92 # We need a FileClass with a different name from 'File', which is a
93 # factory function in 1.7, so that our String class can subclass FileClass
94 # in any version.
95 _FileClass = File
96
97 else: # Gnuplot.py version 1.7 and greater
98 _FileClass = _BaseFileItem = PlotItems._FileItem
99 _BaseTempFileItem = PlotItems._TempFileItem
100 File = PlotItems.File
101
102 # Now, we can add our generic code which is version independent
103
104 # First some useful utilities
105 def eps_fix_bbox(fname):
106 """Fix the bounding box of an eps file by running ps2eps on it.
107
108 If its name ends in .eps, the original file is removed.
109
110 This is particularly useful for plots made by Gnuplot with square aspect
111 ratio: there is a bug in Gnuplot which makes it generate a bounding box
112 which is far wider than the actual plot.
113
114 This function assumes that ps2eps is installed in your system."""
115
116 # note: ps2ps and eps2eps do NOT work, ONLY ps2eps works correctly. The
117 # others make output with bitmapped fonts, which looks horrible.
118 print 'Fixing eps file: <%s>' % fname
119 xsys('ps2eps -f -q -l %s' % fname)
120 if fname.endswith('.eps'):
121 os.rename(fname+'.eps',fname)
122
123 def is_list1d(x,containers = [types.ListType,types.TupleType]):
124 """Returns true if x appears to be a 1d list/tuple/array.
125
126 The heuristics are: identify Numeric arrays, or lists/tuples whose first
127 element is not itself a list/tuple. This way zipped lists should work like
128 the original Gnuplot. There's no inexpensive way to know if a list doesn't
129 have a composite object after its first element, so that kind of input
130 will produce an error. But it should work well in most cases.
131 """
132 x_type = type(x)
133
134 return x_type == Numeric.ArrayType and len(x.shape)==1 or \
135 (x_type in containers and
136 type(x[0]) not in containers + [Numeric.ArrayType])
137
138 def zip_items(items,titles=None):
139 """zip together neighboring 1-d arrays, and zip standalone ones
140 with their index. Leave other plot items alone."""
141
142 class StandaloneItem(Exception): pass
143
144 def get_titles(titles):
145 """Return the next title and the input titles array.
146
147 The input array may be changed to None when no titles are left to
148 prevent extra unnecessary calls to this function."""
149
150 try:
151 title = titles[tit_ct[0]] # tit_ct[0] is in zip_items'scope
152 except IndexError:
153 titles = None # so we don't enter again
154 title = None
155 else:
156 tit_ct[0] += 1
157 return title,titles
158
159 new_items = []
160
161 if titles:
162 # Initialize counter. It was put in a list as a hack to allow the
163 # nested get_titles to modify it without raising a NameError.
164 tit_ct = [0]
165
166 n = 0 # this loop needs to be done by hand
167 while n < len(items):
168 item = items[n]
169 try:
170 if is_list1d(item):
171 if n==len(items)-1: # last in list
172 raise StandaloneItem
173 else: # check the next item and zip together if needed
174 next_item = items[n+1]
175 if next_item is None:
176 n += 1
177 raise StandaloneItem
178 elif is_list1d(next_item):
179 # this would be best done with an iterator
180 if titles:
181 title,titles = get_titles(titles)
182 else:
183 title = None
184 new_items.append(Data(zip(item,next_item),
185 title=title))
186 n += 1 # avoid double-inclusion of next item
187 else: # can't zip with next, zip with own index list
188 raise StandaloneItem
189 else: # not 1-d array
190 new_items.append(item)
191 except StandaloneItem:
192 if titles:
193 title,titles = get_titles(titles)
194 else:
195 title = None
196 new_items.append(Data(zip(range(len(item)),item),title=title))
197 except AttributeError:
198 new_items.append(item)
199 n+=1
200
201 return new_items
202
203 # And some classes with enhanced functionality.
204 class String(_FileClass):
205 """Make a PlotItem from data in a string with the same format as a File.
206
207 This allows writing data directly inside python scripts using the exact
208 same format and manipulation options which would be used for external
209 files."""
210
211 def __init__(self, data_str, **keyw):
212 """Construct a String object.
213
214 <data_str> is a string formatted exactly like a valid Gnuplot data
215 file would be. All options from the File constructor are valid here.
216
217 Warning: when used for interactive plotting in scripts which exit
218 immediately, you may get an error because the temporary file used to
219 hold the string data was deleted before Gnuplot had a chance to see
220 it. You can work around this problem by putting a raw_input() call at
221 the end of the script.
222
223 This problem does not appear when generating PostScript output, only
224 with Gnuplot windows."""
225
226 self.tmpfile = _BaseTempFileItem()
227 tmpfile = file(self.tmpfile.filename,'w')
228 tmpfile.write(data_str)
229 _BaseFileItem.__init__(self,self.tmpfile,**keyw)
230
231
232 class Gnuplot(Gnuplot_ori.Gnuplot):
233 """Improved Gnuplot class.
234
235 Enhancements: better plot,replot and hardcopy methods. New methods for
236 quick range setting.
237 """
238
239 def xrange(self,min='*',max='*'):
240 """Set xrange. If min/max is omitted, it is set to '*' (auto).
241
242 Note that this is different from the regular Gnuplot behavior, where
243 an unspecified limit means no change. Here any unspecified limit is
244 set to autoscaling, allowing these functions to be used for full
245 autoscaling when called with no arguments.
246
247 To preserve one limit's current value while changing the other, an
248 explicit '' argument must be given as the limit to be kept.
249
250 Similar functions exist for [y{2}z{2}rtuv]range."""
251
252 self('set xrange [%s:%s]' % (min,max))
253
254 def yrange(self,min='*',max='*'):
255 self('set yrange [%s:%s]' % (min,max))
256
257 def zrange(self,min='*',max='*'):
258 self('set zrange [%s:%s]' % (min,max))
259
260 def x2range(self,min='*',max='*'):
261 self('set xrange [%s:%s]' % (min,max))
262
263 def y2range(self,min='*',max='*'):
264 self('set yrange [%s:%s]' % (min,max))
265
266 def z2range(self,min='*',max='*'):
267 self('set zrange [%s:%s]' % (min,max))
268
269 def rrange(self,min='*',max='*'):
270 self('set rrange [%s:%s]' % (min,max))
271
272 def trange(self,min='*',max='*'):
273 self('set trange [%s:%s]' % (min,max))
274
275 def urange(self,min='*',max='*'):
276 self('set urange [%s:%s]' % (min,max))
277
278 def vrange(self,min='*',max='*'):
279 self('set vrange [%s:%s]' % (min,max))
280
281 def set_ps(self,option):
282 """Set an option for the PostScript terminal and reset default term."""
283
284 self('set terminal postscript %s ' % option)
285 self('set terminal %s' % gp.GnuplotOpts.default_term)
286
287 def __plot_ps(self, plot_method,*items, **keyw):
288 """Wrapper for plot/splot/replot, with processing of hardcopy options.
289
290 For internal use only."""
291
292 # Filter out PostScript options which will crash the normal plot/replot
293 psargs = {'filename':None,
294 'mode':None,
295 'eps':None,
296 'enhanced':None,
297 'color':None,
298 'solid':None,
299 'duplexing':None,
300 'fontname':None,
301 'fontsize':None,
302 'debug':0 }
303
304 for k in psargs.keys():
305 if keyw.has_key(k):
306 psargs[k] = keyw[k]
307 del keyw[k]
308
309 # Filter out other options the original plot doesn't know
310 hardcopy = popkey(keyw,'hardcopy',psargs['filename'] is not None)
311 titles = popkey(keyw,'titles',0)
312
313 # the filename keyword should control hardcopy generation, this is an
314 # override switch only which needs to be explicitly set to zero
315 if hardcopy:
316 if psargs['filename'] is None:
317 raise ValueError, \
318 'If you request hardcopy, you must give a filename.'
319
320 # set null output so nothing goes to screen. hardcopy() restores output
321 self('set term dumb')
322 # I don't know how to prevent screen output in Windows
323 if os.name == 'posix':
324 self('set output "/dev/null"')
325
326 new_items = zip_items(items,titles)
327 # plot_method is either plot or replot from the original Gnuplot class:
328 plot_method(self,*new_items,**keyw)
329
330 # Do hardcopy if requested
331 if hardcopy:
332 if psargs['filename'].endswith('.eps'):
333 psargs['eps'] = 1
334 self.hardcopy(**psargs)
335
336 def plot(self, *items, **keyw):
337 """Draw a new plot.
338
339 Clear the current plot and create a new 2-d plot containing
340 the specified items. Each arguments should be of the
341 following types:
342
343 'PlotItem' (e.g., 'Data', 'File', 'Func') -- This is the most
344 flexible way to call plot because the PlotItems can
345 contain suboptions. Moreover, PlotItems can be saved to
346 variables so that their lifetime is longer than one plot
347 command; thus they can be replotted with minimal overhead.
348
349 'string' (e.g., 'sin(x)') -- The string is interpreted as
350 'Func(string)' (a function that is computed by gnuplot).
351
352 Anything else -- The object, which should be convertible to an
353 array, is passed to the 'Data' constructor, and thus
354 plotted as data. If the conversion fails, an exception is
355 raised.
356
357
358 This is a modified version of plot(). Compared to the original in
359 Gnuplot.py, this version has several enhancements, listed below.
360
361
362 Modifications to the input arguments
363 ------------------------------------
364
365 (1-d array means Numeric array, list or tuple):
366
367 (i) Any 1-d array which is NOT followed by another 1-d array, is
368 automatically zipped with range(len(array_1d)). Typing g.plot(y) will
369 plot y against its indices.
370
371 (ii) If two 1-d arrays are contiguous in the argument list, they are
372 automatically zipped together. So g.plot(x,y) plots y vs. x, and
373 g.plot(x1,y1,x2,y2) plots y1 vs. x1 and y2 vs. x2.
374
375 (iii) Any 1-d array which is followed by None is automatically zipped
376 with range(len(array_1d)). In this form, typing g.plot(y1,None,y2)
377 will plot both y1 and y2 against their respective indices (and NOT
378 versus one another). The None prevents zipping y1 and y2 together, and
379 since y2 is unpaired it is automatically zipped to its indices by (i)
380
381 (iv) Any other arguments which don't match these cases are left alone and
382 passed to the code below.
383
384 For lists or tuples, the heuristics used to determine whether they are
385 in fact 1-d is fairly simplistic: their first element is checked, and
386 if it is not a list or tuple itself, it is assumed that the whole
387 object is one-dimensional.
388
389 An additional optional keyword 'titles' has been added: it must be a
390 list of strings to be used as labels for the individual plots which
391 are NOT PlotItem objects (since those objects carry their own labels
392 within).
393
394
395 PostScript generation
396 ---------------------
397
398 This version of plot() also handles automatically the production of
399 PostScript output. The main options are (given as keyword arguments):
400
401 - filename: a string, typically ending in .eps. If given, the plot is
402 sent to this file in PostScript format.
403
404 - hardcopy: this can be set to 0 to override 'filename'. It does not
405 need to be given to produce PostScript, its purpose is to allow
406 switching PostScript output off globally in scripts without having to
407 manually change 'filename' values in multiple calls.
408
409 All other keywords accepted by Gnuplot.hardcopy() are transparently
410 passed, and safely ignored if output is sent to the screen instead of
411 PostScript.
412
413 For example:
414
415 In [1]: x=frange(0,2*pi,npts=100)
416
417 Generate a plot in file 'sin.eps':
418
419 In [2]: plot(x,sin(x),filename = 'sin.eps')
420
421 Plot to screen instead, without having to change the filename:
422
423 In [3]: plot(x,sin(x),filename = 'sin.eps',hardcopy=0)
424
425 Pass the 'color=0' option to hardcopy for monochrome output:
426
427 In [4]: plot(x,sin(x),filename = 'sin.eps',color=0)
428
429 PostScript generation through plot() is useful mainly for scripting
430 uses where you are not interested in interactive plotting. For
431 interactive use, the hardcopy() function is typically more convenient:
432
433 In [5]: plot(x,sin(x))
434
435 In [6]: hardcopy('sin.eps') """
436
437 self.__plot_ps(Gnuplot_ori.Gnuplot.plot,*items,**keyw)
438
439 def plot2(self,arg,**kw):
440 """Plot the entries of a dictionary or a list/tuple of arrays.
441
442 This simple utility calls plot() with a list of Gnuplot.Data objects
443 constructed either from the values of the input dictionary, or the entries
444 in it if it is a tuple or list. Each item gets labeled with the key/index
445 in the Gnuplot legend.
446
447 Each item is plotted by zipping it with a list of its indices.
448
449 Any keywords are passed directly to plot()."""
450
451 if hasattr(arg,'keys'):
452 keys = arg.keys()
453 keys.sort()
454 else:
455 keys = range(len(arg))
456
457 pitems = [Data(zip(range(len(arg[k])),arg[k]),title=`k`) for k in keys]
458 self.plot(*pitems,**kw)
459
460 def splot(self, *items, **keyw):
461 """Draw a new three-dimensional plot.
462
463 Clear the current plot and create a new 3-d plot containing
464 the specified items. Arguments can be of the following types:
465
466 'PlotItem' (e.g., 'Data', 'File', 'Func', 'GridData' ) -- This
467 is the most flexible way to call plot because the
468 PlotItems can contain suboptions. Moreover, PlotItems can
469 be saved to variables so that their lifetime is longer
470 than one plot command--thus they can be replotted with
471 minimal overhead.
472
473 'string' (e.g., 'sin(x*y)') -- The string is interpreted as a
474 'Func()' (a function that is computed by gnuplot).
475
476 Anything else -- The object is converted to a Data() item, and
477 thus plotted as data. Note that each data point should
478 normally have at least three values associated with it
479 (i.e., x, y, and z). If the conversion fails, an
480 exception is raised.
481
482 This is a modified version of splot(). Compared to the original in
483 Gnuplot.py, this version has several enhancements, listed in the
484 plot() documentation.
485 """
486
487 self.__plot_ps(Gnuplot_ori.Gnuplot.splot,*items,**keyw)
488
489 def replot(self, *items, **keyw):
490 """Replot the data, possibly adding new 'PlotItem's.
491
492 Replot the existing graph, using the items in the current
493 itemlist. If arguments are specified, they are interpreted as
494 additional items to be plotted alongside the existing items on
495 the same graph. See 'plot' for details.
496
497 If you want to replot to a postscript file, you MUST give the
498 'filename' keyword argument in each call to replot. The Gnuplot python
499 interface has no way of knowing that your previous call to
500 Gnuplot.plot() was meant for PostScript output."""
501
502 self.__plot_ps(Gnuplot_ori.Gnuplot.replot,*items,**keyw)
503
504 # The original hardcopy has a bug. See fix at the end. The rest of the code
505 # was lifted verbatim from the original, so that people using IPython get the
506 # benefits without having to manually patch Gnuplot.py
507 def hardcopy(self, filename=None,
508 mode=None,
509 eps=None,
510 enhanced=None,
511 color=None,
512 solid=None,
513 duplexing=None,
514 fontname=None,
515 fontsize=None,
516 debug = 0,
517 ):
518 """Create a hardcopy of the current plot.
519
520 Create a postscript hardcopy of the current plot to the
521 default printer (if configured) or to the specified filename.
522
523 Note that gnuplot remembers the postscript suboptions across
524 terminal changes. Therefore if you set, for example, color=1
525 for one hardcopy then the next hardcopy will also be color
526 unless you explicitly choose color=0. Alternately you can
527 force all of the options to their defaults by setting
528 mode='default'. I consider this to be a bug in gnuplot.
529
530 Keyword arguments:
531
532 'filename=<string>' -- if a filename is specified, save the
533 output in that file; otherwise print it immediately
534 using the 'default_lpr' configuration option. If the
535 filename ends in '.eps', EPS mode is automatically
536 selected (like manually specifying eps=1 or mode='eps').
537
538 'mode=<string>' -- set the postscript submode ('landscape',
539 'portrait', 'eps', or 'default'). The default is
540 to leave this option unspecified.
541
542 'eps=<bool>' -- shorthand for 'mode="eps"'; asks gnuplot to
543 generate encapsulated postscript.
544
545 'enhanced=<bool>' -- if set (the default), then generate
546 enhanced postscript, which allows extra features like
547 font-switching, superscripts, and subscripts in axis
548 labels. (Some old gnuplot versions do not support
549 enhanced postscript; if this is the case set
550 gp.GnuplotOpts.prefer_enhanced_postscript=None.)
551
552 'color=<bool>' -- if set, create a plot with color. Default
553 is to leave this option unchanged.
554
555 'solid=<bool>' -- if set, force lines to be solid (i.e., not
556 dashed).
557
558 'duplexing=<string>' -- set duplexing option ('defaultplex',
559 'simplex', or 'duplex'). Only request double-sided
560 printing if your printer can handle it. Actually this
561 option is probably meaningless since hardcopy() can only
562 print a single plot at a time.
563
564 'fontname=<string>' -- set the default font to <string>,
565 which must be a valid postscript font. The default is
566 to leave this option unspecified.
567
568 'fontsize=<double>' -- set the default font size, in
569 postscript points.
570
571 'debug=<bool>' -- print extra debugging information (useful if
572 your PostScript files are misteriously not being created).
573 """
574
575 if filename is None:
576 assert gp.GnuplotOpts.default_lpr is not None, \
577 OptionException('default_lpr is not set, so you can only '
578 'print to a file.')
579 filename = gp.GnuplotOpts.default_lpr
580 lpr_output = 1
581 else:
582 if filename.endswith('.eps'):
583 eps = 1
584 lpr_output = 0
585
586 # Be careful processing the options. If the user didn't
587 # request an option explicitly, do not specify it on the 'set
588 # terminal' line (don't even specify the default value for the
589 # option). This is to avoid confusing older versions of
590 # gnuplot that do not support all of these options. The
591 # exception is 'enhanced', which is just too useful to have to
592 # specify each time!
593
594 setterm = ['set', 'terminal', 'postscript']
595 if eps:
596 assert mode is None or mode=='eps', \
597 OptionException('eps option and mode are incompatible')
598 setterm.append('eps')
599 else:
600 if mode is not None:
601 assert mode in ['landscape', 'portrait', 'eps', 'default'], \
602 OptionException('illegal mode "%s"' % mode)
603 setterm.append(mode)
604 if enhanced is None:
605 enhanced = gp.GnuplotOpts.prefer_enhanced_postscript
606 if enhanced is not None:
607 if enhanced: setterm.append('enhanced')
608 else: setterm.append('noenhanced')
609 if color is not None:
610 if color: setterm.append('color')
611 else: setterm.append('monochrome')
612 if solid is not None:
613 if solid: setterm.append('solid')
614 else: setterm.append('dashed')
615 if duplexing is not None:
616 assert duplexing in ['defaultplex', 'simplex', 'duplex'], \
617 OptionException('illegal duplexing mode "%s"' % duplexing)
618 setterm.append(duplexing)
619 if fontname is not None:
620 setterm.append('"%s"' % fontname)
621 if fontsize is not None:
622 setterm.append('%s' % fontsize)
623
624 self(string.join(setterm))
625 self.set_string('output', filename)
626 # replot the current figure (to the printer):
627 self.refresh()
628
629 # fperez. Ugly kludge: often for some reason the file is NOT created
630 # and we must reissue the creation commands. I have no idea why!
631 if not lpr_output:
632 #print 'Hardcopy <%s>' % filename # dbg
633 maxtries = 20
634 delay = 0.1 # delay (in seconds) between print attempts
635 for i in range(maxtries):
636 time.sleep(0.05) # safety, very small delay
637 if os.path.isfile(filename):
638 if debug:
639 print 'Hardcopy to file <%s> success at attempt #%s.' \
640 % (filename,i+1)
641 break
642 time.sleep(delay)
643 # try again, issue all commands just in case
644 self(string.join(setterm))
645 self.set_string('output', filename)
646 self.refresh()
647 if not os.path.isfile(filename):
648 print >> sys.stderr,'ERROR: Tried %s times and failed to '\
649 'create hardcopy file `%s`' % (maxtries,filename)
650
651 # reset the terminal to its `default' setting:
652 self('set terminal %s' % gp.GnuplotOpts.default_term)
653 self.set_string('output')
654
655 #********************** End of file <Gnuplot2.py> ************************
@@ -0,0 +1,148 b''
1 # -*- coding: utf-8 -*-
2 """Interactive functions and magic functions for Gnuplot usage.
3
4 This requires the Gnuplot.py module for interfacing python with Gnuplot, which
5 can be downloaded from:
6
7 http://gnuplot-py.sourceforge.net/
8
9 See gphelp() below for details on the services offered by this module.
10
11 Inspired by a suggestion/request from Arnd Baecker.
12
13 $Id: GnuplotInteractive.py 389 2004-10-09 07:59:30Z fperez $"""
14
15 __all__ = ['Gnuplot','gp','gp_new','plot','plot2','splot','replot',
16 'hardcopy','gpdata','gpfile','gpstring','gpfunc','gpgrid',
17 'gphelp']
18
19 import IPython.GnuplotRuntime as GRun
20 from IPython.genutils import page,warn
21
22 # Set global names for interactive use
23 Gnuplot = GRun.Gnuplot
24 gp_new = GRun.gp_new
25 gp = GRun.gp
26 plot = gp.plot
27 plot2 = gp.plot2
28 splot = gp.splot
29 replot = gp.replot
30 hardcopy = gp.hardcopy
31
32 # Accessors for the main plot object constructors:
33 gpdata = Gnuplot.Data
34 gpfile = Gnuplot.File
35 gpstring = Gnuplot.String
36 gpfunc = Gnuplot.Func
37 gpgrid = Gnuplot.GridData
38
39 def gphelp():
40 """Print information about the Gnuplot facilities in IPython."""
41
42 page("""
43 IPython provides an interface to access the Gnuplot scientific plotting
44 system, in an environment similar to that of Mathematica or Matlab.
45
46 New top-level global objects
47 ----------------------------
48
49 Please see their respective docstrings for further details.
50
51 - gp: a running Gnuplot instance. You can access its methods as
52 gp.<method>. gp(`a string`) will execute the given string as if it had been
53 typed in an interactive gnuplot window.
54
55 - plot, splot, replot and hardcopy: aliases to the methods of the same name in
56 the global running Gnuplot instance gp. These allow you to simply type:
57
58 In [1]: plot(x,sin(x),title='Sin(x)') # assuming x is a Numeric array
59
60 and obtain a plot of sin(x) vs x with the title 'Sin(x)'.
61
62 - gp_new: a function which returns a new Gnuplot instance. This can be used to
63 have multiple Gnuplot instances running in your session to compare different
64 plots, each in a separate window.
65
66 - Gnuplot: alias to the Gnuplot2 module, an improved drop-in replacement for
67 the original Gnuplot.py. Gnuplot2 needs Gnuplot but redefines several of its
68 functions with improved versions (Gnuplot2 comes with IPython).
69
70 - gpdata, gpfile, gpstring, gpfunc, gpgrid: aliases to Gnuplot.Data,
71 Gnuplot.File, Gnuplot.String, Gnuplot.Func and Gnuplot.GridData
72 respectively. These functions create objects which can then be passed to the
73 plotting commands. See the Gnuplot.py documentation for details.
74
75 Keep in mind that all commands passed to a Gnuplot instance are executed in
76 the Gnuplot namespace, where no Python variables exist. For example, for
77 plotting sin(x) vs x as above, typing
78
79 In [2]: gp('plot x,sin(x)')
80
81 would not work. Instead, you would get the plot of BOTH the functions 'x' and
82 'sin(x)', since Gnuplot doesn't know about the 'x' Python array. The plot()
83 method lives in python and does know about these variables.
84
85
86 New magic functions
87 -------------------
88
89 %gpc: pass one command to Gnuplot and execute it or open a Gnuplot shell where
90 each line of input is executed.
91
92 %gp_set_default: reset the value of IPython's global Gnuplot instance.""")
93
94 # Code below is all for IPython use
95 # Define the magic functions for communicating with the above gnuplot instance.
96 def magic_gpc(self,parameter_s=''):
97 """Execute a gnuplot command or open a gnuplot shell.
98
99 Usage (omit the % if automagic is on). There are two ways to use it:
100
101 1) %gpc 'command' -> passes 'command' directly to the gnuplot instance.
102
103 2) %gpc -> will open up a prompt (gnuplot>>>) which takes input like the
104 standard gnuplot interactive prompt. If you need to type a multi-line
105 command, use \\ at the end of each intermediate line.
106
107 Upon exiting of the gnuplot sub-shell, you return to your IPython
108 session (the gnuplot sub-shell can be invoked as many times as needed).
109 """
110
111 if parameter_s.strip():
112 self.shell.gnuplot(parameter_s)
113 else:
114 self.shell.gnuplot.interact()
115
116 def magic_gp_set_default(self,parameter_s=''):
117 """Set the default gnuplot instance accessed by the %gp magic function.
118
119 %gp_set_default name
120
121 Call with the name of the new instance at the command line. If you want to
122 set this instance in your own code (using an embedded IPython, for
123 example), simply set the variable __IPYTHON__.gnuplot to your own gnuplot
124 instance object."""
125
126 gname = parameter_s.strip()
127 G = eval(gname,self.shell.user_ns)
128 self.shell.gnuplot = G
129 self.shell.user_ns.update({'plot':G.plot,'splot':G.splot,'plot2':G.plot2,
130 'replot':G.replot,'hardcopy':G.hardcopy})
131
132 try:
133 __IPYTHON__
134 except NameError:
135 pass
136 else:
137 # make the global Gnuplot instance known to IPython
138 __IPYTHON__.gnuplot = GRun.gp
139 __IPYTHON__.gnuplot.shell_first_time = 1
140
141 print """*** Type `gphelp` for help on the Gnuplot integration features."""
142
143 # Add the new magic functions to the class dict
144 from IPython.iplib import InteractiveShell
145 InteractiveShell.magic_gpc = magic_gpc
146 InteractiveShell.magic_gp_set_default = magic_gp_set_default
147
148 #********************** End of file <GnuplotInteractive.py> *******************
@@ -0,0 +1,147 b''
1 # -*- coding: utf-8 -*-
2 """Basic Gnuplot functionality for inclusion in other code.
3
4 This module creates a running Gnuplot instance called 'gp' and builds other
5 convenient globals for quick use in running scripts. It is intended to allow
6 you to script plotting tasks in Python with a minimum of effort. A typical
7 usage would be:
8
9 import IPython.GnuplotRuntime as GP # or some other short name
10 GP.gp.plot(GP.File('your_data.dat'))
11
12
13 This module exposes the following objects:
14
15 - gp: a running Gnuplot instance. You can access its methods as
16 gp.<method>. gp(`a string`) will execute the given string as if it had been
17 typed in an interactive gnuplot window.
18
19 - gp_new: a function which returns a new Gnuplot instance. This can be used to
20 have multiple Gnuplot instances running in your session to compare different
21 plots.
22
23 - Gnuplot: alias to the Gnuplot2 module, an improved drop-in replacement for
24 the original Gnuplot.py. Gnuplot2 needs Gnuplot but redefines several of its
25 functions with improved versions (Gnuplot2 comes with IPython).
26
27 - Data: alias to Gnuplot.Data, makes a PlotItem from array data.
28
29 - File: alias to Gnuplot.File, makes a PlotItem from a file.
30
31 - String: alias to Gnuplot.String, makes a PlotItem from a string formatted
32 exactly like a file for Gnuplot.File would be.
33
34 - Func: alias to Gnuplot.Func, makes a PlotItem from a function string.
35
36 - GridData: alias to Gnuplot.GridData, makes a PlotItem from grid data.
37
38 - pm3d_config: a string with Gnuplot commands to set up the pm3d mode for
39 surface plotting. You can activate it simply by calling gp(pm3d_config).
40
41 - eps_fix_bbox: A Unix-only function to fix eps files with bad bounding boxes
42 (which Gnuplot generates when the plot size is set to square).
43
44 This requires the Gnuplot.py module for interfacing Python with Gnuplot, which
45 can be downloaded from:
46
47 http://gnuplot-py.sourceforge.net/
48
49 Inspired by a suggestion/request from Arnd Baecker.
50
51 $Id: GnuplotRuntime.py 389 2004-10-09 07:59:30Z fperez $"""
52
53 __all__ = ['Gnuplot','gp','gp_new','Data','File','Func','GridData',
54 'pm3d_config','eps_fix_bbox']
55
56 import os,tempfile,sys
57 from IPython.genutils import getoutput
58
59 #---------------------------------------------------------------------------
60 # Notes on mouse support for Gnuplot.py
61
62 # If you do not have a mouse-enabled gnuplot, set gnuplot_mouse to 0. If you
63 # use gnuplot, you should really grab a recent, mouse enabled copy. It is an
64 # extremely useful feature. Mouse support is official as of gnuplot 4.0,
65 # released in April 2004.
66
67 # For the mouse features to work correctly, you MUST set your Gnuplot.py
68 # module to use temporary files instead of 'inline data' for data
69 # communication. Note that this is the default, so unless you've manually
70 # fiddled with it you should be ok. If you need to make changes, in the
71 # Gnuplot module directory, loook for the gp_unix.py file and make sure the
72 # prefer_inline_data variable is set to 0. If you set it to 1 Gnuplot.py will
73 # try to pass the data to gnuplot via standard input, which completely
74 # confuses the mouse control system (even though it may be a bit faster than
75 # using temp files).
76
77 # As of Gnuplot.py v1.7, a new option was added to use FIFOs (pipes). This
78 # mechanism, while fast, also breaks the mouse system. You must therefore set
79 # the variable prefer_fifo_data to 0 in gp_unix.py.
80
81 tmpname = tempfile.mktemp()
82 open(tmpname,'w').write('set mouse')
83 gnu_out = getoutput('gnuplot '+ tmpname)
84 os.unlink(tmpname)
85 if gnu_out: # Gnuplot won't print anything if it has mouse support
86 print "*** Your version of Gnuplot appears not to have mouse support."
87 gnuplot_mouse = 0
88 else:
89 gnuplot_mouse = 1
90 del tmpname,gnu_out
91
92 # Default state for persistence of new gnuplot instances
93 if os.name in ['nt','dos'] or sys.platform == 'cygwin':
94 gnuplot_persist = 0
95 else:
96 gnuplot_persist = 1
97
98 import IPython.Gnuplot2 as Gnuplot
99
100 class NotGiven: pass
101
102 def gp_new(mouse=NotGiven,persist=NotGiven):
103 """Return a new Gnuplot instance.
104
105 The instance returned uses the improved methods defined in Gnuplot2.
106
107 Options (boolean):
108
109 - mouse: if unspecified, the module global gnuplot_mouse is used.
110
111 - persist: if unspecified, the module global gnuplot_persist is used."""
112
113 if mouse is NotGiven:
114 mouse = gnuplot_mouse
115 if persist is NotGiven:
116 persist = gnuplot_persist
117 g = Gnuplot.Gnuplot(persist=persist)
118 if mouse:
119 g('set mouse')
120 return g
121
122 # Global-level names.
123
124 # A global Gnuplot instance for interactive use:
125 gp = gp_new()
126
127 # Accessors for the main plot object constructors:
128 Data = Gnuplot.Data
129 File = Gnuplot.File
130 Func = Gnuplot.Func
131 String = Gnuplot.String
132 GridData = Gnuplot.GridData
133
134 # A Unix-only function to fix eps files with bad bounding boxes (which Gnuplot
135 # generates when the plot size is set to square):
136 eps_fix_bbox = Gnuplot.eps_fix_bbox
137
138 # String for configuring pm3d. Simply call g(pm3d_config) to execute it. pm3d
139 # is a very nice mode for plotting colormaps on surfaces. Modify the defaults
140 # below to suit your taste.
141 pm3d_config = """
142 set pm3d solid
143 set hidden3d
144 unset surface
145 set isosamples 50
146 """
147 #******************** End of file <GnuplotRuntime.py> ******************
@@ -0,0 +1,253 b''
1 # -*- coding: utf-8 -*-
2 """String interpolation for Python (by Ka-Ping Yee, 14 Feb 2000).
3
4 This module lets you quickly and conveniently interpolate values into
5 strings (in the flavour of Perl or Tcl, but with less extraneous
6 punctuation). You get a bit more power than in the other languages,
7 because this module allows subscripting, slicing, function calls,
8 attribute lookup, or arbitrary expressions. Variables and expressions
9 are evaluated in the namespace of the caller.
10
11 The itpl() function returns the result of interpolating a string, and
12 printpl() prints out an interpolated string. Here are some examples:
13
14 from Itpl import printpl
15 printpl("Here is a $string.")
16 printpl("Here is a $module.member.")
17 printpl("Here is an $object.member.")
18 printpl("Here is a $functioncall(with, arguments).")
19 printpl("Here is an ${arbitrary + expression}.")
20 printpl("Here is an $array[3] member.")
21 printpl("Here is a $dictionary['member'].")
22
23 The filter() function filters a file object so that output through it
24 is interpolated. This lets you produce the illusion that Python knows
25 how to do interpolation:
26
27 import Itpl
28 sys.stdout = Itpl.filter()
29 f = "fancy"
30 print "Isn't this $f?"
31 print "Standard output has been replaced with a $sys.stdout object."
32 sys.stdout = Itpl.unfilter()
33 print "Okay, back $to $normal."
34
35 Under the hood, the Itpl class represents a string that knows how to
36 interpolate values. An instance of the class parses the string once
37 upon initialization; the evaluation and substitution can then be done
38 each time the instance is evaluated with str(instance). For example:
39
40 from Itpl import Itpl
41 s = Itpl("Here is $foo.")
42 foo = 5
43 print str(s)
44 foo = "bar"
45 print str(s)
46
47 $Id: Itpl.py 542 2005-03-18 09:16:04Z fperez $
48 """ # ' -> close an open quote for stupid emacs
49
50 #*****************************************************************************
51 #
52 # Copyright (c) 2001 Ka-Ping Yee <ping@lfw.org>
53 #
54 #
55 # Published under the terms of the MIT license, hereby reproduced:
56 #
57 # Permission is hereby granted, free of charge, to any person obtaining a copy
58 # of this software and associated documentation files (the "Software"), to
59 # deal in the Software without restriction, including without limitation the
60 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
61 # sell copies of the Software, and to permit persons to whom the Software is
62 # furnished to do so, subject to the following conditions:
63 #
64 # The above copyright notice and this permission notice shall be included in
65 # all copies or substantial portions of the Software.
66 #
67 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
68 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
69 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
70 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
71 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
72 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
73 # IN THE SOFTWARE.
74 #
75 #*****************************************************************************
76
77 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
78 __license__ = 'MIT'
79
80 import sys, string
81 from types import StringType
82 from tokenize import tokenprog
83
84 class ItplError(ValueError):
85 def __init__(self, text, pos):
86 self.text = text
87 self.pos = pos
88 def __str__(self):
89 return "unfinished expression in %s at char %d" % (
90 repr(self.text), self.pos)
91
92 def matchorfail(text, pos):
93 match = tokenprog.match(text, pos)
94 if match is None:
95 raise ItplError(text, pos)
96 return match, match.end()
97
98 class Itpl:
99 """Class representing a string with interpolation abilities.
100
101 Upon creation, an instance works out what parts of the format
102 string are literal and what parts need to be evaluated. The
103 evaluation and substitution happens in the namespace of the
104 caller when str(instance) is called."""
105
106 def __init__(self, format):
107 """The single argument to this constructor is a format string.
108
109 The format string is parsed according to the following rules:
110
111 1. A dollar sign and a name, possibly followed by any of:
112 - an open-paren, and anything up to the matching paren
113 - an open-bracket, and anything up to the matching bracket
114 - a period and a name
115 any number of times, is evaluated as a Python expression.
116
117 2. A dollar sign immediately followed by an open-brace, and
118 anything up to the matching close-brace, is evaluated as
119 a Python expression.
120
121 3. Outside of the expressions described in the above two rules,
122 two dollar signs in a row give you one literal dollar sign."""
123
124 if type(format) != StringType:
125 raise TypeError, "needs string initializer"
126 self.format = format
127
128 namechars = "abcdefghijklmnopqrstuvwxyz" \
129 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
130 chunks = []
131 pos = 0
132
133 while 1:
134 dollar = string.find(format, "$", pos)
135 if dollar < 0: break
136 nextchar = format[dollar+1]
137
138 if nextchar == "{":
139 chunks.append((0, format[pos:dollar]))
140 pos, level = dollar+2, 1
141 while level:
142 match, pos = matchorfail(format, pos)
143 tstart, tend = match.regs[3]
144 token = format[tstart:tend]
145 if token == "{": level = level+1
146 elif token == "}": level = level-1
147 chunks.append((1, format[dollar+2:pos-1]))
148
149 elif nextchar in namechars:
150 chunks.append((0, format[pos:dollar]))
151 match, pos = matchorfail(format, dollar+1)
152 while pos < len(format):
153 if format[pos] == "." and \
154 pos+1 < len(format) and format[pos+1] in namechars:
155 match, pos = matchorfail(format, pos+1)
156 elif format[pos] in "([":
157 pos, level = pos+1, 1
158 while level:
159 match, pos = matchorfail(format, pos)
160 tstart, tend = match.regs[3]
161 token = format[tstart:tend]
162 if token[0] in "([": level = level+1
163 elif token[0] in ")]": level = level-1
164 else: break
165 chunks.append((1, format[dollar+1:pos]))
166
167 else:
168 chunks.append((0, format[pos:dollar+1]))
169 pos = dollar + 1 + (nextchar == "$")
170
171 if pos < len(format): chunks.append((0, format[pos:]))
172 self.chunks = chunks
173
174 def __repr__(self):
175 return "<Itpl %s >" % repr(self.format)
176
177 def __str__(self):
178 """Evaluate and substitute the appropriate parts of the string."""
179
180 # We need to skip enough frames to get to the actual caller outside of
181 # Itpl.
182 frame = sys._getframe(1)
183 while frame.f_globals["__name__"] == __name__: frame = frame.f_back
184 loc, glob = frame.f_locals, frame.f_globals
185
186 result = []
187 for live, chunk in self.chunks:
188 if live: result.append(str(eval(chunk,glob,loc)))
189 else: result.append(chunk)
190
191 return ''.join(result)
192
193 class ItplNS(Itpl):
194 """Class representing a string with interpolation abilities.
195
196 This inherits from Itpl, but at creation time a namespace is provided
197 where the evaluation will occur. The interpolation becomes a bit more
198 efficient, as no traceback needs to be extracte. It also allows the
199 caller to supply a different namespace for the interpolation to occur than
200 its own."""
201
202 def __init__(self, format,globals,locals=None):
203 """ItplNS(format,globals[,locals]) -> interpolating string instance.
204
205 This constructor, besides a format string, takes a globals dictionary
206 and optionally a locals (which defaults to globals if not provided).
207
208 For further details, see the Itpl constructor."""
209
210 if locals is None:
211 locals = globals
212 self.globals = globals
213 self.locals = locals
214 Itpl.__init__(self,format)
215
216 def __str__(self):
217 """Evaluate and substitute the appropriate parts of the string."""
218 glob = self.globals
219 loc = self.locals
220 result = []
221 for live, chunk in self.chunks:
222 if live: result.append(str(eval(chunk,glob,loc)))
223 else: result.append(chunk)
224 return ''.join(result)
225
226 # utilities for fast printing
227 def itpl(text): return str(Itpl(text))
228 def printpl(text): print itpl(text)
229 # versions with namespace
230 def itplns(text,globals,locals=None): return str(ItplNS(text,globals,locals))
231 def printplns(text,globals,locals=None): print itplns(text,globals,locals)
232
233 class ItplFile:
234 """A file object that filters each write() through an interpolator."""
235 def __init__(self, file): self.file = file
236 def __repr__(self): return "<interpolated " + repr(self.file) + ">"
237 def __getattr__(self, attr): return getattr(self.file, attr)
238 def write(self, text): self.file.write(str(Itpl(text)))
239
240 def filter(file=sys.stdout):
241 """Return an ItplFile that filters writes to the given file object.
242
243 'file = filter(file)' replaces 'file' with a filtered object that
244 has a write() method. When called with no argument, this creates
245 a filter to sys.stdout."""
246 return ItplFile(file)
247
248 def unfilter(ifile=None):
249 """Return the original file that corresponds to the given ItplFile.
250
251 'file = unfilter(file)' undoes the effect of 'file = filter(file)'.
252 'sys.stdout = unfilter()' undoes the effect of 'sys.stdout = filter()'."""
253 return ifile and ifile.file or sys.stdout.file
@@ -0,0 +1,185 b''
1 # -*- coding: utf-8 -*-
2 """
3 Logger class for IPython's logging facilities.
4
5 $Id: Logger.py 430 2004-11-30 08:52:05Z fperez $
6 """
7
8 #*****************************************************************************
9 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 #
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
15
16 #****************************************************************************
17 # Modules and globals
18
19 from IPython import Release
20 __author__ = '%s <%s>\n%s <%s>' % \
21 ( Release.authors['Janko'] + Release.authors['Fernando'] )
22 __license__ = Release.license
23
24 # Python standard modules
25 import os,sys,glob
26
27 # Homebrewed
28 from IPython.genutils import *
29
30 #****************************************************************************
31 # FIXME: The logger class shouldn't be a mixin, it throws too many things into
32 # the InteractiveShell namespace. Rather make it a standalone tool, and create
33 # a Logger instance in InteractiveShell that uses it. Doing this will require
34 # tracking down a *lot* of nasty uses of the Logger attributes in
35 # InteractiveShell, but will clean up things quite a bit.
36
37 class Logger:
38 """A Logfile Mixin class with different policies for file creation"""
39
40 # FIXME: once this isn't a mixin, log_ns should just be 'namespace', since the
41 # names won't collide anymore.
42 def __init__(self,log_ns):
43 self._i00,self._i,self._ii,self._iii = '','','',''
44 self.do_full_cache = 0 # FIXME. There's also a do_full.. in OutputCache
45 self.log_ns = log_ns
46 # defaults
47 self.LOGMODE = 'backup'
48 self.defname = 'logfile'
49
50 def create_log(self,header='',fname='',defname='.Logger.log'):
51 """Generate a new log-file with a default header"""
52 if fname:
53 self.LOG = fname
54
55 if self.LOG:
56 self.logfname = self.LOG
57 else:
58 self.logfname = defname
59
60 if self.LOGMODE == 'over':
61 if os.path.isfile(self.logfname):
62 os.remove(self.logfname)
63 self.logfile = open(self.logfname,'w')
64 if self.LOGMODE == 'backup':
65 if os.path.isfile(self.logfname):
66 backup_logname = self.logfname+'~'
67 # Manually remove any old backup, since os.rename may fail
68 # under Windows.
69 if os.path.isfile(backup_logname):
70 os.remove(backup_logname)
71 os.rename(self.logfname,backup_logname)
72 self.logfile = open(self.logfname,'w')
73 elif self.LOGMODE == 'global':
74 self.logfname = os.path.join(self.home_dir, self.defname)
75 self.logfile = open(self.logfname, 'a')
76 self.LOG = self.logfname
77 elif self.LOGMODE == 'rotate':
78 if os.path.isfile(self.logfname):
79 if os.path.isfile(self.logfname+'.001~'):
80 old = glob.glob(self.logfname+'.*~')
81 old.sort()
82 old.reverse()
83 for f in old:
84 root, ext = os.path.splitext(f)
85 num = int(ext[1:-1])+1
86 os.rename(f, root+'.'+`num`.zfill(3)+'~')
87 os.rename(self.logfname, self.logfname+'.001~')
88 self.logfile = open(self.logfname,'w')
89 elif self.LOGMODE == 'append':
90 self.logfile = open(self.logfname,'a')
91
92 if self.LOGMODE != 'append':
93 self.logfile.write(header)
94 self.logfile.flush()
95
96 def logstart(self, header='',parameter_s = ''):
97 if not hasattr(self, 'LOG'):
98 logfname = self.LOG or parameter_s or './'+self.defname
99 self.create_log(header,logfname)
100 elif parameter_s and hasattr(self,'logfname') and \
101 parameter_s != self.logfname:
102 self.close_log()
103 self.create_log(header,parameter_s)
104
105 self._dolog = 1
106
107 def switch_log(self,val):
108 """Switch logging on/off. val should be ONLY 0 or 1."""
109
110 if not val in [0,1]:
111 raise ValueError, \
112 'Call switch_log ONLY with 0 or 1 as argument, not with:',val
113
114 label = {0:'OFF',1:'ON'}
115
116 try:
117 _ = self.logfile
118 except AttributeError:
119 print """
120 Logging hasn't been started yet (use %logstart for that).
121
122 %logon/%logoff are for temporarily starting and stopping logging for a logfile
123 which already exists. But you must first start the logging process with
124 %logstart (optionally giving a logfile name)."""
125
126 else:
127 if self._dolog == val:
128 print 'Logging is already',label[val]
129 else:
130 print 'Switching logging',label[val]
131 self._dolog = 1 - self._dolog
132
133 def logstate(self):
134 """Print a status message about the logger."""
135 try:
136 logfile = self.logfname
137 except:
138 print 'Logging has not been activated.'
139 else:
140 state = self._dolog and 'active' or 'temporarily suspended'
141 print """
142 File:\t%s
143 Mode:\t%s
144 State:\t%s """ % (logfile,self.LOGMODE,state)
145
146
147 def log(self, line,continuation=None):
148 """Write the line to a log and create input cache variables _i*."""
149
150 # update the auto _i tables
151 #print '***logging line',line # dbg
152 #print '***cache_count', self.outputcache.prompt_count # dbg
153 input_hist = self.log_ns['_ih']
154 if not continuation and line:
155 self._iii = self._ii
156 self._ii = self._i
157 self._i = self._i00
158 # put back the final \n of every input line
159 self._i00 = line+'\n'
160 #print 'Logging input:<%s>' % line # dbg
161 input_hist.append(self._i00)
162
163 # hackish access to top-level namespace to create _i1,_i2... dynamically
164 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
165 if self.do_full_cache:
166 in_num = self.outputcache.prompt_count
167 # add blank lines if the input cache fell out of sync. This can happen
168 # for embedded instances which get killed via C-D and then get resumed.
169 while in_num >= len(input_hist):
170 input_hist.append('\n')
171 new_i = '_i%s' % in_num
172 if continuation:
173 self._i00 = '%s%s\n' % (self.log_ns[new_i],line)
174 input_hist[in_num] = self._i00
175 to_main[new_i] = self._i00
176 self.log_ns.update(to_main)
177
178 if self._dolog and line:
179 self.logfile.write(line+'\n')
180 self.logfile.flush()
181
182 def close_log(self):
183 if hasattr(self, 'logfile'):
184 self.logfile.close()
185 self.logfname = ''
This diff has been collapsed as it changes many lines, (2490 lines changed) Show them Hide them
@@ -0,0 +1,2490 b''
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
3
4 $Id: Magic.py 583 2005-05-13 21:20:33Z fperez $"""
5
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
13
14 #****************************************************************************
15 # Modules and globals
16
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
21
22 # Python standard modules
23 import __builtin__
24 import os,sys,inspect,pydoc,re,tempfile,shlex,pdb,bdb,time
25 try:
26 import profile,pstats
27 except ImportError:
28 profile = pstats = None
29 from getopt import getopt
30 from pprint import pprint, pformat
31 from cStringIO import StringIO
32
33 # Homebrewed
34 from IPython.Struct import Struct
35 from IPython.Itpl import Itpl, itpl, printpl,itplns
36 from IPython.FakeModule import FakeModule
37 from IPython import OInspect
38 from IPython.genutils import *
39
40 # Globals to be set later by Magic constructor
41 MAGIC_PREFIX = ''
42 MAGIC_ESCAPE = ''
43
44 #***************************************************************************
45 # Utility functions
46 def magic2python(cmd):
47 """Convert a command string of magic syntax to valid Python code."""
48
49 if cmd.startswith('#'+MAGIC_ESCAPE) or \
50 cmd.startswith(MAGIC_ESCAPE):
51 if cmd[0]=='#':
52 cmd = cmd[1:]
53 # we need to return the proper line end later
54 if cmd[-1] == '\n':
55 endl = '\n'
56 else:
57 endl = ''
58 try:
59 func,args = cmd[1:].split(' ',1)
60 except:
61 func,args = cmd[1:].rstrip(),''
62 args = args.replace('"','\\"').replace("'","\\'").rstrip()
63 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
64 else:
65 return cmd
66
67 def on_off(tag):
68 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
69 return ['OFF','ON'][tag]
70
71 def get_py_filename(name):
72 """Return a valid python filename in the current directory.
73
74 If the given name is not a file, it adds '.py' and searches again.
75 Raises IOError with an informative message if the file isn't found."""
76
77 name = os.path.expanduser(name)
78 if not os.path.isfile(name) and not name.endswith('.py'):
79 name += '.py'
80 if os.path.isfile(name):
81 return name
82 else:
83 raise IOError,'File `%s` not found.' % name
84
85 # Try to use shlex.split for converting an input string into a sys.argv-type
86 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
87 try:
88 shlex_split = shlex.split
89 except AttributeError:
90 _quotesre = re.compile(r'[\'"](.*)[\'"]')
91 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
92 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
93 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
94 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
95 % os.sep)
96
97 def shlex_split(s):
98 """Simplified backport to Python 2.2 of shlex.split().
99
100 This is a quick and dirty hack, since the shlex module under 2.2 lacks
101 several of the features needed to really match the functionality of
102 shlex.split() in 2.3."""
103
104 lex = shlex.shlex(StringIO(s))
105 # Try to get options, extensions and path separators as characters
106 lex.wordchars = _wordchars
107 lex.commenters = ''
108 # Make a list out of the lexer by hand, since in 2.2 it's not an
109 # iterator.
110 lout = []
111 while 1:
112 token = lex.get_token()
113 if token == '':
114 break
115 # Try to handle quoted tokens correctly
116 quotes = _quotesre.match(token)
117 if quotes:
118 token = quotes.group(1)
119 lout.append(token)
120 return lout
121
122 #****************************************************************************
123 # Utility classes
124 class Macro:
125 """Simple class to store the value of macros as strings.
126
127 This allows us to later exec them by checking when something is an
128 instance of this class."""
129
130 def __init__(self,cmds):
131 """Build a macro from a list of commands."""
132
133 # Since the list may include multi-line entries, first make sure that
134 # they've been all broken up before passing it to magic2python
135 cmdlist = map(magic2python,''.join(cmds).split('\n'))
136 self.value = '\n'.join(cmdlist)
137
138 def __str__(self):
139 return self.value
140
141 #***************************************************************************
142 # Main class implementing Magic functionality
143 class Magic:
144 """Magic functions for InteractiveShell.
145
146 Shell functions which can be reached as %function_name. All magic
147 functions should accept a string, which they can parse for their own
148 needs. This can make some functions easier to type, eg `%cd ../`
149 vs. `%cd("../")`
150
151 ALL definitions MUST begin with the prefix magic_. The user won't need it
152 at the command line, but it is is needed in the definition. """
153
154 # class globals
155 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
156 'Automagic is ON, % prefix NOT needed for magic functions.']
157
158 #......................................................................
159 # some utility functions
160
161 def __init__(self,shell):
162 # XXX This is hackish, clean up later to avoid these messy globals
163 global MAGIC_PREFIX, MAGIC_ESCAPE
164
165 self.options_table = {}
166 MAGIC_PREFIX = shell.name+'.magic_'
167 MAGIC_ESCAPE = shell.ESC_MAGIC
168 if profile is None:
169 self.magic_prun = self.profile_missing_notice
170
171 def profile_missing_notice(self, *args, **kwargs):
172 error("""\
173 The profile module could not be found. If you are a Debian user,
174 it has been removed from the standard Debian package because of its non-free
175 license. To use profiling, please install"python2.3-profiler" from non-free.""")
176
177 def default_option(self,fn,optstr):
178 """Make an entry in the options_table for fn, with value optstr"""
179
180 if fn not in self.lsmagic():
181 error("%s is not a magic function" % fn)
182 self.options_table[fn] = optstr
183
184 def lsmagic(self):
185 """Return a list of currently available magic functions.
186
187 Gives a list of the bare names after mangling (['ls','cd', ...], not
188 ['magic_ls','magic_cd',...]"""
189
190 # FIXME. This needs a cleanup, in the way the magics list is built.
191
192 # magics in class definition
193 class_magic = lambda fn: fn.startswith('magic_') and \
194 callable(Magic.__dict__[fn])
195 # in instance namespace (run-time user additions)
196 inst_magic = lambda fn: fn.startswith('magic_') and \
197 callable(self.__dict__[fn])
198 # and bound magics by user (so they can access self):
199 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
200 callable(self.__class__.__dict__[fn])
201 magics = filter(class_magic,Magic.__dict__.keys()) + \
202 filter(inst_magic,self.__dict__.keys()) + \
203 filter(inst_bound_magic,self.__class__.__dict__.keys())
204 out = []
205 for fn in magics:
206 out.append(fn.replace('magic_','',1))
207 out.sort()
208 return out
209
210 def set_shell(self,shell):
211 self.shell = shell
212 self.alias_table = shell.alias_table
213
214 def extract_input_slices(self,slices):
215 """Return as a string a set of input history slices.
216
217 The set of slices is given as a list of strings (like ['1','4:8','9'],
218 since this function is for use by magic functions which get their
219 arguments as strings."""
220
221 cmds = []
222 for chunk in slices:
223 if ':' in chunk:
224 ini,fin = map(int,chunk.split(':'))
225 else:
226 ini = int(chunk)
227 fin = ini+1
228 cmds.append(self.shell.input_hist[ini:fin])
229 return cmds
230
231 def _ofind(self,oname):
232 """Find an object in the available namespaces.
233
234 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
235
236 Has special code to detect magic functions.
237 """
238
239 oname = oname.strip()
240
241 # Namespaces to search in:
242 user_ns = self.shell.user_ns
243 internal_ns = self.shell.internal_ns
244 builtin_ns = __builtin__.__dict__
245 alias_ns = self.shell.alias_table
246
247 # Put them in a list. The order is important so that we find things in
248 # the same order that Python finds them.
249 namespaces = [ ('Interactive',user_ns),
250 ('IPython internal',internal_ns),
251 ('Python builtin',builtin_ns),
252 ('Alias',alias_ns),
253 ]
254
255 # initialize results to 'null'
256 found = 0; obj = None; ospace = None; ds = None;
257 ismagic = 0; isalias = 0
258
259 # Look for the given name by splitting it in parts. If the head is
260 # found, then we look for all the remaining parts as members, and only
261 # declare success if we can find them all.
262 oname_parts = oname.split('.')
263 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
264 for nsname,ns in namespaces:
265 try:
266 obj = ns[oname_head]
267 except KeyError:
268 continue
269 else:
270 for part in oname_rest:
271 try:
272 obj = getattr(obj,part)
273 except:
274 # Blanket except b/c some badly implemented objects
275 # allow __getattr__ to raise exceptions other than
276 # AttributeError, which then crashes IPython.
277 break
278 else:
279 # If we finish the for loop (no break), we got all members
280 found = 1
281 ospace = nsname
282 if ns == alias_ns:
283 isalias = 1
284 break # namespace loop
285
286 # Try to see if it's magic
287 if not found:
288 if oname.startswith(self.shell.ESC_MAGIC):
289 oname = oname[1:]
290 obj = getattr(self,'magic_'+oname,None)
291 if obj is not None:
292 found = 1
293 ospace = 'IPython internal'
294 ismagic = 1
295
296 # Last try: special-case some literals like '', [], {}, etc:
297 if not found and oname_head in ["''",'""','[]','{}','()']:
298 obj = eval(oname_head)
299 found = 1
300 ospace = 'Interactive'
301
302 return {'found':found, 'obj':obj, 'namespace':ospace,
303 'ismagic':ismagic, 'isalias':isalias}
304
305 def arg_err(self,func):
306 """Print docstring if incorrect arguments were passed"""
307 print 'Error in arguments:'
308 print OInspect.getdoc(func)
309
310
311 def format_latex(self,str):
312 """Format a string for latex inclusion."""
313
314 # Characters that need to be escaped for latex:
315 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
316 # Magic command names as headers:
317 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
318 re.MULTILINE)
319 # Magic commands
320 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
321 re.MULTILINE)
322 # Paragraph continue
323 par_re = re.compile(r'\\$',re.MULTILINE)
324
325 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
326 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
327 str = par_re.sub(r'\\\\',str)
328 str = escape_re.sub(r'\\\1',str)
329 return str
330
331 def format_screen(self,str):
332 """Format a string for screen printing.
333
334 This removes some latex-type format codes."""
335 # Paragraph continue
336 par_re = re.compile(r'\\$',re.MULTILINE)
337 str = par_re.sub('',str)
338 return str
339
340 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
341 """Parse options passed to an argument string.
342
343 The interface is similar to that of getopt(), but it returns back a
344 Struct with the options as keys and the stripped argument string still
345 as a string.
346
347 arg_str is quoted as a true sys.argv vector by calling on the fly a
348 python process in a subshell. This allows us to easily expand
349 variables, glob files, quote arguments, etc, with all the power and
350 correctness of the underlying system shell.
351
352 Options:
353 -mode: default 'string'. If given as 'list', the argument string is
354 returned as a list (split on whitespace) instead of a string.
355
356 -list_all: put all option values in lists. Normally only options
357 appearing more than once are put in a list."""
358
359 # inject default options at the beginning of the input line
360 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
361 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
362
363 mode = kw.get('mode','string')
364 if mode not in ['string','list']:
365 raise ValueError,'incorrect mode given: %s' % mode
366 # Get options
367 list_all = kw.get('list_all',0)
368
369 # Check if we have more than one argument to warrant extra processing:
370 odict = {} # Dictionary with options
371 args = arg_str.split()
372 if len(args) >= 1:
373 # If the list of inputs only has 0 or 1 thing in it, there's no
374 # need to look for options
375 argv = shlex_split(arg_str)
376 # Do regular option processing
377 opts,args = getopt(argv,opt_str,*long_opts)
378 for o,a in opts:
379 if o.startswith('--'):
380 o = o[2:]
381 else:
382 o = o[1:]
383 try:
384 odict[o].append(a)
385 except AttributeError:
386 odict[o] = [odict[o],a]
387 except KeyError:
388 if list_all:
389 odict[o] = [a]
390 else:
391 odict[o] = a
392
393 # Prepare opts,args for return
394 opts = Struct(odict)
395 if mode == 'string':
396 args = ' '.join(args)
397
398 return opts,args
399
400 #......................................................................
401 # And now the actual magic functions
402
403 # Functions for IPython shell work (vars,funcs, config, etc)
404 def magic_lsmagic(self, parameter_s = ''):
405 """List currently available magic functions."""
406 mesc = self.shell.ESC_MAGIC
407 print 'Available magic functions:\n'+mesc+\
408 (' '+mesc).join(self.lsmagic())
409 print '\n' + Magic.auto_status[self.shell.rc.automagic]
410 return None
411
412 def magic_magic(self, parameter_s = ''):
413 """Print information about the magic function system."""
414
415 mode = ''
416 try:
417 if parameter_s.split()[0] == '-latex':
418 mode = 'latex'
419 except:
420 pass
421
422 magic_docs = []
423 for fname in self.lsmagic():
424 mname = 'magic_' + fname
425 for space in (Magic,self,self.__class__):
426 try:
427 fn = space.__dict__[mname]
428 except KeyError:
429 pass
430 else:
431 break
432 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
433 fname,fn.__doc__))
434 magic_docs = ''.join(magic_docs)
435
436 if mode == 'latex':
437 print self.format_latex(magic_docs)
438 return
439 else:
440 magic_docs = self.format_screen(magic_docs)
441
442 outmsg = """
443 IPython's 'magic' functions
444 ===========================
445
446 The magic function system provides a series of functions which allow you to
447 control the behavior of IPython itself, plus a lot of system-type
448 features. All these functions are prefixed with a % character, but parameters
449 are given without parentheses or quotes.
450
451 NOTE: If you have 'automagic' enabled (via the command line option or with the
452 %automagic function), you don't need to type in the % explicitly. By default,
453 IPython ships with automagic on, so you should only rarely need the % escape.
454
455 Example: typing '%cd mydir' (without the quotes) changes you working directory
456 to 'mydir', if it exists.
457
458 You can define your own magic functions to extend the system. See the supplied
459 ipythonrc and example-magic.py files for details (in your ipython
460 configuration directory, typically $HOME/.ipython/).
461
462 You can also define your own aliased names for magic functions. In your
463 ipythonrc file, placing a line like:
464
465 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
466
467 will define %pf as a new name for %profile.
468
469 You can also call magics in code using the ipmagic() function, which IPython
470 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
471
472 For a list of the available magic functions, use %lsmagic. For a description
473 of any of them, type %magic_name?, e.g. '%cd?'.
474
475 Currently the magic system has the following functions:\n"""
476
477 mesc = self.shell.ESC_MAGIC
478 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
479 "\n\n%s%s\n\n%s" % (outmsg,
480 magic_docs,mesc,mesc,
481 (' '+mesc).join(self.lsmagic()),
482 Magic.auto_status[self.shell.rc.automagic] ) )
483
484 page(outmsg,screen_lines=self.shell.rc.screen_length)
485
486 def magic_automagic(self, parameter_s = ''):
487 """Make magic functions callable without having to type the initial %.
488
489 Toggles on/off (when off, you must call it as %automagic, of
490 course). Note that magic functions have lowest priority, so if there's
491 a variable whose name collides with that of a magic fn, automagic
492 won't work for that function (you get the variable instead). However,
493 if you delete the variable (del var), the previously shadowed magic
494 function becomes visible to automagic again."""
495
496 rc = self.shell.rc
497 rc.automagic = not rc.automagic
498 print '\n' + Magic.auto_status[rc.automagic]
499
500 def magic_autocall(self, parameter_s = ''):
501 """Make functions callable without having to type parentheses.
502
503 This toggles the autocall command line option on and off."""
504
505 rc = self.shell.rc
506 rc.autocall = not rc.autocall
507 print "Automatic calling is:",['OFF','ON'][rc.autocall]
508
509 def magic_autoindent(self, parameter_s = ''):
510 """Toggle autoindent on/off (if available)."""
511
512 self.shell.set_autoindent()
513 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
514
515 def magic_system_verbose(self, parameter_s = ''):
516 """Toggle verbose printing of system calls on/off."""
517
518 self.shell.rc_set_toggle('system_verbose')
519 print "System verbose printing is:",\
520 ['OFF','ON'][self.shell.rc.system_verbose]
521
522 def magic_history(self, parameter_s = ''):
523 """Print input history (_i<n> variables), with most recent last.
524
525 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
526 %history [-n] n -> print at most n inputs\\
527 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
528
529 Each input's number <n> is shown, and is accessible as the
530 automatically generated variable _i<n>. Multi-line statements are
531 printed starting at a new line for easy copy/paste.
532
533 If option -n is used, input numbers are not printed. This is useful if
534 you want to get a printout of many lines which can be directly pasted
535 into a text editor.
536
537 This feature is only available if numbered prompts are in use."""
538
539 if not self.do_full_cache:
540 print 'This feature is only available if numbered prompts are in use.'
541 return
542 opts,args = self.parse_options(parameter_s,'n',mode='list')
543
544 default_length = 40
545 if len(args) == 0:
546 final = self.outputcache.prompt_count
547 init = max(1,final-default_length)
548 elif len(args) == 1:
549 final = self.outputcache.prompt_count
550 init = max(1,final-int(args[0]))
551 elif len(args) == 2:
552 init,final = map(int,args)
553 else:
554 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
555 print self.magic_hist.__doc__
556 return
557 width = len(str(final))
558 line_sep = ['','\n']
559 input_hist = self.shell.input_hist
560 print_nums = not opts.has_key('n')
561 for in_num in range(init,final):
562 inline = input_hist[in_num]
563 multiline = inline.count('\n') > 1
564 if print_nums:
565 print str(in_num).ljust(width)+':'+ line_sep[multiline],
566 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
567 inline.startswith('#!'):
568 print inline[1:],
569 else:
570 print inline,
571
572 def magic_hist(self, parameter_s=''):
573 """Alternate name for %history."""
574 return self.magic_history(parameter_s)
575
576 def magic_p(self, parameter_s=''):
577 """Just a short alias for Python's 'print'."""
578 exec 'print ' + parameter_s in self.shell.user_ns
579
580 def magic_r(self, parameter_s=''):
581 """Repeat previous input.
582
583 If given an argument, repeats the previous command which starts with
584 the same string, otherwise it just repeats the previous input.
585
586 Shell escaped commands (with ! as first character) are not recognized
587 by this system, only pure python code and magic commands.
588 """
589
590 start = parameter_s.strip()
591 esc_magic = self.shell.ESC_MAGIC
592 # Identify magic commands even if automagic is on (which means
593 # the in-memory version is different from that typed by the user).
594 if self.shell.rc.automagic:
595 start_magic = esc_magic+start
596 else:
597 start_magic = start
598 # Look through the input history in reverse
599 for n in range(len(self.shell.input_hist)-2,0,-1):
600 input = self.shell.input_hist[n]
601 # skip plain 'r' lines so we don't recurse to infinity
602 if input != 'ipmagic("r")\n' and \
603 (input.startswith(start) or input.startswith(start_magic)):
604 #print 'match',`input` # dbg
605 if input.startswith(esc_magic):
606 input = magic2python(input)
607 #print 'modified',`input` # dbg
608 print 'Executing:',input,
609 exec input in self.shell.user_ns
610 return
611 print 'No previous input matching `%s` found.' % start
612
613 def magic_page(self, parameter_s=''):
614 """Pretty print the object and display it through a pager.
615
616 If no parameter is given, use _ (last output)."""
617 # After a function contributed by Olivier Aubert, slightly modified.
618
619 oname = parameter_s and parameter_s or '_'
620 info = self._ofind(oname)
621 if info['found']:
622 page(pformat(info['obj']))
623 else:
624 print 'Object `%s` not found' % oname
625
626 def magic_profile(self, parameter_s=''):
627 """Print your currently active IPyhton profile."""
628 if self.shell.rc.profile:
629 printpl('Current IPython profile: $self.shell.rc.profile.')
630 else:
631 print 'No profile active.'
632
633 def _inspect(self,meth,oname,**kw):
634 """Generic interface to the inspector system.
635
636 This function is meant to be called by pdef, pdoc & friends."""
637
638 oname = oname.strip()
639 info = Struct(self._ofind(oname))
640 if info.found:
641 pmethod = getattr(self.shell.inspector,meth)
642 formatter = info.ismagic and self.format_screen or None
643 if meth == 'pdoc':
644 pmethod(info.obj,oname,formatter)
645 elif meth == 'pinfo':
646 pmethod(info.obj,oname,formatter,info,**kw)
647 else:
648 pmethod(info.obj,oname)
649 else:
650 print 'Object `%s` not found.' % oname
651 return 'not found' # so callers can take other action
652
653 def magic_pdef(self, parameter_s=''):
654 """Print the definition header for any callable object.
655
656 If the object is a class, print the constructor information."""
657 self._inspect('pdef',parameter_s)
658
659 def magic_pdoc(self, parameter_s=''):
660 """Print the docstring for an object.
661
662 If the given object is a class, it will print both the class and the
663 constructor docstrings."""
664 self._inspect('pdoc',parameter_s)
665
666 def magic_psource(self, parameter_s=''):
667 """Print (or run through pager) the source code for an object."""
668 self._inspect('psource',parameter_s)
669
670 def magic_pfile(self, parameter_s=''):
671 """Print (or run through pager) the file where an object is defined.
672
673 The file opens at the line where the object definition begins. IPython
674 will honor the environment variable PAGER if set, and otherwise will
675 do its best to print the file in a convenient form.
676
677 If the given argument is not an object currently defined, IPython will
678 try to interpret it as a filename (automatically adding a .py extension
679 if needed). You can thus use %pfile as a syntax highlighting code
680 viewer."""
681
682 # first interpret argument as an object name
683 out = self._inspect('pfile',parameter_s)
684 # if not, try the input as a filename
685 if out == 'not found':
686 try:
687 filename = get_py_filename(parameter_s)
688 except IOError,msg:
689 print msg
690 return
691 page(self.shell.inspector.format(file(filename).read()))
692
693 def magic_pinfo(self, parameter_s=''):
694 """Provide detailed information about an object.
695
696 '%pinfo object' is just a synonym for object? or ?object."""
697
698 #print 'pinfo par: <%s>' % parameter_s # dbg
699
700 # detail_level: 0 -> obj? , 1 -> obj??
701 detail_level = 0
702 # We need to detect if we got called as 'pinfo pinfo foo', which can
703 # happen if the user types 'pinfo foo?' at the cmd line.
704 pinfo,qmark1,oname,qmark2 = \
705 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
706 if pinfo or qmark1 or qmark2:
707 detail_level = 1
708 self._inspect('pinfo',oname,detail_level=detail_level)
709
710 def magic_who_ls(self, parameter_s=''):
711 """Return a sorted list of all interactive variables.
712
713 If arguments are given, only variables of types matching these
714 arguments are returned."""
715
716 user_ns = self.shell.user_ns
717 out = []
718 typelist = parameter_s.split()
719 for i in self.shell.user_ns.keys():
720 if not (i.startswith('_') or i.startswith('_i')) \
721 and not (self.internal_ns.has_key(i) or
722 self.user_config_ns.has_key(i)):
723 if typelist:
724 if type(user_ns[i]).__name__ in typelist:
725 out.append(i)
726 else:
727 out.append(i)
728 out.sort()
729 return out
730
731 def magic_who(self, parameter_s=''):
732 """Print all interactive variables, with some minimal formatting.
733
734 If any arguments are given, only variables whose type matches one of
735 these are printed. For example:
736
737 %who function str
738
739 will only list functions and strings, excluding all other types of
740 variables. To find the proper type names, simply use type(var) at a
741 command line to see how python prints type names. For example:
742
743 In [1]: type('hello')\\
744 Out[1]: <type 'str'>
745
746 indicates that the type name for strings is 'str'.
747
748 %who always excludes executed names loaded through your configuration
749 file and things which are internal to IPython.
750
751 This is deliberate, as typically you may load many modules and the
752 purpose of %who is to show you only what you've manually defined."""
753
754 varlist = self.magic_who_ls(parameter_s)
755 if not varlist:
756 print 'Interactive namespace is empty.'
757 return
758
759 # if we have variables, move on...
760
761 # stupid flushing problem: when prompts have no separators, stdout is
762 # getting lost. I'm starting to think this is a python bug. I'm having
763 # to force a flush with a print because even a sys.stdout.flush
764 # doesn't seem to do anything!
765
766 count = 0
767 for i in varlist:
768 print i+'\t',
769 count += 1
770 if count > 8:
771 count = 0
772 print
773 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
774
775 print # well, this does force a flush at the expense of an extra \n
776
777 def magic_whos(self, parameter_s=''):
778 """Like %who, but gives some extra information about each variable.
779
780 The same type filtering of %who can be applied here.
781
782 For all variables, the type is printed. Additionally it prints:
783
784 - For {},[],(): their length.
785
786 - For Numeric arrays, a summary with shape, number of elements,
787 typecode and size in memory.
788
789 - Everything else: a string representation, snipping their middle if
790 too long."""
791
792 varnames = self.magic_who_ls(parameter_s)
793 if not varnames:
794 print 'Interactive namespace is empty.'
795 return
796
797 # if we have variables, move on...
798
799 # for these types, show len() instead of data:
800 seq_types = [types.DictType,types.ListType,types.TupleType]
801
802 # for Numeric arrays, display summary info
803 try:
804 import Numeric
805 except ImportError:
806 array_type = None
807 else:
808 array_type = Numeric.ArrayType.__name__
809
810 # Find all variable names and types so we can figure out column sizes
811 get_vars = lambda i: self.locals[i]
812 type_name = lambda v: type(v).__name__
813 varlist = map(get_vars,varnames)
814 typelist = map(type_name,varlist)
815 # column labels and # of spaces as separator
816 varlabel = 'Variable'
817 typelabel = 'Type'
818 datalabel = 'Data/Info'
819 colsep = 3
820 # variable format strings
821 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
822 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
823 aformat = "%s: %s elems, type `%s`, %s bytes"
824 # find the size of the columns to format the output nicely
825 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
826 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
827 # table header
828 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
829 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
830 # and the table itself
831 kb = 1024
832 Mb = 1048576 # kb**2
833 for vname,var,vtype in zip(varnames,varlist,typelist):
834 print itpl(vformat),
835 if vtype in seq_types:
836 print len(var)
837 elif vtype==array_type:
838 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
839 vsize = Numeric.size(var)
840 vbytes = vsize*var.itemsize()
841 if vbytes < 100000:
842 print aformat % (vshape,vsize,var.typecode(),vbytes)
843 else:
844 print aformat % (vshape,vsize,var.typecode(),vbytes),
845 if vbytes < Mb:
846 print '(%s kb)' % (vbytes/kb,)
847 else:
848 print '(%s Mb)' % (vbytes/Mb,)
849 else:
850 vstr = str(var)
851 if len(vstr) < 50:
852 print vstr
853 else:
854 printpl(vfmt_short)
855
856 def magic_reset(self, parameter_s=''):
857 """Resets the namespace by removing all names defined by the user.
858
859 Input/Output history are left around in case you need them."""
860
861 ans = raw_input(
862 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
863 if not ans.lower() == 'y':
864 print 'Nothing done.'
865 return
866 for i in self.magic_who_ls():
867 del(self.locals[i])
868
869 def magic_config(self,parameter_s=''):
870 """Show IPython's internal configuration."""
871
872 page('Current configuration structure:\n'+
873 pformat(self.shell.rc.dict()))
874
875 def magic_logstart(self,parameter_s=''):
876 """Start logging anywhere in a session.
877
878 %logstart [log_name [log_mode]]
879
880 If no name is given, it defaults to a file named 'ipython.log' in your
881 current directory, in 'rotate' mode (see below).
882
883 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
884 history up to that point and then continues logging.
885
886 %logstart takes a second optional parameter: logging mode. This can be one
887 of (note that the modes are given unquoted):\\
888 over: overwrite existing log.\\
889 backup: rename (if exists) to name~ and start name.\\
890 append: well, that says it.\\
891 rotate: create rotating logs name.1~, name.2~, etc.
892 """
893
894 #FIXME. This function should all be moved to the Logger class.
895
896 valid_modes = qw('over backup append rotate')
897 if self.LOG:
898 print 'Logging is already in place. Logfile:',self.LOG
899 return
900
901 par = parameter_s.strip()
902 if not par:
903 logname = self.LOGDEF
904 logmode = 'rotate' # use rotate for the auto-generated logs
905 else:
906 try:
907 logname,logmode = par.split()
908 except:
909 try:
910 logname = par
911 logmode = 'backup'
912 except:
913 warn('Usage: %log [log_name [log_mode]]')
914 return
915 if not logmode in valid_modes:
916 warn('Logging NOT activated.\n'
917 'Usage: %log [log_name [log_mode]]\n'
918 'Valid modes: '+str(valid_modes))
919 return
920
921 # If we made it this far, I think we're ok:
922 print 'Activating auto-logging.'
923 print 'Current session state plus future input saved to:',logname
924 print 'Logging mode: ',logmode
925 # put logname into rc struct as if it had been called on the command line,
926 # so it ends up saved in the log header
927 # Save it in case we need to restore it...
928 old_logfile = self.shell.rc.opts.get('logfile','')
929 logname = os.path.expanduser(logname)
930 self.shell.rc.opts.logfile = logname
931 self.LOGMODE = logmode # FIXME: this should be set through a function.
932 try:
933 header = str(self.LOGHEAD)
934 self.create_log(header,logname)
935 self.logstart(header,logname)
936 except:
937 self.LOG = '' # we are NOT logging, something went wrong
938 self.shell.rc.opts.logfile = old_logfile
939 warn("Couldn't start log: "+str(sys.exc_info()[1]))
940 else: # log input history up to this point
941 self.logfile.write(self.shell.user_ns['_ih'][1:])
942 self.logfile.flush()
943
944 def magic_logoff(self,parameter_s=''):
945 """Temporarily stop logging.
946
947 You must have previously started logging."""
948 self.switch_log(0)
949
950 def magic_logon(self,parameter_s=''):
951 """Restart logging.
952
953 This function is for restarting logging which you've temporarily
954 stopped with %logoff. For starting logging for the first time, you
955 must use the %logstart function, which allows you to specify an
956 optional log filename."""
957
958 self.switch_log(1)
959
960 def magic_logstate(self,parameter_s=''):
961 """Print the status of the logging system."""
962
963 self.logstate()
964
965 def magic_pdb(self, parameter_s=''):
966 """Control the calling of the pdb interactive debugger.
967
968 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
969 argument it works as a toggle.
970
971 When an exception is triggered, IPython can optionally call the
972 interactive pdb debugger after the traceback printout. %pdb toggles
973 this feature on and off."""
974
975 par = parameter_s.strip().lower()
976
977 if par:
978 try:
979 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
980 except KeyError:
981 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
982 return
983 else:
984 self.shell.InteractiveTB.call_pdb = pdb
985 else:
986 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
987 print 'Automatic pdb calling has been turned',\
988 on_off(self.shell.InteractiveTB.call_pdb)
989
990
991 def magic_prun(self, parameter_s ='',user_mode=1,
992 opts=None,arg_lst=None,prog_ns=None):
993
994 """Run a statement through the python code profiler.
995
996 Usage:\\
997 %prun [options] statement
998
999 The given statement (which doesn't require quote marks) is run via the
1000 python profiler in a manner similar to the profile.run() function.
1001 Namespaces are internally managed to work correctly; profile.run
1002 cannot be used in IPython because it makes certain assumptions about
1003 namespaces which do not hold under IPython.
1004
1005 Options:
1006
1007 -l <limit>: you can place restrictions on what or how much of the
1008 profile gets printed. The limit value can be:
1009
1010 * A string: only information for function names containing this string
1011 is printed.
1012
1013 * An integer: only these many lines are printed.
1014
1015 * A float (between 0 and 1): this fraction of the report is printed
1016 (for example, use a limit of 0.4 to see the topmost 40% only).
1017
1018 You can combine several limits with repeated use of the option. For
1019 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1020 information about class constructors.
1021
1022 -r: return the pstats.Stats object generated by the profiling. This
1023 object has all the information about the profile in it, and you can
1024 later use it for further analysis or in other functions.
1025
1026 Since magic functions have a particular form of calling which prevents
1027 you from writing something like:\\
1028 In [1]: p = %prun -r print 4 # invalid!\\
1029 you must instead use IPython's automatic variables to assign this:\\
1030 In [1]: %prun -r print 4 \\
1031 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1032 In [2]: stats = _
1033
1034 If you really need to assign this value via an explicit function call,
1035 you can always tap directly into the true name of the magic function
1036 by using the ipmagic function (which IPython automatically adds to the
1037 builtins):\\
1038 In [3]: stats = ipmagic('prun','-r print 4')
1039
1040 You can type ipmagic? for more details on ipmagic.
1041
1042 -s <key>: sort profile by given key. You can provide more than one key
1043 by using the option several times: '-s key1 -s key2 -s key3...'. The
1044 default sorting key is 'time'.
1045
1046 The following is copied verbatim from the profile documentation
1047 referenced below:
1048
1049 When more than one key is provided, additional keys are used as
1050 secondary criteria when the there is equality in all keys selected
1051 before them.
1052
1053 Abbreviations can be used for any key names, as long as the
1054 abbreviation is unambiguous. The following are the keys currently
1055 defined:
1056
1057 Valid Arg Meaning\\
1058 "calls" call count\\
1059 "cumulative" cumulative time\\
1060 "file" file name\\
1061 "module" file name\\
1062 "pcalls" primitive call count\\
1063 "line" line number\\
1064 "name" function name\\
1065 "nfl" name/file/line\\
1066 "stdname" standard name\\
1067 "time" internal time
1068
1069 Note that all sorts on statistics are in descending order (placing
1070 most time consuming items first), where as name, file, and line number
1071 searches are in ascending order (i.e., alphabetical). The subtle
1072 distinction between "nfl" and "stdname" is that the standard name is a
1073 sort of the name as printed, which means that the embedded line
1074 numbers get compared in an odd way. For example, lines 3, 20, and 40
1075 would (if the file names were the same) appear in the string order
1076 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1077 line numbers. In fact, sort_stats("nfl") is the same as
1078 sort_stats("name", "file", "line").
1079
1080 -T <filename>: save profile results as shown on screen to a text
1081 file. The profile is still shown on screen.
1082
1083 -D <filename>: save (via dump_stats) profile statistics to given
1084 filename. This data is in a format understod by the pstats module, and
1085 is generated by a call to the dump_stats() method of profile
1086 objects. The profile is still shown on screen.
1087
1088 If you want to run complete programs under the profiler's control, use
1089 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1090 contains profiler specific options as described here.
1091
1092 You can read the complete documentation for the profile module with:\\
1093 In [1]: import profile; profile.help() """
1094
1095 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1096 # protect user quote marks
1097 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1098
1099 if user_mode: # regular user call
1100 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1101 list_all=1)
1102 namespace = self.shell.user_ns
1103 else: # called to run a program by %run -p
1104 try:
1105 filename = get_py_filename(arg_lst[0])
1106 except IOError,msg:
1107 error(msg)
1108 return
1109
1110 arg_str = 'execfile(filename,prog_ns)'
1111 namespace = locals()
1112
1113 opts.merge(opts_def)
1114
1115 prof = profile.Profile()
1116 try:
1117 prof = prof.runctx(arg_str,namespace,namespace)
1118 sys_exit = ''
1119 except SystemExit:
1120 sys_exit = """*** SystemExit exception caught in code being profiled."""
1121
1122 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1123
1124 lims = opts.l
1125 if lims:
1126 lims = [] # rebuild lims with ints/floats/strings
1127 for lim in opts.l:
1128 try:
1129 lims.append(int(lim))
1130 except ValueError:
1131 try:
1132 lims.append(float(lim))
1133 except ValueError:
1134 lims.append(lim)
1135
1136 # trap output
1137 sys_stdout = sys.stdout
1138 stdout_trap = StringIO()
1139 try:
1140 sys.stdout = stdout_trap
1141 stats.print_stats(*lims)
1142 finally:
1143 sys.stdout = sys_stdout
1144 output = stdout_trap.getvalue()
1145 output = output.rstrip()
1146
1147 page(output,screen_lines=self.shell.rc.screen_length)
1148 print sys_exit,
1149
1150 dump_file = opts.D[0]
1151 text_file = opts.T[0]
1152 if dump_file:
1153 prof.dump_stats(dump_file)
1154 print '\n*** Profile stats marshalled to file',\
1155 `dump_file`+'.',sys_exit
1156 if text_file:
1157 file(text_file,'w').write(output)
1158 print '\n*** Profile printout saved to text file',\
1159 `text_file`+'.',sys_exit
1160
1161 if opts.has_key('r'):
1162 return stats
1163 else:
1164 return None
1165
1166 def magic_run(self, parameter_s ='',runner=None):
1167 """Run the named file inside IPython as a program.
1168
1169 Usage:\\
1170 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1171
1172 Parameters after the filename are passed as command-line arguments to
1173 the program (put in sys.argv). Then, control returns to IPython's
1174 prompt.
1175
1176 This is similar to running at a system prompt:\\
1177 $ python file args\\
1178 but with the advantage of giving you IPython's tracebacks, and of
1179 loading all variables into your interactive namespace for further use
1180 (unless -p is used, see below).
1181
1182 The file is executed in a namespace initially consisting only of
1183 __name__=='__main__' and sys.argv constructed as indicated. It thus
1184 sees its environment as if it were being run as a stand-alone
1185 program. But after execution, the IPython interactive namespace gets
1186 updated with all variables defined in the program (except for __name__
1187 and sys.argv). This allows for very convenient loading of code for
1188 interactive work, while giving each program a 'clean sheet' to run in.
1189
1190 Options:
1191
1192 -n: __name__ is NOT set to '__main__', but to the running file's name
1193 without extension (as python does under import). This allows running
1194 scripts and reloading the definitions in them without calling code
1195 protected by an ' if __name__ == "__main__" ' clause.
1196
1197 -i: run the file in IPython's namespace instead of an empty one. This
1198 is useful if you are experimenting with code written in a text editor
1199 which depends on variables defined interactively.
1200
1201 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1202 being run. This is particularly useful if IPython is being used to
1203 run unittests, which always exit with a sys.exit() call. In such
1204 cases you are interested in the output of the test results, not in
1205 seeing a traceback of the unittest module.
1206
1207 -t: print timing information at the end of the run. IPython will give
1208 you an estimated CPU time consumption for your script, which under
1209 Unix uses the resource module to avoid the wraparound problems of
1210 time.clock(). Under Unix, an estimate of time spent on system tasks
1211 is also given (for Windows platforms this is reported as 0.0).
1212
1213 If -t is given, an additional -N<N> option can be given, where <N>
1214 must be an integer indicating how many times you want the script to
1215 run. The final timing report will include total and per run results.
1216
1217 For example (testing the script uniq_stable.py):
1218
1219 In [1]: run -t uniq_stable
1220
1221 IPython CPU timings (estimated):\\
1222 User : 0.19597 s.\\
1223 System: 0.0 s.\\
1224
1225 In [2]: run -t -N5 uniq_stable
1226
1227 IPython CPU timings (estimated):\\
1228 Total runs performed: 5\\
1229 Times : Total Per run\\
1230 User : 0.910862 s, 0.1821724 s.\\
1231 System: 0.0 s, 0.0 s.
1232
1233 -d: run your program under the control of pdb, the Python debugger.
1234 This allows you to execute your program step by step, watch variables,
1235 etc. Internally, what IPython does is similar to calling:
1236
1237 pdb.run('execfile("YOURFILENAME")')
1238
1239 with a breakpoint set on line 1 of your file. You can change the line
1240 number for this automatic breakpoint to be <N> by using the -bN option
1241 (where N must be an integer). For example:
1242
1243 %run -d -b40 myscript
1244
1245 will set the first breakpoint at line 40 in myscript.py. Note that
1246 the first breakpoint must be set on a line which actually does
1247 something (not a comment or docstring) for it to stop execution.
1248
1249 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1250 first enter 'c' (without qoutes) to start execution up to the first
1251 breakpoint.
1252
1253 Entering 'help' gives information about the use of the debugger. You
1254 can easily see pdb's full documentation with "import pdb;pdb.help()"
1255 at a prompt.
1256
1257 -p: run program under the control of the Python profiler module (which
1258 prints a detailed report of execution times, function calls, etc).
1259
1260 You can pass other options after -p which affect the behavior of the
1261 profiler itself. See the docs for %prun for details.
1262
1263 In this mode, the program's variables do NOT propagate back to the
1264 IPython interactive namespace (because they remain in the namespace
1265 where the profiler executes them).
1266
1267 Internally this triggers a call to %prun, see its documentation for
1268 details on the options available specifically for profiling."""
1269
1270 # get arguments and set sys.argv for program to be run.
1271 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1272 mode='list',list_all=1)
1273
1274 try:
1275 filename = get_py_filename(arg_lst[0])
1276 except IndexError:
1277 warn('you must provide at least a filename.')
1278 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1279 return
1280 except IOError,msg:
1281 error(msg)
1282 return
1283
1284 # Control the response to exit() calls made by the script being run
1285 exit_ignore = opts.has_key('e')
1286
1287 # Make sure that the running script gets a proper sys.argv as if it
1288 # were run from a system shell.
1289 save_argv = sys.argv # save it for later restoring
1290 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1291
1292 if opts.has_key('i'):
1293 prog_ns = self.shell.user_ns
1294 __name__save = self.shell.user_ns['__name__']
1295 prog_ns['__name__'] = '__main__'
1296 else:
1297 if opts.has_key('n'):
1298 name = os.path.splitext(os.path.basename(filename))[0]
1299 else:
1300 name = '__main__'
1301 prog_ns = {'__name__':name}
1302
1303 # pickle fix. See iplib for an explanation
1304 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1305
1306 stats = None
1307 try:
1308 if opts.has_key('p'):
1309 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1310 else:
1311 if opts.has_key('d'):
1312 deb = pdb.Pdb()
1313 # reset Breakpoint state, which is moronically kept
1314 # in a class
1315 bdb.Breakpoint.next = 1
1316 bdb.Breakpoint.bplist = {}
1317 bdb.Breakpoint.bpbynumber = [None]
1318 # Set an initial breakpoint to stop execution
1319 maxtries = 10
1320 bp = int(opts.get('b',[1])[0])
1321 checkline = deb.checkline(filename,bp)
1322 if not checkline:
1323 for bp in range(bp+1,bp+maxtries+1):
1324 if deb.checkline(filename,bp):
1325 break
1326 else:
1327 msg = ("\nI failed to find a valid line to set "
1328 "a breakpoint\n"
1329 "after trying up to line: %s.\n"
1330 "Please set a valid breakpoint manually "
1331 "with the -b option." % bp)
1332 error(msg)
1333 return
1334 # if we find a good linenumber, set the breakpoint
1335 deb.do_break('%s:%s' % (filename,bp))
1336 # Start file run
1337 print "NOTE: Enter 'c' at the",
1338 print "(Pdb) prompt to start your script."
1339 deb.run('execfile("%s")' % filename,prog_ns)
1340 else:
1341 if runner is None:
1342 runner = self.shell.safe_execfile
1343 if opts.has_key('t'):
1344 try:
1345 nruns = int(opts['N'][0])
1346 if nruns < 1:
1347 error('Number of runs must be >=1')
1348 return
1349 except (KeyError):
1350 nruns = 1
1351 if nruns == 1:
1352 t0 = clock2()
1353 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1354 t1 = clock2()
1355 t_usr = t1[0]-t0[0]
1356 t_sys = t1[1]-t1[1]
1357 print "\nIPython CPU timings (estimated):"
1358 print " User : %10s s." % t_usr
1359 print " System: %10s s." % t_sys
1360 else:
1361 runs = range(nruns)
1362 t0 = clock2()
1363 for nr in runs:
1364 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1365 t1 = clock2()
1366 t_usr = t1[0]-t0[0]
1367 t_sys = t1[1]-t1[1]
1368 print "\nIPython CPU timings (estimated):"
1369 print "Total runs performed:",nruns
1370 print " Times : %10s %10s" % ('Total','Per run')
1371 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1372 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1373
1374 else:
1375 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1376 if opts.has_key('i'):
1377 self.shell.user_ns['__name__'] = __name__save
1378 else:
1379 # update IPython interactive namespace
1380 del prog_ns['__name__']
1381 self.shell.user_ns.update(prog_ns)
1382 finally:
1383 sys.argv = save_argv
1384 return stats
1385
1386 def magic_runlog(self, parameter_s =''):
1387 """Run files as logs.
1388
1389 Usage:\\
1390 %runlog file1 file2 ...
1391
1392 Run the named files (treating them as log files) in sequence inside
1393 the interpreter, and return to the prompt. This is much slower than
1394 %run because each line is executed in a try/except block, but it
1395 allows running files with syntax errors in them.
1396
1397 Normally IPython will guess when a file is one of its own logfiles, so
1398 you can typically use %run even for logs. This shorthand allows you to
1399 force any file to be treated as a log file."""
1400
1401 for f in parameter_s.split():
1402 self.shell.safe_execfile(f,self.shell.user_ns,
1403 self.shell.user_ns,islog=1)
1404
1405 def magic_time(self,parameter_s = ''):
1406 """Time execution of a Python statement or expression.
1407
1408 The CPU and wall clock times are printed, and the value of the
1409 expression (if any) is returned. Note that under Win32, system time
1410 is always reported as 0, since it can not be measured.
1411
1412 This function provides very basic timing functionality. In Python
1413 2.3, the timeit module offers more control and sophistication, but for
1414 now IPython supports Python 2.2, so we can not rely on timeit being
1415 present.
1416
1417 Some examples:
1418
1419 In [1]: time 2**128
1420 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1421 Wall time: 0.00
1422 Out[1]: 340282366920938463463374607431768211456L
1423
1424 In [2]: n = 1000000
1425
1426 In [3]: time sum(range(n))
1427 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1428 Wall time: 1.37
1429 Out[3]: 499999500000L
1430
1431 In [4]: time print 'hello world'
1432 hello world
1433 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1434 Wall time: 0.00
1435 """
1436
1437 # fail immediately if the given expression can't be compiled
1438 try:
1439 mode = 'eval'
1440 code = compile(parameter_s,'<timed eval>',mode)
1441 except SyntaxError:
1442 mode = 'exec'
1443 code = compile(parameter_s,'<timed exec>',mode)
1444 # skew measurement as little as possible
1445 glob = self.shell.user_ns
1446 clk = clock2
1447 wtime = time.time
1448 # time execution
1449 wall_st = wtime()
1450 if mode=='eval':
1451 st = clk()
1452 out = eval(code,glob)
1453 end = clk()
1454 else:
1455 st = clk()
1456 exec code in glob
1457 end = clk()
1458 out = None
1459 wall_end = wtime()
1460 # Compute actual times and report
1461 wall_time = wall_end-wall_st
1462 cpu_user = end[0]-st[0]
1463 cpu_sys = end[1]-st[1]
1464 cpu_tot = cpu_user+cpu_sys
1465 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1466 (cpu_user,cpu_sys,cpu_tot)
1467 print "Wall time: %.2f" % wall_time
1468 return out
1469
1470 def magic_macro(self,parameter_s = ''):
1471 """Define a set of input lines as a macro for future re-execution.
1472
1473 Usage:\\
1474 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1475
1476 This will define a global variable called `name` which is a string
1477 made of joining the slices and lines you specify (n1,n2,... numbers
1478 above) from your input history into a single string. This variable
1479 acts like an automatic function which re-executes those lines as if
1480 you had typed them. You just type 'name' at the prompt and the code
1481 executes.
1482
1483 Note that the slices use the standard Python slicing notation (5:8
1484 means include lines numbered 5,6,7).
1485
1486 For example, if your history contains (%hist prints it):
1487
1488 44: x=1\\
1489 45: y=3\\
1490 46: z=x+y\\
1491 47: print x\\
1492 48: a=5\\
1493 49: print 'x',x,'y',y\\
1494
1495 you can create a macro with lines 44 through 47 (included) and line 49
1496 called my_macro with:
1497
1498 In [51]: %macro my_macro 44:48 49
1499
1500 Now, typing `my_macro` (without quotes) will re-execute all this code
1501 in one pass.
1502
1503 You don't need to give the line-numbers in order, and any given line
1504 number can appear multiple times. You can assemble macros with any
1505 lines from your input history in any order.
1506
1507 The macro is a simple object which holds its value in an attribute,
1508 but IPython's display system checks for macros and executes them as
1509 code instead of printing them when you type their name.
1510
1511 You can view a macro's contents by explicitly printing it with:
1512
1513 'print macro_name'.
1514
1515 For one-off cases which DON'T contain magic function calls in them you
1516 can obtain similar results by explicitly executing slices from your
1517 input history with:
1518
1519 In [60]: exec In[44:48]+In[49]"""
1520
1521 args = parameter_s.split()
1522 name,ranges = args[0], args[1:]
1523 #print 'rng',ranges # dbg
1524 cmds = self.extract_input_slices(ranges)
1525 macro = Macro(cmds)
1526 self.shell.user_ns.update({name:macro})
1527 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1528 print 'Macro contents:'
1529 print str(macro).rstrip(),
1530
1531 def magic_save(self,parameter_s = ''):
1532 """Save a set of lines to a given filename.
1533
1534 Usage:\\
1535 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1536
1537 This function uses the same syntax as %macro for line extraction, but
1538 instead of creating a macro it saves the resulting string to the
1539 filename you specify.
1540
1541 It adds a '.py' extension to the file if you don't do so yourself, and
1542 it asks for confirmation before overwriting existing files."""
1543
1544 args = parameter_s.split()
1545 fname,ranges = args[0], args[1:]
1546 if not fname.endswith('.py'):
1547 fname += '.py'
1548 if os.path.isfile(fname):
1549 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1550 if ans.lower() not in ['y','yes']:
1551 print 'Operation cancelled.'
1552 return
1553 cmds = ''.join(self.extract_input_slices(ranges))
1554 f = file(fname,'w')
1555 f.write(cmds)
1556 f.close()
1557 print 'The following commands were written to file `%s`:' % fname
1558 print cmds
1559
1560 def magic_ed(self,parameter_s = ''):
1561 """Alias to %edit."""
1562 return self.magic_edit(parameter_s)
1563
1564 def magic_edit(self,parameter_s = '',last_call=['','']):
1565 """Bring up an editor and execute the resulting code.
1566
1567 Usage:
1568 %edit [options] [args]
1569
1570 %edit runs IPython's editor hook. The default version of this hook is
1571 set to call the __IPYTHON__.rc.editor command. This is read from your
1572 environment variable $EDITOR. If this isn't found, it will default to
1573 vi under Linux/Unix and to notepad under Windows. See the end of this
1574 docstring for how to change the editor hook.
1575
1576 You can also set the value of this editor via the command line option
1577 '-editor' or in your ipythonrc file. This is useful if you wish to use
1578 specifically for IPython an editor different from your typical default
1579 (and for Windows users who typically don't set environment variables).
1580
1581 This command allows you to conveniently edit multi-line code right in
1582 your IPython session.
1583
1584 If called without arguments, %edit opens up an empty editor with a
1585 temporary file and will execute the contents of this file when you
1586 close it (don't forget to save it!).
1587
1588 Options:
1589
1590 -p: this will call the editor with the same data as the previous time
1591 it was used, regardless of how long ago (in your current session) it
1592 was.
1593
1594 -x: do not execute the edited code immediately upon exit. This is
1595 mainly useful if you are editing programs which need to be called with
1596 command line arguments, which you can then do using %run.
1597
1598 Arguments:
1599
1600 If arguments are given, the following possibilites exist:
1601
1602 - The arguments are numbers or pairs of colon-separated numbers (like
1603 1 4:8 9). These are interpreted as lines of previous input to be
1604 loaded into the editor. The syntax is the same of the %macro command.
1605
1606 - If the argument doesn't start with a number, it is evaluated as a
1607 variable and its contents loaded into the editor. You can thus edit
1608 any string which contains python code (including the result of
1609 previous edits).
1610
1611 - If the argument is the name of an object (other than a string),
1612 IPython will try to locate the file where it was defined and open the
1613 editor at the point where it is defined. You can use `%edit function`
1614 to load an editor exactly at the point where 'function' is defined,
1615 edit it and have the file be executed automatically.
1616
1617 Note: opening at an exact line is only supported under Unix, and some
1618 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1619 '+NUMBER' parameter necessary for this feature. Good editors like
1620 (X)Emacs, vi, jed, pico and joe all do.
1621
1622 - If the argument is not found as a variable, IPython will look for a
1623 file with that name (adding .py if necessary) and load it into the
1624 editor. It will execute its contents with execfile() when you exit,
1625 loading any code in the file into your interactive namespace.
1626
1627 After executing your code, %edit will return as output the code you
1628 typed in the editor (except when it was an existing file). This way
1629 you can reload the code in further invocations of %edit as a variable,
1630 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1631 the output.
1632
1633 Note that %edit is also available through the alias %ed.
1634
1635 This is an example of creating a simple function inside the editor and
1636 then modifying it. First, start up the editor:
1637
1638 In [1]: ed\\
1639 Editing... done. Executing edited code...\\
1640 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1641
1642 We can then call the function foo():
1643
1644 In [2]: foo()\\
1645 foo() was defined in an editing session
1646
1647 Now we edit foo. IPython automatically loads the editor with the
1648 (temporary) file where foo() was previously defined:
1649
1650 In [3]: ed foo\\
1651 Editing... done. Executing edited code...
1652
1653 And if we call foo() again we get the modified version:
1654
1655 In [4]: foo()\\
1656 foo() has now been changed!
1657
1658 Here is an example of how to edit a code snippet successive
1659 times. First we call the editor:
1660
1661 In [8]: ed\\
1662 Editing... done. Executing edited code...\\
1663 hello\\
1664 Out[8]: "print 'hello'\\n"
1665
1666 Now we call it again with the previous output (stored in _):
1667
1668 In [9]: ed _\\
1669 Editing... done. Executing edited code...\\
1670 hello world\\
1671 Out[9]: "print 'hello world'\\n"
1672
1673 Now we call it with the output #8 (stored in _8, also as Out[8]):
1674
1675 In [10]: ed _8\\
1676 Editing... done. Executing edited code...\\
1677 hello again\\
1678 Out[10]: "print 'hello again'\\n"
1679
1680
1681 Changing the default editor hook:
1682
1683 If you wish to write your own editor hook, you can put it in a
1684 configuration file which you load at startup time. The default hook
1685 is defined in the IPython.hooks module, and you can use that as a
1686 starting example for further modifications. That file also has
1687 general instructions on how to set a new hook for use once you've
1688 defined it."""
1689
1690 # FIXME: This function has become a convoluted mess. It needs a
1691 # ground-up rewrite with clean, simple logic.
1692
1693 def make_filename(arg):
1694 "Make a filename from the given args"
1695 try:
1696 filename = get_py_filename(arg)
1697 except IOError:
1698 if args.endswith('.py'):
1699 filename = arg
1700 else:
1701 filename = None
1702 return filename
1703
1704 # custom exceptions
1705 class DataIsObject(Exception): pass
1706
1707 opts,args = self.parse_options(parameter_s,'px')
1708
1709 # Default line number value
1710 lineno = None
1711 if opts.has_key('p'):
1712 args = '_%s' % last_call[0]
1713 if not self.shell.user_ns.has_key(args):
1714 args = last_call[1]
1715
1716 # use last_call to remember the state of the previous call, but don't
1717 # let it be clobbered by successive '-p' calls.
1718 try:
1719 last_call[0] = self.shell.outputcache.prompt_count
1720 if not opts.has_key('p'):
1721 last_call[1] = parameter_s
1722 except:
1723 pass
1724
1725 # by default this is done with temp files, except when the given
1726 # arg is a filename
1727 use_temp = 1
1728
1729 if re.match(r'\d',args):
1730 # Mode where user specifies ranges of lines, like in %macro.
1731 # This means that you can't edit files whose names begin with
1732 # numbers this way. Tough.
1733 ranges = args.split()
1734 data = ''.join(self.extract_input_slices(ranges))
1735 elif args.endswith('.py'):
1736 filename = make_filename(args)
1737 data = ''
1738 use_temp = 0
1739 elif args:
1740 try:
1741 # Load the parameter given as a variable. If not a string,
1742 # process it as an object instead (below)
1743
1744 #print '*** args',args,'type',type(args) # dbg
1745 data = eval(args,self.shell.user_ns)
1746 if not type(data) in StringTypes:
1747 raise DataIsObject
1748 except (NameError,SyntaxError):
1749 # given argument is not a variable, try as a filename
1750 filename = make_filename(args)
1751 if filename is None:
1752 warn("Argument given (%s) can't be found as a variable "
1753 "or as a filename." % args)
1754 return
1755 data = ''
1756 use_temp = 0
1757 except DataIsObject:
1758 # For objects, try to edit the file where they are defined
1759 try:
1760 filename = inspect.getabsfile(data)
1761 datafile = 1
1762 except TypeError:
1763 filename = make_filename(args)
1764 datafile = 1
1765 warn('Could not find file where `%s` is defined.\n'
1766 'Opening a file named `%s`' % (args,filename))
1767 # Now, make sure we can actually read the source (if it was in
1768 # a temp file it's gone by now).
1769 if datafile:
1770 try:
1771 lineno = inspect.getsourcelines(data)[1]
1772 except IOError:
1773 filename = make_filename(args)
1774 if filename is None:
1775 warn('The file `%s` where `%s` was defined cannot '
1776 'be read.' % (filename,data))
1777 return
1778 use_temp = 0
1779 else:
1780 data = ''
1781
1782 if use_temp:
1783 filename = tempfile.mktemp('.py')
1784 self.shell.tempfiles.append(filename)
1785
1786 if data and use_temp:
1787 tmp_file = open(filename,'w')
1788 tmp_file.write(data)
1789 tmp_file.close()
1790
1791 # do actual editing here
1792 print 'Editing...',
1793 sys.stdout.flush()
1794 self.shell.hooks.editor(filename,lineno)
1795 if opts.has_key('x'): # -x prevents actual execution
1796 print
1797 else:
1798 print 'done. Executing edited code...'
1799 try:
1800 execfile(filename,self.shell.user_ns)
1801 except IOError,msg:
1802 if msg.filename == filename:
1803 warn('File not found. Did you forget to save?')
1804 return
1805 else:
1806 self.shell.showtraceback()
1807 except:
1808 self.shell.showtraceback()
1809 if use_temp:
1810 contents = open(filename).read()
1811 return contents
1812
1813 def magic_xmode(self,parameter_s = ''):
1814 """Switch modes for the exception handlers.
1815
1816 Valid modes: Plain, Context and Verbose.
1817
1818 If called without arguments, acts as a toggle."""
1819
1820 new_mode = parameter_s.strip().capitalize()
1821 try:
1822 self.InteractiveTB.set_mode(mode = new_mode)
1823 print 'Exception reporting mode:',self.InteractiveTB.mode
1824 except:
1825 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1826
1827 def magic_colors(self,parameter_s = ''):
1828 """Switch color scheme for prompts, info system and exception handlers.
1829
1830 Currently implemented schemes: NoColor, Linux, LightBG.
1831
1832 Color scheme names are not case-sensitive."""
1833
1834 new_scheme = parameter_s.strip()
1835 if not new_scheme:
1836 print 'You must specify a color scheme.'
1837 return
1838 # Under Windows, check for Gary Bishop's readline, which is necessary
1839 # for ANSI coloring
1840 if os.name in ['nt','dos']:
1841 try:
1842 import readline
1843 except ImportError:
1844 has_readline = 0
1845 else:
1846 try:
1847 readline.GetOutputFile()
1848 except AttributeError:
1849 has_readline = 0
1850 else:
1851 has_readline = 1
1852 if not has_readline:
1853 msg = """\
1854 Proper color support under MS Windows requires Gary Bishop's readline library.
1855 You can find it at:
1856 http://sourceforge.net/projects/uncpythontools
1857 Gary's readline needs the ctypes module, from:
1858 http://starship.python.net/crew/theller/ctypes
1859
1860 Defaulting color scheme to 'NoColor'"""
1861 new_scheme = 'NoColor'
1862 warn(msg)
1863
1864 # Set prompt colors
1865 try:
1866 self.shell.outputcache.set_colors(new_scheme)
1867 except:
1868 warn('Error changing prompt color schemes.\n'
1869 + str(sys.exc_info()[1]))
1870 else:
1871 self.shell.rc.colors = \
1872 self.shell.outputcache.color_table.active_scheme_name
1873 # Set exception colors
1874 try:
1875 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1876 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1877 except:
1878 warn('Error changing exception color schemes.\n'
1879 + str(sys.exc_info()[1]))
1880 # Set info (for 'object?') colors
1881 if self.shell.rc.color_info:
1882 try:
1883 self.shell.inspector.set_active_scheme(new_scheme)
1884 except:
1885 warn('Error changing object inspector color schemes.\n'
1886 + str(sys.exc_info()[1]))
1887 else:
1888 self.shell.inspector.set_active_scheme('NoColor')
1889
1890 def magic_color_info(self,parameter_s = ''):
1891 """Toggle color_info.
1892
1893 The color_info configuration parameter controls whether colors are
1894 used for displaying object details (by things like %psource, %pfile or
1895 the '?' system). This function toggles this value with each call.
1896
1897 Note that unless you have a fairly recent pager (less works better
1898 than more) in your system, using colored object information displays
1899 will not work properly. Test it and see."""
1900
1901 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1902 self.magic_colors(self.shell.rc.colors)
1903 print 'Object introspection functions have now coloring:',
1904 print ['OFF','ON'][self.shell.rc.color_info]
1905
1906 def magic_Pprint(self, parameter_s=''):
1907 """Toggle pretty printing on/off."""
1908
1909 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1910 print 'Pretty printing has been turned', \
1911 ['OFF','ON'][self.shell.outputcache.Pprint]
1912
1913 def magic_Exit(self, parameter_s=''):
1914 """Exit IPython without confirmation."""
1915
1916 self.shell.exit_now = True
1917
1918 def magic_Quit(self, parameter_s=''):
1919 """Exit IPython without confirmation (like %Exit)."""
1920
1921 self.shell.exit_now = True
1922
1923 #......................................................................
1924 # Functions to implement unix shell-type things
1925
1926 def magic_alias(self, parameter_s = ''):
1927 """Define an alias for a system command.
1928
1929 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1930
1931 Then, typing 'alias_name params' will execute the system command 'cmd
1932 params' (from your underlying operating system).
1933
1934 Aliases have lower precedence than magic functions and Python normal
1935 variables, so if 'foo' is both a Python variable and an alias, the
1936 alias can not be executed until 'del foo' removes the Python variable.
1937
1938 You can use the %l specifier in an alias definition to represent the
1939 whole line when the alias is called. For example:
1940
1941 In [2]: alias all echo "Input in brackets: <%l>"\\
1942 In [3]: all hello world\\
1943 Input in brackets: <hello world>
1944
1945 You can also define aliases with parameters using %s specifiers (one
1946 per parameter):
1947
1948 In [1]: alias parts echo first %s second %s\\
1949 In [2]: %parts A B\\
1950 first A second B\\
1951 In [3]: %parts A\\
1952 Incorrect number of arguments: 2 expected.\\
1953 parts is an alias to: 'echo first %s second %s'
1954
1955 Note that %l and %s are mutually exclusive. You can only use one or
1956 the other in your aliases.
1957
1958 Aliases expand Python variables just like system calls using ! or !!
1959 do: all expressions prefixed with '$' get expanded. For details of
1960 the semantic rules, see PEP-215:
1961 http://www.python.org/peps/pep-0215.html. This is the library used by
1962 IPython for variable expansion. If you want to access a true shell
1963 variable, an extra $ is necessary to prevent its expansion by IPython:
1964
1965 In [6]: alias show echo\\
1966 In [7]: PATH='A Python string'\\
1967 In [8]: show $PATH\\
1968 A Python string\\
1969 In [9]: show $$PATH\\
1970 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1971
1972 You can use the alias facility to acess all of $PATH. See the %rehash
1973 and %rehashx functions, which automatically create aliases for the
1974 contents of your $PATH.
1975
1976 If called with no parameters, %alias prints the current alias table."""
1977
1978 par = parameter_s.strip()
1979 if not par:
1980 if self.shell.rc.automagic:
1981 prechar = ''
1982 else:
1983 prechar = self.shell.ESC_MAGIC
1984 print 'Alias\t\tSystem Command\n'+'-'*30
1985 atab = self.shell.alias_table
1986 aliases = atab.keys()
1987 aliases.sort()
1988 for alias in aliases:
1989 print prechar+alias+'\t\t'+atab[alias][1]
1990 print '-'*30+'\nTotal number of aliases:',len(aliases)
1991 return
1992 try:
1993 alias,cmd = par.split(None,1)
1994 except:
1995 print OInspect.getdoc(self.magic_alias)
1996 else:
1997 nargs = cmd.count('%s')
1998 if nargs>0 and cmd.find('%l')>=0:
1999 error('The %s and %l specifiers are mutually exclusive '
2000 'in alias definitions.')
2001 else: # all looks OK
2002 self.shell.alias_table[alias] = (nargs,cmd)
2003 self.shell.alias_table_validate(verbose=1)
2004 # end magic_alias
2005
2006 def magic_unalias(self, parameter_s = ''):
2007 """Remove an alias"""
2008
2009 aname = parameter_s.strip()
2010 if aname in self.shell.alias_table:
2011 del self.shell.alias_table[aname]
2012
2013 def magic_rehash(self, parameter_s = ''):
2014 """Update the alias table with all entries in $PATH.
2015
2016 This version does no checks on execute permissions or whether the
2017 contents of $PATH are truly files (instead of directories or something
2018 else). For such a safer (but slower) version, use %rehashx."""
2019
2020 # This function (and rehashx) manipulate the alias_table directly
2021 # rather than calling magic_alias, for speed reasons. A rehash on a
2022 # typical Linux box involves several thousand entries, so efficiency
2023 # here is a top concern.
2024
2025 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2026 alias_table = self.shell.alias_table
2027 for pdir in path:
2028 for ff in os.listdir(pdir):
2029 # each entry in the alias table must be (N,name), where
2030 # N is the number of positional arguments of the alias.
2031 alias_table[ff] = (0,ff)
2032 # Make sure the alias table doesn't contain keywords or builtins
2033 self.shell.alias_table_validate()
2034 # Call again init_auto_alias() so we get 'rm -i' and other modified
2035 # aliases since %rehash will probably clobber them
2036 self.shell.init_auto_alias()
2037
2038 def magic_rehashx(self, parameter_s = ''):
2039 """Update the alias table with all executable files in $PATH.
2040
2041 This version explicitly checks that every entry in $PATH is a file
2042 with execute access (os.X_OK), so it is much slower than %rehash.
2043
2044 Under Windows, it checks executability as a match agains a
2045 '|'-separated string of extensions, stored in the IPython config
2046 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2047
2048 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2049 alias_table = self.shell.alias_table
2050
2051 if os.name == 'posix':
2052 isexec = lambda fname:os.path.isfile(fname) and \
2053 os.access(fname,os.X_OK)
2054 else:
2055
2056 try:
2057 winext = os.environ['pathext'].replace(';','|').replace('.','')
2058 except KeyError:
2059 winext = 'exe|com|bat'
2060
2061 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2062 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2063 savedir = os.getcwd()
2064 try:
2065 # write the whole loop for posix/Windows so we don't have an if in
2066 # the innermost part
2067 if os.name == 'posix':
2068 for pdir in path:
2069 os.chdir(pdir)
2070 for ff in os.listdir(pdir):
2071 if isexec(ff):
2072 # each entry in the alias table must be (N,name),
2073 # where N is the number of positional arguments of the
2074 # alias.
2075 alias_table[ff] = (0,ff)
2076 else:
2077 for pdir in path:
2078 os.chdir(pdir)
2079 for ff in os.listdir(pdir):
2080 if isexec(ff):
2081 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2082 # Make sure the alias table doesn't contain keywords or builtins
2083 self.shell.alias_table_validate()
2084 # Call again init_auto_alias() so we get 'rm -i' and other
2085 # modified aliases since %rehashx will probably clobber them
2086 self.shell.init_auto_alias()
2087 finally:
2088 os.chdir(savedir)
2089
2090 def magic_pwd(self, parameter_s = ''):
2091 """Return the current working directory path."""
2092 return os.getcwd()
2093
2094 def magic_cd(self, parameter_s=''):
2095 """Change the current working directory.
2096
2097 This command automatically maintains an internal list of directories
2098 you visit during your IPython session, in the variable _dh. The
2099 command %dhist shows this history nicely formatted.
2100
2101 Usage:
2102
2103 cd 'dir': changes to directory 'dir'.
2104
2105 cd -: changes to the last visited directory.
2106
2107 cd -<n>: changes to the n-th directory in the directory history.
2108
2109 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2110 (note: cd <bookmark_name> is enough if there is no
2111 directory <bookmark_name>, but a bookmark with the name exists.)
2112
2113 Options:
2114
2115 -q: quiet. Do not print the working directory after the cd command is
2116 executed. By default IPython's cd command does print this directory,
2117 since the default prompts do not display path information.
2118
2119 Note that !cd doesn't work for this purpose because the shell where
2120 !command runs is immediately discarded after executing 'command'."""
2121
2122 parameter_s = parameter_s.strip()
2123 bkms = self.shell.persist.get("bookmarks",{})
2124
2125 numcd = re.match(r'(-)(\d+)$',parameter_s)
2126 # jump in directory history by number
2127 if numcd:
2128 nn = int(numcd.group(2))
2129 try:
2130 ps = self.shell.user_ns['_dh'][nn]
2131 except IndexError:
2132 print 'The requested directory does not exist in history.'
2133 return
2134 else:
2135 opts = {}
2136 else:
2137 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2138 # jump to previous
2139 if ps == '-':
2140 try:
2141 ps = self.shell.user_ns['_dh'][-2]
2142 except IndexError:
2143 print 'No previous directory to change to.'
2144 return
2145 # jump to bookmark
2146 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2147 if bkms.has_key(ps):
2148 target = bkms[ps]
2149 print '(bookmark:%s) -> %s' % (ps,target)
2150 ps = target
2151 else:
2152 if bkms:
2153 error("Bookmark '%s' not found. "
2154 "Use '%bookmark -l' to see your bookmarks." % ps)
2155 else:
2156 print "Bookmarks not set - use %bookmark <bookmarkname>"
2157 return
2158
2159 # at this point ps should point to the target dir
2160 if ps:
2161 try:
2162 os.chdir(os.path.expanduser(ps))
2163 except OSError:
2164 print sys.exc_info()[1]
2165 else:
2166 self.shell.user_ns['_dh'].append(os.getcwd())
2167 else:
2168 os.chdir(self.home_dir)
2169 self.shell.user_ns['_dh'].append(os.getcwd())
2170 if not 'q' in opts:
2171 print self.shell.user_ns['_dh'][-1]
2172
2173 def magic_dhist(self, parameter_s=''):
2174 """Print your history of visited directories.
2175
2176 %dhist -> print full history\\
2177 %dhist n -> print last n entries only\\
2178 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2179
2180 This history is automatically maintained by the %cd command, and
2181 always available as the global list variable _dh. You can use %cd -<n>
2182 to go to directory number <n>."""
2183
2184 dh = self.shell.user_ns['_dh']
2185 if parameter_s:
2186 try:
2187 args = map(int,parameter_s.split())
2188 except:
2189 self.arg_err(Magic.magic_dhist)
2190 return
2191 if len(args) == 1:
2192 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2193 elif len(args) == 2:
2194 ini,fin = args
2195 else:
2196 self.arg_err(Magic.magic_dhist)
2197 return
2198 else:
2199 ini,fin = 0,len(dh)
2200 nlprint(dh,
2201 header = 'Directory history (kept in _dh)',
2202 start=ini,stop=fin)
2203
2204 def magic_env(self, parameter_s=''):
2205 """List environment variables."""
2206
2207 # environ is an instance of UserDict
2208 return os.environ.data
2209
2210 def magic_pushd(self, parameter_s=''):
2211 """Place the current dir on stack and change directory.
2212
2213 Usage:\\
2214 %pushd ['dirname']
2215
2216 %pushd with no arguments does a %pushd to your home directory.
2217 """
2218 if parameter_s == '': parameter_s = '~'
2219 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2220 os.path.expanduser(self.dir_stack[0]):
2221 try:
2222 self.magic_cd(parameter_s)
2223 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2224 self.magic_dirs()
2225 except:
2226 print 'Invalid directory'
2227 else:
2228 print 'You are already there!'
2229
2230 def magic_popd(self, parameter_s=''):
2231 """Change to directory popped off the top of the stack.
2232 """
2233 if len (self.dir_stack) > 1:
2234 self.dir_stack.pop(0)
2235 self.magic_cd(self.dir_stack[0])
2236 print self.dir_stack[0]
2237 else:
2238 print "You can't remove the starting directory from the stack:",\
2239 self.dir_stack
2240
2241 def magic_dirs(self, parameter_s=''):
2242 """Return the current directory stack."""
2243
2244 return self.dir_stack[:]
2245
2246 def magic_sc(self, parameter_s=''):
2247 """Shell capture - execute a shell command and capture its output.
2248
2249 %sc [options] varname=command
2250
2251 IPython will run the given command using commands.getoutput(), and
2252 will then update the user's interactive namespace with a variable
2253 called varname, containing the value of the call. Your command can
2254 contain shell wildcards, pipes, etc.
2255
2256 The '=' sign in the syntax is mandatory, and the variable name you
2257 supply must follow Python's standard conventions for valid names.
2258
2259 Options:
2260
2261 -l: list output. Split the output on newlines into a list before
2262 assigning it to the given variable. By default the output is stored
2263 as a single string.
2264
2265 -v: verbose. Print the contents of the variable.
2266
2267 In most cases you should not need to split as a list, because the
2268 returned value is a special type of string which can automatically
2269 provide its contents either as a list (split on newlines) or as a
2270 space-separated string. These are convenient, respectively, either
2271 for sequential processing or to be passed to a shell command.
2272
2273 For example:
2274
2275 # Capture into variable a
2276 In [9]: sc a=ls *py
2277
2278 # a is a string with embedded newlines
2279 In [10]: a
2280 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2281
2282 # which can be seen as a list:
2283 In [11]: a.l
2284 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2285
2286 # or as a whitespace-separated string:
2287 In [12]: a.s
2288 Out[12]: 'setup.py win32_manual_post_install.py'
2289
2290 # a.s is useful to pass as a single command line:
2291 In [13]: !wc -l $a.s
2292 146 setup.py
2293 130 win32_manual_post_install.py
2294 276 total
2295
2296 # while the list form is useful to loop over:
2297 In [14]: for f in a.l:
2298 ....: !wc -l $f
2299 ....:
2300 146 setup.py
2301 130 win32_manual_post_install.py
2302
2303 Similiarly, the lists returned by the -l option are also special, in
2304 the sense that you can equally invoke the .s attribute on them to
2305 automatically get a whitespace-separated string from their contents:
2306
2307 In [1]: sc -l b=ls *py
2308
2309 In [2]: b
2310 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2311
2312 In [3]: b.s
2313 Out[3]: 'setup.py win32_manual_post_install.py'
2314
2315 In summary, both the lists and strings used for ouptut capture have
2316 the following special attributes:
2317
2318 .l (or .list) : value as list.
2319 .n (or .nlstr): value as newline-separated string.
2320 .s (or .spstr): value as space-separated string.
2321 """
2322
2323 opts,args = self.parse_options(parameter_s,'lv')
2324 # Try to get a variable name and command to run
2325 try:
2326 # the variable name must be obtained from the parse_options
2327 # output, which uses shlex.split to strip options out.
2328 var,_ = args.split('=',1)
2329 var = var.strip()
2330 # But the the command has to be extracted from the original input
2331 # parameter_s, not on what parse_options returns, to avoid the
2332 # quote stripping which shlex.split performs on it.
2333 _,cmd = parameter_s.split('=',1)
2334 except ValueError:
2335 var,cmd = '',''
2336 if not var:
2337 error('you must specify a variable to assign the command to.')
2338 return
2339 # If all looks ok, proceed
2340 out,err = self.shell.getoutputerror(cmd)
2341 if err:
2342 print >> Term.cerr,err
2343 if opts.has_key('l'):
2344 out = SList(out.split('\n'))
2345 else:
2346 out = LSString(out)
2347 if opts.has_key('v'):
2348 print '%s ==\n%s' % (var,pformat(out))
2349 self.shell.user_ns.update({var:out})
2350
2351 def magic_sx(self, parameter_s=''):
2352 """Shell execute - run a shell command and capture its output.
2353
2354 %sx command
2355
2356 IPython will run the given command using commands.getoutput(), and
2357 return the result formatted as a list (split on '\\n'). Since the
2358 output is _returned_, it will be stored in ipython's regular output
2359 cache Out[N] and in the '_N' automatic variables.
2360
2361 Notes:
2362
2363 1) If an input line begins with '!!', then %sx is automatically
2364 invoked. That is, while:
2365 !ls
2366 causes ipython to simply issue system('ls'), typing
2367 !!ls
2368 is a shorthand equivalent to:
2369 %sx ls
2370
2371 2) %sx differs from %sc in that %sx automatically splits into a list,
2372 like '%sc -l'. The reason for this is to make it as easy as possible
2373 to process line-oriented shell output via further python commands.
2374 %sc is meant to provide much finer control, but requires more
2375 typing.
2376
2377 3) Just like %sc -l, this is a list with special attributes:
2378
2379 .l (or .list) : value as list.
2380 .n (or .nlstr): value as newline-separated string.
2381 .s (or .spstr): value as whitespace-separated string.
2382
2383 This is very useful when trying to use such lists as arguments to
2384 system commands."""
2385
2386 if parameter_s:
2387 out,err = self.shell.getoutputerror(parameter_s)
2388 if err:
2389 print >> Term.cerr,err
2390 return SList(out.split('\n'))
2391
2392 def magic_bg(self, parameter_s=''):
2393 """Run a job in the background, in a separate thread.
2394
2395 For example,
2396
2397 %bg myfunc(x,y,z=1)
2398
2399 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2400 execution starts, a message will be printed indicating the job
2401 number. If your job number is 5, you can use
2402
2403 myvar = jobs.result(5) or myvar = jobs[5].result
2404
2405 to assign this result to variable 'myvar'.
2406
2407 IPython has a job manager, accessible via the 'jobs' object. You can
2408 type jobs? to get more information about it, and use jobs.<TAB> to see
2409 its attributes. All attributes not starting with an underscore are
2410 meant for public use.
2411
2412 In particular, look at the jobs.new() method, which is used to create
2413 new jobs. This magic %bg function is just a convenience wrapper
2414 around jobs.new(), for expression-based jobs. If you want to create a
2415 new job with an explicit function object and arguments, you must call
2416 jobs.new() directly.
2417
2418 The jobs.new docstring also describes in detail several important
2419 caveats associated with a thread-based model for background job
2420 execution. Type jobs.new? for details.
2421
2422 You can check the status of all jobs with jobs.status().
2423
2424 The jobs variable is set by IPython into the Python builtin namespace.
2425 If you ever declare a variable named 'jobs', you will shadow this
2426 name. You can either delete your global jobs variable to regain
2427 access to the job manager, or make a new name and assign it manually
2428 to the manager (stored in IPython's namespace). For example, to
2429 assign the job manager to the Jobs name, use:
2430
2431 Jobs = __builtins__.jobs"""
2432
2433 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2434
2435 def magic_bookmark(self, parameter_s=''):
2436 """Manage IPython's bookmark system.
2437
2438 %bookmark <name> - set bookmark to current dir
2439 %bookmark <name> <dir> - set bookmark to <dir>
2440 %bookmark -l - list all bookmarks
2441 %bookmark -d <name> - remove bookmark
2442 %bookmark -r - remove all bookmarks
2443
2444 You can later on access a bookmarked folder with:
2445 %cd -b <name>
2446 or simply '%cd <name>' if there is no directory called <name> AND
2447 there is such a bookmark defined.
2448
2449 Your bookmarks persist through IPython sessions, but they are
2450 associated with each profile."""
2451
2452 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2453 if len(args) > 2:
2454 error('You can only give at most two arguments')
2455 return
2456
2457 bkms = self.shell.persist.get('bookmarks',{})
2458
2459 if opts.has_key('d'):
2460 try:
2461 todel = args[0]
2462 except IndexError:
2463 error('You must provide a bookmark to delete')
2464 else:
2465 try:
2466 del bkms[todel]
2467 except:
2468 error("Can't delete bookmark '%s'" % todel)
2469 elif opts.has_key('r'):
2470 bkms = {}
2471 elif opts.has_key('l'):
2472 bks = bkms.keys()
2473 bks.sort()
2474 if bks:
2475 size = max(map(len,bks))
2476 else:
2477 size = 0
2478 fmt = '%-'+str(size)+'s -> %s'
2479 print 'Current bookmarks:'
2480 for bk in bks:
2481 print fmt % (bk,bkms[bk])
2482 else:
2483 if not args:
2484 error("You must specify the bookmark name")
2485 elif len(args)==1:
2486 bkms[args[0]] = os.getcwd()
2487 elif len(args)==2:
2488 bkms[args[0]] = args[1]
2489 self.persist['bookmarks'] = bkms
2490 # end Magic
@@ -0,0 +1,398 b''
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
3
4 Uses syntax highlighting for presenting the various information elements.
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
8
9 $Id: OInspect.py 575 2005-04-08 14:16:44Z fperez $
10 """
11
12 #*****************************************************************************
13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
14 #
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
17 #*****************************************************************************
18
19 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
22
23 __all__ = ['Inspector','InspectColors']
24
25 # stdlib modules
26 import inspect,linecache,types,StringIO,string
27
28 # IPython's own
29 from IPython.Itpl import itpl
30 from IPython.genutils import page,indent,Term
31 from IPython import PyColorize
32 from IPython.ColorANSI import *
33
34 #****************************************************************************
35 # Builtin color schemes
36
37 Colors = TermColors # just a shorthand
38
39 # Build a few color schemes
40 NoColor = ColorScheme(
41 'NoColor',{
42 'header' : Colors.NoColor,
43 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
44 } )
45
46 LinuxColors = ColorScheme(
47 'Linux',{
48 'header' : Colors.LightRed,
49 'normal' : Colors.Normal # color off (usu. Colors.Normal)
50 } )
51
52 LightBGColors = ColorScheme(
53 'LightBG',{
54 'header' : Colors.Red,
55 'normal' : Colors.Normal # color off (usu. Colors.Normal)
56 } )
57
58 # Build table of color schemes (needed by the parser)
59 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
60 'Linux')
61
62 #****************************************************************************
63 # Auxiliary functions
64 def getdoc(obj):
65 """Stable wrapper around inspect.getdoc.
66
67 This can't crash because of attribute problems.
68
69 It also attempts to call a getdoc() method on the given object. This
70 allows objects which provide their docstrings via non-standard mechanisms
71 (like Pyro proxies) to still be inspected by ipython's ? system."""
72
73 ds = None # default return value
74 try:
75 ds = inspect.getdoc(obj)
76 except:
77 # Harden against an inspect failure, which can occur with
78 # SWIG-wrapped extensions.
79 pass
80 # Allow objects to offer customized documentation via a getdoc method:
81 try:
82 ds2 = obj.getdoc()
83 except:
84 pass
85 else:
86 # if we get extra info, we add it to the normal docstring.
87 if ds is None:
88 ds = ds2
89 else:
90 ds = '%s\n%s' % (ds,ds2)
91 return ds
92
93 #****************************************************************************
94 # Class definitions
95
96 class myStringIO(StringIO.StringIO):
97 """Adds a writeln method to normal StringIO."""
98 def writeln(self,*arg,**kw):
99 """Does a write() and then a write('\n')"""
100 self.write(*arg,**kw)
101 self.write('\n')
102
103 class Inspector:
104 def __init__(self,color_table,code_color_table,scheme):
105 self.color_table = color_table
106 self.parser = PyColorize.Parser(code_color_table,out='str')
107 self.format = self.parser.format
108 self.set_active_scheme(scheme)
109
110 def __getargspec(self,obj):
111 """Get the names and default values of a function's arguments.
112
113 A tuple of four things is returned: (args, varargs, varkw, defaults).
114 'args' is a list of the argument names (it may contain nested lists).
115 'varargs' and 'varkw' are the names of the * and ** arguments or None.
116 'defaults' is an n-tuple of the default values of the last n arguments.
117
118 Modified version of inspect.getargspec from the Python Standard
119 Library."""
120
121 if inspect.isfunction(obj):
122 func_obj = obj
123 elif inspect.ismethod(obj):
124 func_obj = obj.im_func
125 else:
126 raise TypeError, 'arg is not a Python function'
127 args, varargs, varkw = inspect.getargs(func_obj.func_code)
128 return args, varargs, varkw, func_obj.func_defaults
129
130 def __getdef(self,obj,oname=''):
131 """Return the definition header for any callable object.
132
133 If any exception is generated, None is returned instead and the
134 exception is suppressed."""
135
136 try:
137 return oname + inspect.formatargspec(*self.__getargspec(obj))
138 except:
139 return None
140
141 def __head(self,h):
142 """Return a header string with proper colors."""
143 return '%s%s%s' % (self.color_table.active_colors.header,h,
144 self.color_table.active_colors.normal)
145
146 def set_active_scheme(self,scheme):
147 self.color_table.set_active_scheme(scheme)
148 self.parser.color_table.set_active_scheme(scheme)
149
150 def noinfo(self,msg,oname):
151 """Generic message when no information is found."""
152 print 'No %s found' % msg,
153 if oname:
154 print 'for %s' % oname
155 else:
156 print
157
158 def pdef(self,obj,oname=''):
159 """Print the definition header for any callable object.
160
161 If the object is a class, print the constructor information."""
162
163 if not callable(obj):
164 print 'Object is not callable.'
165 return
166
167 header = ''
168 if type(obj) is types.ClassType:
169 header = self.__head('Class constructor information:\n')
170 obj = obj.__init__
171 elif type(obj) is types.InstanceType:
172 obj = obj.__call__
173
174 output = self.__getdef(obj,oname)
175 if output is None:
176 self.noinfo('definition header',oname)
177 else:
178 print >>Term.cout, header,self.format(output),
179
180 def pdoc(self,obj,oname='',formatter = None):
181 """Print the docstring for any object.
182
183 Optional:
184 -formatter: a function to run the docstring through for specially
185 formatted docstrings."""
186
187 head = self.__head # so that itpl can find it even if private
188 ds = getdoc(obj)
189 if formatter:
190 ds = formatter(ds)
191 if type(obj) is types.ClassType:
192 init_ds = getdoc(obj.__init__)
193 output = itpl('$head("Class Docstring:")\n'
194 '$indent(ds)\n'
195 '$head("Constructor Docstring"):\n'
196 '$indent(init_ds)')
197 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
198 call_ds = getdoc(obj.__call__)
199 if call_ds:
200 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
201 '$head("Calling Docstring:")\n$indent(call_ds)')
202 else:
203 output = ds
204 else:
205 output = ds
206 if output is None:
207 self.noinfo('documentation',oname)
208 return
209 page(output)
210
211 def psource(self,obj,oname=''):
212 """Print the source code for an object."""
213
214 # Flush the source cache because inspect can return out-of-date source
215 linecache.checkcache()
216 try:
217 src = inspect.getsource(obj)
218 except:
219 self.noinfo('source',oname)
220 else:
221 page(self.format(src))
222
223 def pfile(self,obj,oname=''):
224 """Show the whole file where an object was defined."""
225 try:
226 sourcelines,lineno = inspect.getsourcelines(obj)
227 except:
228 self.noinfo('file',oname)
229 else:
230 # run contents of file through pager starting at line
231 # where the object is defined
232 page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
233
234 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
235 """Show detailed information about an object.
236
237 Optional arguments:
238
239 - oname: name of the variable pointing to the object.
240
241 - formatter: special formatter for docstrings (see pdoc)
242
243 - info: a structure with some information fields which may have been
244 precomputed already.
245
246 - detail_level: if set to 1, more information is given.
247 """
248
249 obj_type = type(obj)
250
251 header = self.__head
252 if info is None:
253 ismagic = 0
254 isalias = 0
255 ospace = ''
256 else:
257 ismagic = info.ismagic
258 isalias = info.isalias
259 ospace = info.namespace
260 # Get docstring, special-casing aliases:
261 if isalias:
262 ds = "Alias to the system command:\n %s" % obj[1]
263 else:
264 ds = getdoc(obj)
265 if formatter is not None:
266 ds = formatter(ds)
267
268 # store output in a list which gets joined with \n at the end.
269 out = myStringIO()
270
271 string_max = 200 # max size of strings to show (snipped if longer)
272 shalf = int((string_max -5)/2)
273
274 if ismagic:
275 obj_type_name = 'Magic function'
276 elif isalias:
277 obj_type_name = 'System alias'
278 else:
279 obj_type_name = obj_type.__name__
280 out.writeln(header('Type:\t\t')+obj_type_name)
281
282 try:
283 bclass = obj.__class__
284 out.writeln(header('Base Class:\t')+str(bclass))
285 except: pass
286
287 # String form, but snip if too long in ? form (full in ??)
288 try:
289 ostr = str(obj)
290 str_head = 'String Form:'
291 if not detail_level and len(ostr)>string_max:
292 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
293 ostr = ("\n" + " " * len(str_head.expandtabs())).\
294 join(map(string.strip,ostr.split("\n")))
295 if ostr.find('\n') > -1:
296 # Print multi-line strings starting at the next line.
297 str_sep = '\n'
298 else:
299 str_sep = '\t'
300 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
301 except:
302 pass
303
304 if ospace:
305 out.writeln(header('Namespace:\t')+ospace)
306
307 # Length (for strings and lists)
308 try:
309 length = str(len(obj))
310 out.writeln(header('Length:\t\t')+length)
311 except: pass
312
313 # Filename where object was defined
314 try:
315 file = inspect.getabsfile(obj)
316 if file.endswith('<string>'):
317 file = 'Dynamically generated function. No source code available.'
318 out.writeln(header('File:\t\t')+file)
319 except: pass
320
321 # reconstruct the function definition and print it:
322 defln = self.__getdef(obj,oname)
323 if defln:
324 out.write(header('Definition:\t')+self.format(defln))
325
326 # Docstrings only in detail 0 mode, since source contains them (we
327 # avoid repetitions). If source fails, we add them back, see below.
328 if ds and detail_level == 0:
329 out.writeln(header('Docstring:\n') + indent(ds))
330
331 # Original source code for any callable
332 if detail_level:
333 # Flush the source cache because inspect can return out-of-date source
334 linecache.checkcache()
335 try:
336 source = self.format(inspect.getsource(obj))
337 out.write(header('Source:\n')+source.rstrip())
338 except:
339 if ds:
340 out.writeln(header('Docstring:\n') + indent(ds))
341
342 # Constructor docstring for classes
343 if obj_type is types.ClassType:
344 # reconstruct the function definition and print it:
345 try:
346 obj_init = obj.__init__
347 except AttributeError:
348 init_def = init_ds = None
349 else:
350 init_def = self.__getdef(obj_init,oname)
351 init_ds = getdoc(obj_init)
352
353 if init_def or init_ds:
354 out.writeln(header('\nConstructor information:'))
355 if init_def:
356 out.write(header('Definition:\t')+ self.format(init_def))
357 if init_ds:
358 out.writeln(header('Docstring:\n') + indent(init_ds))
359 # and class docstring for instances:
360 elif obj_type is types.InstanceType:
361
362 # First, check whether the instance docstring is identical to the
363 # class one, and print it separately if they don't coincide. In
364 # most cases they will, but it's nice to print all the info for
365 # objects which use instance-customized docstrings.
366 if ds:
367 class_ds = getdoc(obj.__class__)
368 if class_ds and ds != class_ds:
369 out.writeln(header('Class Docstring:\n') +
370 indent(class_ds))
371
372 # Next, try to show constructor docstrings
373 try:
374 init_ds = getdoc(obj.__init__)
375 except AttributeError:
376 init_ds = None
377 if init_ds:
378 out.writeln(header('Constructor Docstring:\n') +
379 indent(init_ds))
380
381 # Call form docstring for callable instances
382 if hasattr(obj,'__call__'):
383 out.writeln(header('Callable:\t')+'Yes')
384 call_def = self.__getdef(obj.__call__,oname)
385 if call_def is None:
386 out.write(header('Call def:\t')+
387 'Calling definition not available.')
388 else:
389 out.write(header('Call def:\t')+self.format(call_def))
390 call_ds = getdoc(obj.__call__)
391 if call_ds:
392 out.writeln(header('Call docstring:\n') + indent(call_ds))
393
394 # Finally send to printer/pager
395 output = out.getvalue()
396 if output:
397 page(output)
398 # end pinfo
@@ -0,0 +1,262 b''
1 # -*- coding: utf-8 -*-
2 """Class to trap stdout and stderr and log them separately.
3
4 $Id: OutputTrap.py 542 2005-03-18 09:16:04Z fperez $"""
5
6 #*****************************************************************************
7 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 #
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
12
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
16
17 import exceptions,sys
18 from cStringIO import StringIO
19
20 class OutputTrapError(exceptions.Exception):
21 """Exception for OutputTrap class."""
22
23 def __init__(self,args=None):
24 exceptions.Exception.__init__(self)
25 self.args = args
26
27 class OutputTrap:
28
29 """Class to trap standard output and standard error. They get logged in
30 StringIO objects which are available as <instance>.out and
31 <instance>.err. The class also offers summary methods which format this
32 data a bit.
33
34 A word of caution: because it blocks messages, using this class can make
35 debugging very tricky. If you are having bizarre problems silently, try
36 turning your output traps off for a while. You can call the constructor
37 with the parameter debug=1 for these cases. This turns actual trapping
38 off, but you can keep the rest of your code unchanged (this has already
39 been a life saver).
40
41 Example:
42
43 # config: trapper with a line of dots as log separator (final '\\n' needed)
44 config = OutputTrap('Config','Out ','Err ','.'*80+'\\n')
45
46 # start trapping output
47 config.trap_all()
48
49 # now all output is logged ...
50 # do stuff...
51
52 # output back to normal:
53 config.release_all()
54
55 # print all that got logged:
56 print config.summary()
57
58 # print individual raw data:
59 print config.out.getvalue()
60 print config.err.getvalue()
61 """
62
63 def __init__(self,name='Generic Output Trap',
64 out_head='Standard Output. ',err_head='Standard Error. ',
65 sum_sep='\n',debug=0,trap_out=0,trap_err=0,
66 quiet_out=0,quiet_err=0):
67 self.name = name
68 self.out_head = out_head
69 self.err_head = err_head
70 self.sum_sep = sum_sep
71 self.out = StringIO()
72 self.err = StringIO()
73 self.out_save = None
74 self.err_save = None
75 self.debug = debug
76 self.quiet_out = quiet_out
77 self.quiet_err = quiet_err
78 if trap_out:
79 self.trap_out()
80 if trap_err:
81 self.trap_err()
82
83 def trap_out(self):
84 """Trap and log stdout."""
85 if sys.stdout is self.out:
86 raise OutputTrapError,'You are already trapping stdout.'
87 if not self.debug:
88 self._out_save = sys.stdout
89 sys.stdout = self.out
90
91 def release_out(self):
92 """Release stdout."""
93 if not self.debug:
94 if not sys.stdout is self.out:
95 raise OutputTrapError,'You are not trapping stdout.'
96 sys.stdout = self._out_save
97 self.out_save = None
98
99 def summary_out(self):
100 """Return as a string the log from stdout."""
101 out = self.out.getvalue()
102 if out:
103 if self.quiet_out:
104 return out
105 else:
106 return self.out_head + 'Log by '+ self.name + ':\n' + out
107 else:
108 return ''
109
110 def flush_out(self):
111 """Flush the stdout log. All data held in the log is lost."""
112
113 self.out.close()
114 self.out = StringIO()
115
116 def trap_err(self):
117 """Trap and log stderr."""
118 if sys.stderr is self.err:
119 raise OutputTrapError,'You are already trapping stderr.'
120 if not self.debug:
121 self._err_save = sys.stderr
122 sys.stderr = self.err
123
124 def release_err(self):
125 """Release stderr."""
126 if not self.debug:
127 if not sys.stderr is self.err:
128 raise OutputTrapError,'You are not trapping stderr.'
129 sys.stderr = self._err_save
130 self.err_save = None
131
132 def summary_err(self):
133 """Return as a string the log from stderr."""
134 err = self.err.getvalue()
135 if err:
136 if self.quiet_err:
137 return err
138 else:
139 return self.err_head + 'Log by '+ self.name + ':\n' + err
140 else:
141 return ''
142
143 def flush_err(self):
144 """Flush the stdout log. All data held in the log is lost."""
145
146 self.err.close()
147 self.err = StringIO()
148
149 def trap_all(self):
150 """Trap and log both stdout and stderr.
151
152 Cacthes and discards OutputTrapError exceptions raised."""
153 try:
154 self.trap_out()
155 except OutputTrapError:
156 pass
157 try:
158 self.trap_err()
159 except OutputTrapError:
160 pass
161
162 def release_all(self):
163 """Release both stdout and stderr.
164
165 Cacthes and discards OutputTrapError exceptions raised."""
166 try:
167 self.release_out()
168 except OutputTrapError:
169 pass
170 try:
171 self.release_err()
172 except OutputTrapError:
173 pass
174
175 def summary_all(self):
176 """Return as a string the log from stdout and stderr, prepending a separator
177 to each (defined in __init__ as sum_sep)."""
178 sum = ''
179 sout = self.summary_out()
180 if sout:
181 sum += self.sum_sep + sout
182 serr = self.summary_err()
183 if serr:
184 sum += '\n'+self.sum_sep + serr
185 return sum
186
187 def flush_all(self):
188 """Flush stdout and stderr"""
189 self.flush_out()
190 self.flush_err()
191
192 # a few shorthands
193 trap = trap_all
194 release = release_all
195 summary = summary_all
196 flush = flush_all
197 # end OutputTrap
198
199
200 #****************************************************************************
201 # Module testing. Incomplete, I'm lazy...
202
203 def _test_all():
204
205 """Module testing functions, activated when the module is called as a
206 script (not imported)."""
207
208 # Put tests for this module in here.
209 # Define them as nested functions so they don't clobber the
210 # pydoc-generated docs
211
212 def _test_():
213 name = ''
214 print '#'*50+'\nRunning test for ' + name
215 # ...
216 print 'Finished test for '+ name +'\n'+'#'*50
217
218 def _test_OutputTrap():
219 trap = OutputTrap(name = 'Test Trap', sum_sep = '.'*50+'\n',
220 out_head = 'SOut. ', err_head = 'SErr. ')
221
222 name = 'OutputTrap class'
223 print '#'*50+'\nRunning test for ' + name
224 print 'Trapping out'
225 trap.trap_out()
226 print >>sys.stdout, '>>stdout. stdout is trapped.'
227 print >>sys.stderr, '>>stderr. stdout is trapped.'
228 trap.release_out()
229 print trap.summary_out()
230
231 print 'Trapping err'
232 trap.trap_err()
233 print >>sys.stdout, '>>stdout. stderr is trapped.'
234 print >>sys.stderr, '>>stderr. stderr is trapped.'
235 trap.release_err()
236 print trap.summary_err()
237
238 print 'Trapping all (no flushing)'
239 trap.trap_all()
240 print >>sys.stdout, '>>stdout. stdout/err is trapped.'
241 print >>sys.stderr, '>>stderr. stdout/err is trapped.'
242 trap.release_all()
243 print trap.summary_all()
244
245 print 'Trapping all (flushing first)'
246 trap.flush()
247 trap.trap_all()
248 print >>sys.stdout, '>>stdout. stdout/err is trapped.'
249 print >>sys.stderr, '>>stderr. stdout/err is trapped.'
250 trap.release_all()
251 print trap.summary_all()
252 print 'Finished test for '+ name +'\n'+'#'*50
253
254 # call the actual tests here:
255 _test_OutputTrap()
256
257
258 if __name__=="__main__":
259 # _test_all() # XXX BROKEN.
260 pass
261
262 #************************ end of file <OutputTrap.py> ************************
This diff has been collapsed as it changes many lines, (574 lines changed) Show them Hide them
@@ -0,0 +1,574 b''
1 # -*- coding: utf-8 -*-
2 """
3 Classes for handling input/output prompts.
4
5 $Id: Prompts.py 564 2005-03-26 22:43:58Z fperez $"""
6
7 #*****************************************************************************
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
13
14 from IPython import Release
15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 __license__ = Release.license
17 __version__ = Release.version
18
19 #****************************************************************************
20 # Required modules
21 import __builtin__
22 import os,sys,socket
23 import time
24 from pprint import pprint,pformat
25
26 # IPython's own
27 from IPython.genutils import *
28 from IPython.Struct import Struct
29 from IPython.Magic import Macro
30 from IPython.Itpl import ItplNS
31 from IPython import ColorANSI
32
33 #****************************************************************************
34 #Color schemes for Prompts.
35
36 PromptColors = ColorANSI.ColorSchemeTable()
37 InputColors = ColorANSI.InputTermColors # just a shorthand
38 Colors = ColorANSI.TermColors # just a shorthand
39
40 PromptColors.add_scheme(ColorANSI.ColorScheme(
41 'NoColor',
42 in_prompt = InputColors.NoColor, # Input prompt
43 in_number = InputColors.NoColor, # Input prompt number
44 in_prompt2 = InputColors.NoColor, # Continuation prompt
45 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
46
47 out_prompt = Colors.NoColor, # Output prompt
48 out_number = Colors.NoColor, # Output prompt number
49
50 normal = Colors.NoColor # color off (usu. Colors.Normal)
51 ))
52 # make some schemes as instances so we can copy them for modification easily:
53 __PColLinux = ColorANSI.ColorScheme(
54 'Linux',
55 in_prompt = InputColors.Green,
56 in_number = InputColors.LightGreen,
57 in_prompt2 = InputColors.Green,
58 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
59
60 out_prompt = Colors.Red,
61 out_number = Colors.LightRed,
62
63 normal = Colors.Normal
64 )
65 # Don't forget to enter it into the table!
66 PromptColors.add_scheme(__PColLinux)
67 # Slightly modified Linux for light backgrounds
68 __PColLightBG = ColorANSI.ColorScheme('LightBG',**__PColLinux.colors.dict().copy())
69
70 __PColLightBG.colors.update(
71 in_prompt = InputColors.Blue,
72 in_number = InputColors.LightBlue,
73 in_prompt2 = InputColors.Blue
74 )
75 PromptColors.add_scheme(__PColLightBG)
76
77 del Colors,InputColors
78
79 #-----------------------------------------------------------------------------
80 def multiple_replace(dict, text):
81 """ Replace in 'text' all occurences of any key in the given
82 dictionary by its corresponding value. Returns the new string."""
83
84 # Function by Xavier Defrang, originally found at:
85 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
86
87 # Create a regular expression from the dictionary keys
88 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
89 # For each match, look-up corresponding value in dictionary
90 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
91
92 #-----------------------------------------------------------------------------
93 # Special characters that can be used in prompt templates, mainly bash-like
94
95 # If $HOME isn't defined (Windows), make it an absurd string so that it can
96 # never be expanded out into '~'. Basically anything which can never be a
97 # reasonable directory name will do, we just want the $HOME -> '~' operation
98 # to become a no-op. We pre-compute $HOME here so it's not done on every
99 # prompt call.
100
101 # FIXME:
102
103 # - This should be turned into a class which does proper namespace management,
104 # since the prompt specials need to be evaluated in a certain namespace.
105 # Currently it's just globals, which need to be managed manually by code
106 # below.
107
108 # - I also need to split up the color schemes from the prompt specials
109 # somehow. I don't have a clean design for that quite yet.
110
111 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
112
113 # We precompute a few more strings here for the prompt_specials, which are
114 # fixed once ipython starts. This reduces the runtime overhead of computing
115 # prompt strings.
116 USER = os.environ.get("USER")
117 HOSTNAME = socket.gethostname()
118 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
119 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
120
121 prompt_specials_color = {
122 # Prompt/history count
123 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
124 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
125 # Prompt/history count, with the actual digits replaced by dots. Used
126 # mainly in continuation prompts (prompt_in2)
127 '\\D': '${"."*len(str(self.cache.prompt_count))}',
128 # Current working directory
129 '\\w': '${os.getcwd()}',
130 # Current time
131 '\\t' : '${time.strftime("%H:%M:%S")}',
132 # Basename of current working directory.
133 # (use os.sep to make this portable across OSes)
134 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
135 # These X<N> are an extension to the normal bash prompts. They return
136 # N terms of the path, after replacing $HOME with '~'
137 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
138 '\\X1': '${self.cwd_filt(1)}',
139 '\\X2': '${self.cwd_filt(2)}',
140 '\\X3': '${self.cwd_filt(3)}',
141 '\\X4': '${self.cwd_filt(4)}',
142 '\\X5': '${self.cwd_filt(5)}',
143 # Y<N> are similar to X<N>, but they show '~' if it's the directory
144 # N+1 in the list. Somewhat like %cN in tcsh.
145 '\\Y0': '${self.cwd_filt2(0)}',
146 '\\Y1': '${self.cwd_filt2(1)}',
147 '\\Y2': '${self.cwd_filt2(2)}',
148 '\\Y3': '${self.cwd_filt2(3)}',
149 '\\Y4': '${self.cwd_filt2(4)}',
150 '\\Y5': '${self.cwd_filt2(5)}',
151 # Hostname up to first .
152 '\\h': HOSTNAME_SHORT,
153 # Full hostname
154 '\\H': HOSTNAME,
155 # Username of current user
156 '\\u': USER,
157 # Escaped '\'
158 '\\\\': '\\',
159 # Newline
160 '\\n': '\n',
161 # Carriage return
162 '\\r': '\r',
163 # Release version
164 '\\v': __version__,
165 # Root symbol ($ or #)
166 '\\$': ROOT_SYMBOL,
167 }
168
169 # A copy of the prompt_specials dictionary but with all color escapes removed,
170 # so we can correctly compute the prompt length for the auto_rewrite method.
171 prompt_specials_nocolor = prompt_specials_color.copy()
172 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
173 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
174
175 # Add in all the InputTermColors color escapes as valid prompt characters.
176 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
177 # with a color name which may begin with a letter used by any other of the
178 # allowed specials. This of course means that \\C will never be allowed for
179 # anything else.
180 input_colors = ColorANSI.InputTermColors
181 for _color in dir(input_colors):
182 if _color[0] != '_':
183 c_name = '\\C_'+_color
184 prompt_specials_color[c_name] = getattr(input_colors,_color)
185 prompt_specials_nocolor[c_name] = ''
186
187 # we default to no color for safety. Note that prompt_specials is a global
188 # variable used by all prompt objects.
189 prompt_specials = prompt_specials_nocolor
190
191 #-----------------------------------------------------------------------------
192 def str_safe(arg):
193 """Convert to a string, without ever raising an exception.
194
195 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
196 error message."""
197
198 try:
199 return str(arg)
200 except Exception,msg:
201 return '<ERROR: %s>' % msg
202
203 class BasePrompt:
204 """Interactive prompt similar to Mathematica's."""
205 def __init__(self,cache,sep,prompt,pad_left=False):
206
207 # Hack: we access information about the primary prompt through the
208 # cache argument. We need this, because we want the secondary prompt
209 # to be aligned with the primary one. Color table info is also shared
210 # by all prompt classes through the cache. Nice OO spaghetti code!
211 self.cache = cache
212 self.sep = sep
213
214 # regexp to count the number of spaces at the end of a prompt
215 # expression, useful for prompt auto-rewriting
216 self.rspace = re.compile(r'(\s*)$')
217 # Flag to left-pad prompt strings to match the length of the primary
218 # prompt
219 self.pad_left = pad_left
220 # Set template to create each actual prompt (where numbers change)
221 self.p_template = prompt
222 self.set_p_str()
223
224 def set_p_str(self):
225 """ Set the interpolating prompt strings.
226
227 This must be called every time the color settings change, because the
228 prompt_specials global may have changed."""
229
230 import os,time # needed in locals for prompt string handling
231 loc = locals()
232 self.p_str = ItplNS('%s%s%s' %
233 ('${self.sep}${self.col_p}',
234 multiple_replace(prompt_specials, self.p_template),
235 '${self.col_norm}'),self.cache.user_ns,loc)
236
237 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
238 self.p_template),
239 self.cache.user_ns,loc)
240
241 def write(self,msg): # dbg
242 sys.stdout.write(msg)
243 return ''
244
245 def __str__(self):
246 """Return a string form of the prompt.
247
248 This for is useful for continuation and output prompts, since it is
249 left-padded to match lengths with the primary one (if the
250 self.pad_left attribute is set)."""
251
252 out_str = str_safe(self.p_str)
253 if self.pad_left:
254 # We must find the amount of padding required to match lengths,
255 # taking the color escapes (which are invisible on-screen) into
256 # account.
257 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
258 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
259 return format % out_str
260 else:
261 return out_str
262
263 # these path filters are put in as methods so that we can control the
264 # namespace where the prompt strings get evaluated
265 def cwd_filt(self,depth):
266 """Return the last depth elements of the current working directory.
267
268 $HOME is always replaced with '~'.
269 If depth==0, the full path is returned."""
270
271 cwd = os.getcwd().replace(HOME,"~")
272 out = os.sep.join(cwd.split(os.sep)[-depth:])
273 if out:
274 return out
275 else:
276 return os.sep
277
278 def cwd_filt2(self,depth):
279 """Return the last depth elements of the current working directory.
280
281 $HOME is always replaced with '~'.
282 If depth==0, the full path is returned."""
283
284 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
285 if '~' in cwd and len(cwd) == depth+1:
286 depth += 1
287 out = os.sep.join(cwd[-depth:])
288 if out:
289 return out
290 else:
291 return os.sep
292
293 class Prompt1(BasePrompt):
294 """Input interactive prompt similar to Mathematica's."""
295
296 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
297 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
298
299 def set_colors(self):
300 self.set_p_str()
301 Colors = self.cache.color_table.active_colors # shorthand
302 self.col_p = Colors.in_prompt
303 self.col_num = Colors.in_number
304 self.col_norm = Colors.in_normal
305 # We need a non-input version of these escapes for the '--->'
306 # auto-call prompts used in the auto_rewrite() method.
307 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
308 self.col_norm_ni = Colors.normal
309
310 def __str__(self):
311 self.cache.prompt_count += 1
312 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
313 return str_safe(self.p_str)
314
315 def auto_rewrite(self):
316 """Print a string of the form '--->' which lines up with the previous
317 input string. Useful for systems which re-write the user input when
318 handling automatically special syntaxes."""
319
320 curr = str(self.cache.last_prompt)
321 nrspaces = len(self.rspace.search(curr).group())
322 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
323 ' '*nrspaces,self.col_norm_ni)
324
325 class PromptOut(BasePrompt):
326 """Output interactive prompt similar to Mathematica's."""
327
328 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
329 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
330 if not self.p_template:
331 self.__str__ = lambda: ''
332
333 def set_colors(self):
334 self.set_p_str()
335 Colors = self.cache.color_table.active_colors # shorthand
336 self.col_p = Colors.out_prompt
337 self.col_num = Colors.out_number
338 self.col_norm = Colors.normal
339
340 class Prompt2(BasePrompt):
341 """Interactive continuation prompt."""
342
343 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
344 self.cache = cache
345 self.p_template = prompt
346 self.pad_left = pad_left
347 self.set_p_str()
348
349 def set_p_str(self):
350 import os,time # needed in locals for prompt string handling
351 loc = locals()
352 self.p_str = ItplNS('%s%s%s' %
353 ('${self.col_p2}',
354 multiple_replace(prompt_specials, self.p_template),
355 '$self.col_norm'),
356 self.cache.user_ns,loc)
357 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
358 self.p_template),
359 self.cache.user_ns,loc)
360
361 def set_colors(self):
362 self.set_p_str()
363 Colors = self.cache.color_table.active_colors
364 self.col_p2 = Colors.in_prompt2
365 self.col_norm = Colors.in_normal
366 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
367 # updated their prompt_in2 definitions. Remove eventually.
368 self.col_p = Colors.out_prompt
369 self.col_num = Colors.out_number
370
371 #-----------------------------------------------------------------------------
372 class CachedOutput:
373 """Class for printing output from calculations while keeping a cache of
374 reults. It dynamically creates global variables prefixed with _ which
375 contain these results.
376
377 Meant to be used as a sys.displayhook replacement, providing numbered
378 prompts and cache services.
379
380 Initialize with initial and final values for cache counter (this defines
381 the maximum size of the cache."""
382
383 def __init__(self,cache_size,Pprint,colors='NoColor',input_sep='\n',
384 output_sep='\n',output_sep2='',user_ns={},
385 ps1 = None, ps2 = None,ps_out = None,
386 input_hist = None,pad_left=True):
387
388 cache_size_min = 20
389 if cache_size <= 0:
390 self.do_full_cache = 0
391 cache_size = 0
392 elif cache_size < cache_size_min:
393 self.do_full_cache = 0
394 cache_size = 0
395 warn('caching was disabled (min value for cache size is %s).' %
396 cache_size_min,level=3)
397 else:
398 self.do_full_cache = 1
399
400 self.cache_size = cache_size
401 self.input_sep = input_sep
402
403 # we need a reference to the user-level namespace
404 self.user_ns = user_ns
405 # and to the user's input
406 self.input_hist = input_hist
407
408 # Set input prompt strings and colors
409 if cache_size == 0:
410 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
411 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
412 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
413 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
414 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
415
416 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
417 pad_left=pad_left)
418 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
419 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
420 pad_left=pad_left)
421 self.color_table = PromptColors
422 self.set_colors(colors)
423
424 # other more normal stuff
425 # b/c each call to the In[] prompt raises it by 1, even the first.
426 self.prompt_count = 0
427 self.cache_count = 1
428 # Store the last prompt string each time, we need it for aligning
429 # continuation and auto-rewrite prompts
430 self.last_prompt = ''
431 self.entries = [None] # output counter starts at 1 for the user
432 self.Pprint = Pprint
433 self.output_sep = output_sep
434 self.output_sep2 = output_sep2
435 self._,self.__,self.___ = '','',''
436 self.pprint_types = map(type,[(),[],{}])
437
438 # these are deliberately global:
439 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
440 self.user_ns.update(to_user_ns)
441
442 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
443 if p_str is None:
444 if self.do_full_cache:
445 return cache_def
446 else:
447 return no_cache_def
448 else:
449 return p_str
450
451 def set_colors(self,colors):
452 """Set the active color scheme and configure colors for the three
453 prompt subsystems."""
454
455 # FIXME: the prompt_specials global should be gobbled inside this
456 # class instead. Do it when cleaning up the whole 3-prompt system.
457 global prompt_specials
458 if colors.lower()=='nocolor':
459 prompt_specials = prompt_specials_nocolor
460 else:
461 prompt_specials = prompt_specials_color
462
463 self.color_table.set_active_scheme(colors)
464 self.prompt1.set_colors()
465 self.prompt2.set_colors()
466 self.prompt_out.set_colors()
467
468 def __call__(self,arg=None):
469 """Printing with history cache management.
470
471 This is invoked everytime the interpreter needs to print, and is
472 activated by setting the variable sys.displayhook to it."""
473
474 # If something injected a '_' variable in __builtin__, delete
475 # ipython's automatic one so we don't clobber that. gettext() in
476 # particular uses _, so we need to stay away from it.
477 if '_' in __builtin__.__dict__:
478 try:
479 del self.user_ns['_']
480 except KeyError:
481 pass
482 if arg is not None:
483 # first handle the cache and counters
484 self.update(arg)
485 # do not print output if input ends in ';'
486 if self.input_hist[self.prompt_count].endswith(';\n'):
487 return
488 # don't use print, puts an extra space
489 Term.cout.write(self.output_sep)
490 if self.do_full_cache:
491 Term.cout.write(str(self.prompt_out))
492
493 if isinstance(arg,Macro):
494 print 'Executing Macro...'
495 # in case the macro takes a long time to execute
496 Term.cout.flush()
497 exec arg.value in self.user_ns
498 return None
499
500 # and now call a possibly user-defined print mechanism
501 self.display(arg)
502 Term.cout.write(self.output_sep2)
503 Term.cout.flush()
504
505 def _display(self,arg):
506 """Default printer method, uses pprint.
507
508 This can be over-ridden by the users to implement special formatting
509 of certain types of output."""
510
511 if self.Pprint:
512 # The following is an UGLY kludge, b/c python fails to properly
513 # identify instances of classes imported in the user namespace
514 # (they have different memory locations, I guess). Structs are
515 # essentially dicts but pprint doesn't know what to do with them.
516 try:
517 if arg.__class__.__module__ == 'Struct' and \
518 arg.__class__.__name__ == 'Struct':
519 out = 'Struct:\n%s' % pformat(arg.dict())
520 else:
521 out = pformat(arg)
522 except:
523 out = pformat(arg)
524 if '\n' in out:
525 # So that multi-line strings line up with the left column of
526 # the screen, instead of having the output prompt mess up
527 # their first line.
528 Term.cout.write('\n')
529 print >>Term.cout, out
530 else:
531 print >>Term.cout, arg
532
533 # Assign the default display method:
534 display = _display
535
536 def update(self,arg):
537 #print '***cache_count', self.cache_count # dbg
538 if self.cache_count >= self.cache_size and self.do_full_cache:
539 self.flush()
540 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
541 # we cause buggy behavior for things like gettext).
542 if '_' not in __builtin__.__dict__:
543 self.___ = self.__
544 self.__ = self._
545 self._ = arg
546 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
547
548 # hackish access to top-level namespace to create _1,_2... dynamically
549 to_main = {}
550 if self.do_full_cache:
551 self.cache_count += 1
552 self.entries.append(arg)
553 new_result = '_'+`self.prompt_count`
554 to_main[new_result] = self.entries[-1]
555 self.user_ns.update(to_main)
556 self.user_ns['_oh'][self.prompt_count] = arg
557
558 def flush(self):
559 if not self.do_full_cache:
560 raise ValueError,"You shouldn't have reached the cache flush "\
561 "if full caching is not enabled!"
562 warn('Output cache limit (currently '+\
563 `self.cache_count`+' entries) hit.\n'
564 'Flushing cache and resetting history counter...\n'
565 'The only history variables available will be _,__,___ and _1\n'
566 'with the current result.')
567 # delete auto-generated vars from global namespace
568 for n in range(1,self.prompt_count + 1):
569 key = '_'+`n`
570 try:
571 del self.user_ns[key]
572 except: pass
573 self.prompt_count = 1
574 self.cache_count = 1
@@ -0,0 +1,255 b''
1 # -*- coding: utf-8 -*-
2 """
3 Class and program to colorize python source code for ANSI terminals.
4
5 Based on an HTML code highlighter by Jurgen Hermann found at:
6 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298
7
8 Modifications by Fernando Perez (fperez@colorado.edu).
9
10 Information on the original HTML highlighter follows:
11
12 MoinMoin - Python Source Parser
13
14 Title:olorize Python source using the built-in tokenizer
15
16 Submitter: Jurgen Hermann
17 Last Updated:2001/04/06
18
19 Version no:1.2
20
21 Description:
22
23 This code is part of MoinMoin (http://moin.sourceforge.net/) and converts
24 Python source code to HTML markup, rendering comments, keywords,
25 operators, numeric and string literals in different colors.
26
27 It shows how to use the built-in keyword, token and tokenize modules to
28 scan Python source code and re-emit it with no changes to its original
29 formatting (which is the hard part).
30
31 $Id: PyColorize.py 485 2005-01-27 19:15:39Z fperez $"""
32
33 __all__ = ['ANSICodeColors','Parser']
34
35 _scheme_default = 'Linux'
36
37 # Imports
38 import string, sys, os, cStringIO
39 import keyword, token, tokenize
40
41 from IPython.ColorANSI import *
42
43 #############################################################################
44 ### Python Source Parser (does Hilighting)
45 #############################################################################
46
47 _KEYWORD = token.NT_OFFSET + 1
48 _TEXT = token.NT_OFFSET + 2
49
50 #****************************************************************************
51 # Builtin color schemes
52
53 Colors = TermColors # just a shorthand
54
55 # Build a few color schemes
56 NoColor = ColorScheme(
57 'NoColor',{
58 token.NUMBER : Colors.NoColor,
59 token.OP : Colors.NoColor,
60 token.STRING : Colors.NoColor,
61 tokenize.COMMENT : Colors.NoColor,
62 token.NAME : Colors.NoColor,
63 token.ERRORTOKEN : Colors.NoColor,
64
65 _KEYWORD : Colors.NoColor,
66 _TEXT : Colors.NoColor,
67
68 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
69 } )
70
71 LinuxColors = ColorScheme(
72 'Linux',{
73 token.NUMBER : Colors.LightCyan,
74 token.OP : Colors.Yellow,
75 token.STRING : Colors.LightBlue,
76 tokenize.COMMENT : Colors.LightRed,
77 token.NAME : Colors.White,
78 token.ERRORTOKEN : Colors.Red,
79
80 _KEYWORD : Colors.LightGreen,
81 _TEXT : Colors.Yellow,
82
83 'normal' : Colors.Normal # color off (usu. Colors.Normal)
84 } )
85
86 LightBGColors = ColorScheme(
87 'LightBG',{
88 token.NUMBER : Colors.Cyan,
89 token.OP : Colors.Blue,
90 token.STRING : Colors.Blue,
91 tokenize.COMMENT : Colors.Red,
92 token.NAME : Colors.Black,
93 token.ERRORTOKEN : Colors.Red,
94
95 _KEYWORD : Colors.Green,
96 _TEXT : Colors.Blue,
97
98 'normal' : Colors.Normal # color off (usu. Colors.Normal)
99 } )
100
101 # Build table of color schemes (needed by the parser)
102 ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
103 _scheme_default)
104
105 class Parser:
106 """ Format colored Python source.
107 """
108
109 def __init__(self, color_table=None,out = sys.stdout):
110 """ Create a parser with a specified color table and output channel.
111
112 Call format() to process code.
113 """
114 self.color_table = color_table and color_table or ANSICodeColors
115 self.out = out
116
117 def format(self, raw, out = None, scheme = ''):
118 """ Parse and send the colored source.
119
120 If out and scheme are not specified, the defaults (given to
121 constructor) are used.
122
123 out should be a file-type object. Optionally, out can be given as the
124 string 'str' and the parser will automatically return the output in a
125 string."""
126
127 self.raw = string.strip(string.expandtabs(raw))
128 string_output = 0
129 if out == 'str' or self.out == 'str':
130 out_old = self.out
131 self.out = cStringIO.StringIO()
132 string_output = 1
133 elif out is not None:
134 self.out = out
135 # local shorthand
136 colors = self.color_table[scheme].colors
137 self.colors = colors # put in object so __call__ sees it
138 # store line offsets in self.lines
139 self.lines = [0, 0]
140 pos = 0
141 while 1:
142 pos = string.find(self.raw, '\n', pos) + 1
143 if not pos: break
144 self.lines.append(pos)
145 self.lines.append(len(self.raw))
146
147 # parse the source and write it
148 self.pos = 0
149 text = cStringIO.StringIO(self.raw)
150 #self.out.write('<pre><font face="Courier New">')
151 try:
152 tokenize.tokenize(text.readline, self)
153 except tokenize.TokenError, ex:
154 msg = ex[0]
155 line = ex[1][0]
156 self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
157 (colors[token.ERRORTOKEN],
158 msg, self.raw[self.lines[line]:],
159 colors.normal)
160 )
161 self.out.write(colors.normal+'\n')
162 if string_output:
163 output = self.out.getvalue()
164 self.out = out_old
165 return output
166
167 def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line):
168 """ Token handler, with syntax highlighting."""
169
170 # local shorthand
171 colors = self.colors
172
173 # line separator, so this works across platforms
174 linesep = os.linesep
175
176 # calculate new positions
177 oldpos = self.pos
178 newpos = self.lines[srow] + scol
179 self.pos = newpos + len(toktext)
180
181 # handle newlines
182 if toktype in [token.NEWLINE, tokenize.NL]:
183 self.out.write(linesep)
184 return
185
186 # send the original whitespace, if needed
187 if newpos > oldpos:
188 self.out.write(self.raw[oldpos:newpos])
189
190 # skip indenting tokens
191 if toktype in [token.INDENT, token.DEDENT]:
192 self.pos = newpos
193 return
194
195 # map token type to a color group
196 if token.LPAR <= toktype and toktype <= token.OP:
197 toktype = token.OP
198 elif toktype == token.NAME and keyword.iskeyword(toktext):
199 toktype = _KEYWORD
200 color = colors.get(toktype, colors[_TEXT])
201
202 #print '<%s>' % toktext, # dbg
203
204 # Triple quoted strings must be handled carefully so that backtracking
205 # in pagers works correctly. We need color terminators on _each_ line.
206 if linesep in toktext:
207 toktext = toktext.replace(linesep, '%s%s%s' %
208 (colors.normal,linesep,color))
209
210 # send text
211 self.out.write('%s%s%s' % (color,toktext,colors.normal))
212
213 def main():
214 """Colorize a python file using ANSI color escapes and print to stdout.
215
216 Usage:
217 %s [-s scheme] filename
218
219 Options:
220
221 -s scheme: give the color scheme to use. Currently only 'Linux'
222 (default) and 'LightBG' and 'NoColor' are implemented (give without
223 quotes). """
224
225 def usage():
226 print >> sys.stderr, main.__doc__ % sys.argv[0]
227 sys.exit(1)
228
229 # FIXME: rewrite this to at least use getopt
230 try:
231 if sys.argv[1] == '-s':
232 scheme_name = sys.argv[2]
233 del sys.argv[1:3]
234 else:
235 scheme_name = _scheme_default
236
237 except:
238 usage()
239
240 try:
241 fname = sys.argv[1]
242 except:
243 usage()
244
245 # write colorized version to stdout
246 parser = Parser()
247 try:
248 parser.format(file(fname).read(),scheme = scheme_name)
249 except IOError,msg:
250 # if user reads through a pager and quits, don't print traceback
251 if msg.args != (32,'Broken pipe'):
252 raise
253
254 if __name__ == "__main__":
255 main()
@@ -0,0 +1,69 b''
1 # -*- coding: utf-8 -*-
2 """Release data for the IPython project.
3
4 $Id: Release.py 605 2005-06-09 14:09:03Z fperez $"""
5
6 #*****************************************************************************
7 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
8 #
9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
10 # <n8gray@caltech.edu>
11 #
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
15
16 # Name of the package for release purposes. This is the name which labels
17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
18 name = 'ipython'
19
20 # For versions with substrings (like 0.6.7_rc1), use _ but NOT -, since
21 # bdist_rpm chokes on dashes in the version string.
22 version = '0.6.16_cvs'
23
24 description = "An enhanced interactive Python shell."
25
26 long_description = \
27 """
28 IPython provides a replacement for the interactive Python interpreter with
29 extra functionality.
30
31 Main features:
32
33 * Comprehensive object introspection.
34
35 * Input history, persistent across sessions.
36
37 * Caching of output results during a session with automatically generated
38 references.
39
40 * Readline based name completion.
41
42 * Extensible system of 'magic' commands for controlling the environment and
43 performing many tasks related either to IPython or the operating system.
44
45 * Configuration system with easy switching between different setups (simpler
46 than changing $PYTHONSTARTUP environment variables every time).
47
48 * Session logging and reloading.
49
50 * Extensible syntax processing for special purpose situations.
51
52 * Access to the system shell with user-extensible alias system.
53
54 * Easily embeddable in other Python programs.
55
56 * Integrated access to the pdb debugger and the Python profiler. """
57
58 license = 'BSD'
59
60 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
61 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
62 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu')
63 }
64
65 url = 'http://ipython.scipy.org'
66
67 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
68
69 keywords = ['Interactive','Interpreter','Shell']
This diff has been collapsed as it changes many lines, (894 lines changed) Show them Hide them
@@ -0,0 +1,894 b''
1 # -*- coding: utf-8 -*-
2 """IPython Shell classes.
3
4 All the matplotlib support code was co-developed with John Hunter,
5 matplotlib's author.
6
7 $Id: Shell.py 605 2005-06-09 14:09:03Z fperez $"""
8
9 #*****************************************************************************
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 #
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
15
16 from IPython import Release
17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __license__ = Release.license
19
20 # Code begins
21 import __main__
22 import __builtin__
23 import sys
24 import os
25 import code
26 import threading
27 import signal
28
29 import IPython
30 from IPython.iplib import InteractiveShell
31 from IPython.ipmaker import make_IPython
32 from IPython.genutils import Term,warn,error,flag_calls
33 from IPython.Struct import Struct
34 from IPython.Magic import Magic
35 from IPython import ultraTB
36
37 # global flag to pass around information about Ctrl-C without exceptions
38 KBINT = False
39
40 # global flag to turn on/off Tk support.
41 USE_TK = False
42
43 #-----------------------------------------------------------------------------
44 # This class is trivial now, but I want to have it in to publish a clean
45 # interface. Later when the internals are reorganized, code that uses this
46 # shouldn't have to change.
47
48 class IPShell:
49 """Create an IPython instance."""
50
51 def __init__(self,argv=None,user_ns=None,debug=1,
52 shell_class=InteractiveShell):
53 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
54 shell_class=shell_class)
55
56 def mainloop(self,sys_exit=0,banner=None):
57 self.IP.mainloop(banner)
58 if sys_exit:
59 sys.exit()
60
61 #-----------------------------------------------------------------------------
62 class IPShellEmbed:
63 """Allow embedding an IPython shell into a running program.
64
65 Instances of this class are callable, with the __call__ method being an
66 alias to the embed() method of an InteractiveShell instance.
67
68 Usage (see also the example-embed.py file for a running example):
69
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71
72 - argv: list containing valid command-line options for IPython, as they
73 would appear in sys.argv[1:].
74
75 For example, the following command-line options:
76
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78
79 would be passed in the argv list as:
80
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82
83 - banner: string which gets printed every time the interpreter starts.
84
85 - exit_msg: string which gets printed every time the interpreter exits.
86
87 - rc_override: a dict or Struct of configuration options such as those
88 used by IPython. These options are read from your ~/.ipython/ipythonrc
89 file when the Shell object is created. Passing an explicit rc_override
90 dict with any options you want allows you to override those values at
91 creation time without having to modify the file. This way you can create
92 embeddable instances configured in any way you want without editing any
93 global files (thus keeping your interactive IPython configuration
94 unchanged).
95
96 Then the ipshell instance can be called anywhere inside your code:
97
98 ipshell(header='') -> Opens up an IPython shell.
99
100 - header: string printed by the IPython shell upon startup. This can let
101 you know where in your code you are when dropping into the shell. Note
102 that 'banner' gets prepended to all calls, so header is used for
103 location-specific information.
104
105 For more details, see the __call__ method below.
106
107 When the IPython shell is exited with Ctrl-D, normal program execution
108 resumes.
109
110 This functionality was inspired by a posting on comp.lang.python by cmkl
111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 by the IDL stop/continue commands."""
113
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 """Note that argv here is a string, NOT a list."""
116 self.set_banner(banner)
117 self.set_exit_msg(exit_msg)
118 self.set_dummy_mode(0)
119
120 # sys.displayhook is a global, we need to save the user's original
121 # Don't rely on __displayhook__, as the user may have changed that.
122 self.sys_displayhook_ori = sys.displayhook
123
124 # save readline completer status
125 try:
126 #print 'Save completer',sys.ipcompleter # dbg
127 self.sys_ipcompleter_ori = sys.ipcompleter
128 except:
129 pass # not nested with IPython
130
131 # FIXME. Passing user_ns breaks namespace handling.
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134
135 self.IP.name_space_init()
136 # mark this as an embedded instance so we know if we get a crash
137 # post-mortem
138 self.IP.rc.embedded = 1
139 # copy our own displayhook also
140 self.sys_displayhook_embed = sys.displayhook
141 # and leave the system's display hook clean
142 sys.displayhook = self.sys_displayhook_ori
143 # don't use the ipython crash handler so that user exceptions aren't
144 # trapped
145 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
146 mode = self.IP.rc.xmode,
147 call_pdb = self.IP.rc.pdb)
148 self.restore_system_completer()
149
150 def restore_system_completer(self):
151 """Restores the readline completer which was in place.
152
153 This allows embedded IPython within IPython not to disrupt the
154 parent's completion.
155 """
156
157 try:
158 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
159 sys.ipcompleter = self.sys_ipcompleter_ori
160 except:
161 pass
162
163 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
164 """Activate the interactive interpreter.
165
166 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
167 the interpreter shell with the given local and global namespaces, and
168 optionally print a header string at startup.
169
170 The shell can be globally activated/deactivated using the
171 set/get_dummy_mode methods. This allows you to turn off a shell used
172 for debugging globally.
173
174 However, *each* time you call the shell you can override the current
175 state of dummy_mode with the optional keyword parameter 'dummy'. For
176 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
177 can still have a specific call work by making it as IPShell(dummy=0).
178
179 The optional keyword parameter dummy controls whether the call
180 actually does anything. """
181
182 # Allow the dummy parameter to override the global __dummy_mode
183 if dummy or (dummy != 0 and self.__dummy_mode):
184 return
185
186 # Set global subsystems (display,completions) to our values
187 sys.displayhook = self.sys_displayhook_embed
188 if self.IP.has_readline:
189 self.IP.readline.set_completer(self.IP.Completer.complete)
190
191 if self.banner and header:
192 format = '%s\n%s\n'
193 else:
194 format = '%s%s\n'
195 banner = format % (self.banner,header)
196
197 # Call the embedding code with a stack depth of 1 so it can skip over
198 # our call and get the original caller's namespaces.
199 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
200
201 if self.exit_msg:
202 print self.exit_msg
203
204 # Restore global systems (display, completion)
205 sys.displayhook = self.sys_displayhook_ori
206 self.restore_system_completer()
207
208 def set_dummy_mode(self,dummy):
209 """Sets the embeddable shell's dummy mode parameter.
210
211 set_dummy_mode(dummy): dummy = 0 or 1.
212
213 This parameter is persistent and makes calls to the embeddable shell
214 silently return without performing any action. This allows you to
215 globally activate or deactivate a shell you're using with a single call.
216
217 If you need to manually"""
218
219 if dummy not in [0,1]:
220 raise ValueError,'dummy parameter must be 0 or 1'
221 self.__dummy_mode = dummy
222
223 def get_dummy_mode(self):
224 """Return the current value of the dummy mode parameter.
225 """
226 return self.__dummy_mode
227
228 def set_banner(self,banner):
229 """Sets the global banner.
230
231 This banner gets prepended to every header printed when the shell
232 instance is called."""
233
234 self.banner = banner
235
236 def set_exit_msg(self,exit_msg):
237 """Sets the global exit_msg.
238
239 This exit message gets printed upon exiting every time the embedded
240 shell is called. It is None by default. """
241
242 self.exit_msg = exit_msg
243
244 #-----------------------------------------------------------------------------
245 def sigint_handler (signum,stack_frame):
246 """Sigint handler for threaded apps.
247
248 This is a horrible hack to pass information about SIGINT _without_ using
249 exceptions, since I haven't been able to properly manage cross-thread
250 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
251 that's my understanding from a c.l.py thread where this was discussed)."""
252
253 global KBINT
254
255 print '\nKeyboardInterrupt - Press <Enter> to continue.',
256 Term.cout.flush()
257 # Set global flag so that runsource can know that Ctrl-C was hit
258 KBINT = True
259
260 class MTInteractiveShell(InteractiveShell):
261 """Simple multi-threaded shell."""
262
263 # Threading strategy taken from:
264 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
265 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
266 # from the pygtk mailing list, to avoid lockups with system calls.
267
268 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
269 user_ns = None, banner2='',**kw):
270 """Similar to the normal InteractiveShell, but with threading control"""
271
272 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
273
274 # Locking control variable
275 self.thread_ready = threading.Condition()
276
277 # Stuff to do at closing time
278 self._kill = False
279 on_kill = kw.get('on_kill')
280 if on_kill is None:
281 on_kill = []
282 # Check that all things to kill are callable:
283 for t in on_kill:
284 if not callable(t):
285 raise TypeError,'on_kill must be a list of callables'
286 self.on_kill = on_kill
287
288 def runsource(self, source, filename="<input>", symbol="single"):
289 """Compile and run some source in the interpreter.
290
291 Modified version of code.py's runsource(), to handle threading issues.
292 See the original for full docstring details."""
293
294 global KBINT
295
296 # If Ctrl-C was typed, we reset the flag and return right away
297 if KBINT:
298 KBINT = False
299 return False
300
301 try:
302 code = self.compile(source, filename, symbol)
303 except (OverflowError, SyntaxError, ValueError):
304 # Case 1
305 self.showsyntaxerror(filename)
306 return False
307
308 if code is None:
309 # Case 2
310 return True
311
312 # Case 3
313 # Store code in self, so the execution thread can handle it
314 self.thread_ready.acquire()
315 self.code_to_run_src = source
316 self.code_to_run = code
317 self.thread_ready.wait() # Wait until processed in timeout interval
318 self.thread_ready.release()
319
320 return False
321
322 def runcode(self):
323 """Execute a code object.
324
325 Multithreaded wrapper around IPython's runcode()."""
326
327 # lock thread-protected stuff
328 self.thread_ready.acquire()
329
330 # Install sigint handler
331 try:
332 signal.signal(signal.SIGINT, sigint_handler)
333 except SystemError:
334 # This happens under Windows, which seems to have all sorts
335 # of problems with signal handling. Oh well...
336 pass
337
338 if self._kill:
339 print >>Term.cout, 'Closing threads...',
340 Term.cout.flush()
341 for tokill in self.on_kill:
342 tokill()
343 print >>Term.cout, 'Done.'
344
345 # Run pending code by calling parent class
346 if self.code_to_run is not None:
347 self.thread_ready.notify()
348 InteractiveShell.runcode(self,self.code_to_run)
349
350 # We're done with thread-protected variables
351 self.thread_ready.release()
352 # This MUST return true for gtk threading to work
353 return True
354
355 def kill (self):
356 """Kill the thread, returning when it has been shut down."""
357 self.thread_ready.acquire()
358 self._kill = True
359 self.thread_ready.release()
360
361 class MatplotlibShellBase:
362 """Mixin class to provide the necessary modifications to regular IPython
363 shell classes for matplotlib support.
364
365 Given Python's MRO, this should be used as the FIRST class in the
366 inheritance hierarchy, so that it overrides the relevant methods."""
367
368 def _matplotlib_config(self,name):
369 """Return various items needed to setup the user's shell with matplotlib"""
370
371 # Initialize matplotlib to interactive mode always
372 import matplotlib
373 from matplotlib import backends
374 matplotlib.interactive(True)
375
376 def use(arg):
377 """IPython wrapper for matplotlib's backend switcher.
378
379 In interactive use, we can not allow switching to a different
380 interactive backend, since thread conflicts will most likely crash
381 the python interpreter. This routine does a safety check first,
382 and refuses to perform a dangerous switch. It still allows
383 switching to non-interactive backends."""
384
385 if arg in backends.interactive_bk and arg != self.mpl_backend:
386 m=('invalid matplotlib backend switch.\n'
387 'This script attempted to switch to the interactive '
388 'backend: `%s`\n'
389 'Your current choice of interactive backend is: `%s`\n\n'
390 'Switching interactive matplotlib backends at runtime\n'
391 'would crash the python interpreter, '
392 'and IPython has blocked it.\n\n'
393 'You need to either change your choice of matplotlib backend\n'
394 'by editing your .matplotlibrc file, or run this script as a \n'
395 'standalone file from the command line, not using IPython.\n' %
396 (arg,self.mpl_backend) )
397 raise RuntimeError, m
398 else:
399 self.mpl_use(arg)
400 self.mpl_use._called = True
401
402 self.matplotlib = matplotlib
403
404 # Take control of matplotlib's error handling, which can normally
405 # lock up the python interpreter when raw_input() is called
406 import matplotlib.backends as backend
407 backend.error_msg = error
408
409 # we'll handle the mainloop, tell show not to
410 import matplotlib.backends
411 matplotlib.backends.show._needmain = False
412 self.mpl_backend = matplotlib.rcParams['backend']
413
414 # we also need to block switching of interactive backends by use()
415 self.mpl_use = matplotlib.use
416 self.mpl_use._called = False
417 # overwrite the original matplotlib.use with our wrapper
418 matplotlib.use = use
419
420 # We need to detect at runtime whether show() is called by the user.
421 # For this, we wrap it into a decorator which adds a 'called' flag.
422 backend.draw_if_interactive = flag_calls(backend.draw_if_interactive)
423
424 # This must be imported last in the matplotlib series, after
425 # backend/interactivity choices have been made
426 try:
427 import matplotlib.pylab as pylab
428 self.pylab = pylab
429 self.pylab_name = 'pylab'
430 except ImportError:
431 import matplotlib.matlab as matlab
432 self.pylab = matlab
433 self.pylab_name = 'matlab'
434
435 # Build a user namespace initialized with matplotlib/matlab features.
436 user_ns = {'__name__':'__main__',
437 '__builtins__' : __builtin__ }
438
439 # Be careful not to remove the final \n in the code string below, or
440 # things will break badly with py22 (I think it's a python bug, 2.3 is
441 # OK).
442 pname = self.pylab_name # Python can't interpolate dotted var names
443 exec ("import matplotlib\n"
444 "import matplotlib.%(pname)s as %(pname)s\n"
445 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
446
447 # Build matplotlib info banner
448 b="""
449 Welcome to pylab, a matplotlib-based Python environment.
450 For more information, type 'help(pylab)'.
451 """
452 return user_ns,b
453
454 def mplot_exec(self,fname,*where,**kw):
455 """Execute a matplotlib script.
456
457 This is a call to execfile(), but wrapped in safeties to properly
458 handle interactive rendering and backend switching."""
459
460 #print '*** Matplotlib runner ***' # dbg
461 # turn off rendering until end of script
462 isInteractive = self.matplotlib.rcParams['interactive']
463 self.matplotlib.interactive(False)
464 self.safe_execfile(fname,*where,**kw)
465 self.matplotlib.interactive(isInteractive)
466 # make rendering call now, if the user tried to do it
467 if self.pylab.draw_if_interactive.called:
468 self.pylab.draw()
469 self.pylab.draw_if_interactive.called = False
470
471 # if a backend switch was performed, reverse it now
472 if self.mpl_use._called:
473 self.matplotlib.rcParams['backend'] = self.mpl_backend
474
475 def magic_run(self,parameter_s=''):
476 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
477
478 # Fix the docstring so users see the original as well
479 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
480 "\n *** Modified %run for Matplotlib,"
481 " with proper interactive handling ***")
482
483 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
484 # and multithreaded. Note that these are meant for internal use, the IPShell*
485 # classes below are the ones meant for public consumption.
486
487 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
488 """Single-threaded shell with matplotlib support."""
489
490 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
491 user_ns = None, **kw):
492 user_ns,b2 = self._matplotlib_config(name)
493 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
494
495 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
496 """Multi-threaded shell with matplotlib support."""
497
498 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
499 user_ns = None, **kw):
500 user_ns,b2 = self._matplotlib_config(name)
501 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
502
503 #-----------------------------------------------------------------------------
504 # Utility functions for the different GUI enabled IPShell* classes.
505
506 def get_tk():
507 """Tries to import Tkinter and returns a withdrawn Tkinter root
508 window. If Tkinter is already imported or not available, this
509 returns None. This function calls `hijack_tk` underneath.
510 """
511 if not USE_TK or sys.modules.has_key('Tkinter'):
512 return None
513 else:
514 try:
515 import Tkinter
516 except ImportError:
517 return None
518 else:
519 hijack_tk()
520 r = Tkinter.Tk()
521 r.withdraw()
522 return r
523
524 def hijack_tk():
525 """Modifies Tkinter's mainloop with a dummy so when a module calls
526 mainloop, it does not block.
527
528 """
529 def misc_mainloop(self, n=0):
530 pass
531 def tkinter_mainloop(n=0):
532 pass
533
534 import Tkinter
535 Tkinter.Misc.mainloop = misc_mainloop
536 Tkinter.mainloop = tkinter_mainloop
537
538 def update_tk(tk):
539 """Updates the Tkinter event loop. This is typically called from
540 the respective WX or GTK mainloops.
541 """
542 if tk:
543 tk.update()
544
545 def hijack_wx():
546 """Modifies wxPython's MainLoop with a dummy so user code does not
547 block IPython. The hijacked mainloop function is returned.
548 """
549 def dummy_mainloop(*args, **kw):
550 pass
551 import wxPython
552 ver = wxPython.__version__
553 orig_mainloop = None
554 if ver[:3] >= '2.5':
555 import wx
556 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
557 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
558 else: raise AttributeError('Could not find wx core module')
559 orig_mainloop = core.PyApp_MainLoop
560 core.PyApp_MainLoop = dummy_mainloop
561 elif ver[:3] == '2.4':
562 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
563 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
564 else:
565 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
566 return orig_mainloop
567
568 def hijack_gtk():
569 """Modifies pyGTK's mainloop with a dummy so user code does not
570 block IPython. This function returns the original `gtk.mainloop`
571 function that has been hijacked.
572
573 NOTE: Make sure you import this *AFTER* you call
574 pygtk.require(...).
575 """
576 def dummy_mainloop(*args, **kw):
577 pass
578 import gtk
579 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
580 else: orig_mainloop = gtk.mainloop
581 gtk.mainloop = dummy_mainloop
582 gtk.main = dummy_mainloop
583 return orig_mainloop
584
585 #-----------------------------------------------------------------------------
586 # The IPShell* classes below are the ones meant to be run by external code as
587 # IPython instances. Note that unless a specific threading strategy is
588 # desired, the factory function start() below should be used instead (it
589 # selects the proper threaded class).
590
591 class IPShellGTK(threading.Thread):
592 """Run a gtk mainloop() in a separate thread.
593
594 Python commands can be passed to the thread where they will be executed.
595 This is implemented by periodically checking for passed code using a
596 GTK timeout callback."""
597
598 TIMEOUT = 100 # Millisecond interval between timeouts.
599
600 def __init__(self,argv=None,user_ns=None,debug=1,
601 shell_class=MTInteractiveShell):
602
603 import pygtk
604 pygtk.require("2.0")
605 import gtk
606
607 self.gtk = gtk
608 self.gtk_mainloop = hijack_gtk()
609
610 # Allows us to use both Tk and GTK.
611 self.tk = get_tk()
612
613 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
614 else: mainquit = self.gtk.mainquit
615
616 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
617 shell_class=shell_class,
618 on_kill=[mainquit])
619 threading.Thread.__init__(self)
620
621 def run(self):
622 self.IP.mainloop()
623 self.IP.kill()
624
625 def mainloop(self):
626
627 if self.gtk.pygtk_version >= (2,4,0):
628 import gobject
629 gobject.timeout_add(self.TIMEOUT, self.on_timer)
630 else:
631 self.gtk.timeout_add(self.TIMEOUT, self.on_timer)
632
633 if sys.platform != 'win32':
634 try:
635 if self.gtk.gtk_version[0] >= 2:
636 self.gtk.threads_init()
637 except AttributeError:
638 pass
639 except RuntimeError:
640 error('Your pyGTK likely has not been compiled with '
641 'threading support.\n'
642 'The exception printout is below.\n'
643 'You can either rebuild pyGTK with threads, or '
644 'try using \n'
645 'matplotlib with a different backend (like Tk or WX).\n'
646 'Note that matplotlib will most likely not work in its '
647 'current state!')
648 self.IP.InteractiveTB()
649 self.start()
650 self.gtk.threads_enter()
651 self.gtk_mainloop()
652 self.gtk.threads_leave()
653 self.join()
654
655 def on_timer(self):
656 update_tk(self.tk)
657 return self.IP.runcode()
658
659
660 class IPShellWX(threading.Thread):
661 """Run a wx mainloop() in a separate thread.
662
663 Python commands can be passed to the thread where they will be executed.
664 This is implemented by periodically checking for passed code using a
665 GTK timeout callback."""
666
667 TIMEOUT = 100 # Millisecond interval between timeouts.
668
669 def __init__(self,argv=None,user_ns=None,debug=1,
670 shell_class=MTInteractiveShell):
671
672 import wxPython.wx as wx
673
674 threading.Thread.__init__(self)
675 self.wx = wx
676 self.wx_mainloop = hijack_wx()
677
678 # Allows us to use both Tk and GTK.
679 self.tk = get_tk()
680
681 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
682 shell_class=shell_class,
683 on_kill=[self.wxexit])
684 self.app = None
685
686 def wxexit(self, *args):
687 if self.app is not None:
688 self.app.agent.timer.Stop()
689 self.app.ExitMainLoop()
690
691 def run(self):
692 self.IP.mainloop()
693 self.IP.kill()
694
695 def mainloop(self):
696
697 self.start()
698
699 class TimerAgent(self.wx.wxMiniFrame):
700 wx = self.wx
701 IP = self.IP
702 tk = self.tk
703 def __init__(self, parent, interval):
704 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
705 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
706 size=(100, 100),style=style)
707 self.Show(False)
708 self.interval = interval
709 self.timerId = self.wx.wxNewId()
710
711 def StartWork(self):
712 self.timer = self.wx.wxTimer(self, self.timerId)
713 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
714 self.timer.Start(self.interval)
715
716 def OnTimer(self, event):
717 update_tk(self.tk)
718 self.IP.runcode()
719
720 class App(self.wx.wxApp):
721 wx = self.wx
722 TIMEOUT = self.TIMEOUT
723 def OnInit(self):
724 'Create the main window and insert the custom frame'
725 self.agent = TimerAgent(None, self.TIMEOUT)
726 self.agent.Show(self.wx.false)
727 self.agent.StartWork()
728 return self.wx.true
729
730 self.app = App(redirect=False)
731 self.wx_mainloop(self.app)
732 self.join()
733
734
735 class IPShellQt(threading.Thread):
736 """Run a Qt event loop in a separate thread.
737
738 Python commands can be passed to the thread where they will be executed.
739 This is implemented by periodically checking for passed code using a
740 Qt timer / slot."""
741
742 TIMEOUT = 100 # Millisecond interval between timeouts.
743
744 def __init__(self,argv=None,user_ns=None,debug=0,
745 shell_class=MTInteractiveShell):
746
747 import qt
748
749 class newQApplication:
750 def __init__( self ):
751 self.QApplication = qt.QApplication
752
753 def __call__( *args, **kwargs ):
754 return qt.qApp
755
756 def exec_loop( *args, **kwargs ):
757 pass
758
759 def __getattr__( self, name ):
760 return getattr( self.QApplication, name )
761
762 qt.QApplication = newQApplication()
763
764 # Allows us to use both Tk and QT.
765 self.tk = get_tk()
766
767 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
768 shell_class=shell_class,
769 on_kill=[qt.qApp.exit])
770
771 threading.Thread.__init__(self)
772
773 def run(self):
774 #sys.excepthook = self.IP.excepthook # dbg
775 self.IP.mainloop()
776 self.IP.kill()
777
778 def mainloop(self):
779 import qt, sys
780 if qt.QApplication.startingUp():
781 a = qt.QApplication.QApplication( sys.argv )
782 self.timer = qt.QTimer()
783 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
784
785 self.start()
786 self.timer.start( self.TIMEOUT, True )
787 while True:
788 if self.IP._kill: break
789 qt.qApp.exec_loop()
790 self.join()
791
792 def on_timer(self):
793 update_tk(self.tk)
794 result = self.IP.runcode()
795 self.timer.start( self.TIMEOUT, True )
796 return result
797
798 # A set of matplotlib public IPython shell classes, for single-threaded
799 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
800 class IPShellMatplotlib(IPShell):
801 """Subclass IPShell with MatplotlibShell as the internal shell.
802
803 Single-threaded class, meant for the Tk* and FLTK* backends.
804
805 Having this on a separate class simplifies the external driver code."""
806
807 def __init__(self,argv=None,user_ns=None,debug=1):
808 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
809
810 class IPShellMatplotlibGTK(IPShellGTK):
811 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
812
813 Multi-threaded class, meant for the GTK* backends."""
814
815 def __init__(self,argv=None,user_ns=None,debug=1):
816 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
817
818 class IPShellMatplotlibWX(IPShellWX):
819 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
820
821 Multi-threaded class, meant for the WX* backends."""
822
823 def __init__(self,argv=None,user_ns=None,debug=1):
824 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
825
826 class IPShellMatplotlibQt(IPShellQt):
827 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
828
829 Multi-threaded class, meant for the Qt* backends."""
830
831 def __init__(self,argv=None,user_ns=None,debug=1):
832 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
833
834 #-----------------------------------------------------------------------------
835 # Factory functions to actually start the proper thread-aware shell
836
837 def _matplotlib_shell_class():
838 """Factory function to handle shell class selection for matplotlib.
839
840 The proper shell class to use depends on the matplotlib backend, since
841 each backend requires a different threading strategy."""
842
843 try:
844 import matplotlib
845 except ImportError:
846 error('matplotlib could NOT be imported! Starting normal IPython.')
847 sh_class = IPShell
848 else:
849 backend = matplotlib.rcParams['backend']
850 if backend.startswith('GTK'):
851 sh_class = IPShellMatplotlibGTK
852 elif backend.startswith('WX'):
853 sh_class = IPShellMatplotlibWX
854 elif backend.startswith('Qt'):
855 sh_class = IPShellMatplotlibQt
856 else:
857 sh_class = IPShellMatplotlib
858 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
859 return sh_class
860
861 # This is the one which should be called by external code.
862 def start():
863 """Return a running shell instance, dealing with threading options.
864
865 This is a factory function which will instantiate the proper IPython shell
866 based on the user's threading choice. Such a selector is needed because
867 different GUI toolkits require different thread handling details."""
868
869 global USE_TK
870 # Crude sys.argv hack to extract the threading options.
871 if len(sys.argv) > 1:
872 if len(sys.argv) > 2:
873 arg2 = sys.argv[2]
874 if arg2.endswith('-tk'):
875 USE_TK = True
876 arg1 = sys.argv[1]
877 if arg1.endswith('-gthread'):
878 shell = IPShellGTK
879 elif arg1.endswith( '-qthread' ):
880 shell = IPShellQt
881 elif arg1.endswith('-wthread'):
882 shell = IPShellWX
883 elif arg1.endswith('-pylab'):
884 shell = _matplotlib_shell_class()
885 else:
886 shell = IPShell
887 else:
888 shell = IPShell
889 return shell()
890
891 # Some aliases for backwards compatibility
892 IPythonShell = IPShell
893 IPythonShellEmbed = IPShellEmbed
894 #************************ End of file <Shell.py> ***************************
@@ -0,0 +1,376 b''
1 # -*- coding: utf-8 -*-
2 """Mimic C structs with lots of extra functionality.
3
4 $Id: Struct.py 410 2004-11-04 07:58:17Z fperez $"""
5
6 #*****************************************************************************
7 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 #
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
12
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
16
17 __all__ = ['Struct']
18
19 import types
20 from IPython.genutils import list2dict2
21
22 class Struct:
23 """Class to mimic C structs but also provide convenient dictionary-like
24 functionality.
25
26 Instances can be initialized with a dictionary, a list of key=value pairs
27 or both. If both are present, the dictionary must come first.
28
29 Because Python classes provide direct assignment to their members, it's
30 easy to overwrite normal methods (S.copy = 1 would destroy access to
31 S.copy()). For this reason, all builtin method names are protected and
32 can't be assigned to. An attempt to do s.copy=1 or s['copy']=1 will raise
33 a KeyError exception. If you really want to, you can bypass this
34 protection by directly assigning to __dict__: s.__dict__['copy']=1 will
35 still work. Doing this will break functionality, though. As in most of
36 Python, namespace protection is weakly enforced, so feel free to shoot
37 yourself if you really want to.
38
39 Note that this class uses more memory and is *much* slower than a regular
40 dictionary, so be careful in situations where memory or performance are
41 critical. But for day to day use it should behave fine. It is particularly
42 convenient for storing configuration data in programs.
43
44 +,+=,- and -= are implemented. +/+= do merges (non-destructive updates),
45 -/-= remove keys from the original. See the method descripitions.
46
47 This class allows a quick access syntax: both s.key and s['key'] are
48 valid. This syntax has a limitation: each 'key' has to be explicitly
49 accessed by its original name. The normal s.key syntax doesn't provide
50 access to the keys via variables whose values evaluate to the desired
51 keys. An example should clarify this:
52
53 Define a dictionary and initialize both with dict and k=v pairs:
54 >>> d={'a':1,'b':2}
55 >>> s=Struct(d,hi=10,ho=20)
56 The return of __repr__ can be used to create a new instance:
57 >>> s
58 Struct({'ho': 20, 'b': 2, 'hi': 10, 'a': 1})
59 __str__ (called by print) shows it's not quite a regular dictionary:
60 >>> print s
61 Struct {a: 1, b: 2, hi: 10, ho: 20}
62 Access by explicitly named key with dot notation:
63 >>> s.a
64 1
65 Or like a dictionary:
66 >>> s['a']
67 1
68 If you want a variable to hold the key value, only dictionary access works:
69 >>> key='hi'
70 >>> s.key
71 Traceback (most recent call last):
72 File "<stdin>", line 1, in ?
73 AttributeError: Struct instance has no attribute 'key'
74 >>> s[key]
75 10
76
77 Another limitation of the s.key syntax (and Struct(key=val)
78 initialization): keys can't be numbers. But numeric keys can be used and
79 accessed using the dictionary syntax. Again, an example:
80
81 This doesn't work:
82 >>> s=Struct(4='hi')
83 SyntaxError: keyword can't be an expression
84 But this does:
85 >>> s=Struct()
86 >>> s[4]='hi'
87 >>> s
88 Struct({4: 'hi'})
89 >>> s[4]
90 'hi'
91 """
92
93 # Attributes to which __setitem__ and __setattr__ will block access.
94 # Note: much of this will be moot in Python 2.2 and will be done in a much
95 # cleaner way.
96 __protected = ('copy dict dictcopy get has_attr has_key items keys '
97 'merge popitem setdefault update values '
98 '__make_dict __dict_invert ').split()
99
100 def __init__(self,dict=None,**kw):
101 """Initialize with a dictionary, another Struct, or by giving
102 explicitly the list of attributes.
103
104 Both can be used, but the dictionary must come first:
105 Struct(dict), Struct(k1=v1,k2=v2) or Struct(dict,k1=v1,k2=v2).
106 """
107 if dict is None:
108 dict = {}
109 if isinstance(dict,Struct):
110 dict = dict.dict()
111 elif dict and type(dict) is not types.DictType:
112 raise TypeError,\
113 'Initialize with a dictionary or key=val pairs.'
114 dict.update(kw)
115 # do the updating by hand to guarantee that we go through the
116 # safety-checked __setitem__
117 for k,v in dict.items():
118 self[k] = v
119
120 def __setitem__(self,key,value):
121 """Used when struct[key] = val calls are made."""
122 if key in Struct.__protected:
123 raise KeyError,'Key '+`key`+' is a protected key of class Struct.'
124 self.__dict__[key] = value
125
126 def __setattr__(self, key, value):
127 """Used when struct.key = val calls are made."""
128 self.__setitem__(key,value)
129
130 def __str__(self):
131 """Gets called by print."""
132
133 return 'Struct('+str(self.__dict__)+')'
134
135 def __repr__(self):
136 """Gets called by repr.
137
138 A Struct can be recreated with S_new=eval(repr(S_old))."""
139 return 'Struct('+str(self.__dict__)+')'
140
141 def __getitem__(self,key):
142 """Allows struct[key] access."""
143 return self.__dict__[key]
144
145 def __contains__(self,key):
146 """Allows use of the 'in' operator."""
147 return self.__dict__.has_key(key)
148
149 def __iadd__(self,other):
150 """S += S2 is a shorthand for S.merge(S2)."""
151 self.merge(other)
152 return self
153
154 def __add__(self,other):
155 """S + S2 -> New Struct made form S and S.merge(S2)"""
156 Sout = self.copy()
157 Sout.merge(other)
158 return Sout
159
160 def __sub__(self,other):
161 """Return S1-S2, where all keys in S2 have been deleted (if present)
162 from S1."""
163 Sout = self.copy()
164 Sout -= other
165 return Sout
166
167 def __isub__(self,other):
168 """Do in place S = S - S2, meaning all keys in S2 have been deleted
169 (if present) from S1."""
170
171 for k in other.keys():
172 if self.has_key(k):
173 del self.__dict__[k]
174
175 def __make_dict(self,__loc_data__,**kw):
176 "Helper function for update and merge. Return a dict from data."
177
178 if __loc_data__ == None:
179 dict = {}
180 elif type(__loc_data__) is types.DictType:
181 dict = __loc_data__
182 elif isinstance(__loc_data__,Struct):
183 dict = __loc_data__.__dict__
184 else:
185 raise TypeError, 'Update with a dict, a Struct or key=val pairs.'
186 if kw:
187 dict.update(kw)
188 return dict
189
190 def __dict_invert(self,dict):
191 """Helper function for merge. Takes a dictionary whose values are
192 lists and returns a dict. with the elements of each list as keys and
193 the original keys as values."""
194
195 outdict = {}
196 for k,lst in dict.items():
197 if type(lst) is types.StringType:
198 lst = lst.split()
199 for entry in lst:
200 outdict[entry] = k
201 return outdict
202
203 def clear(self):
204 """Clear all attributes."""
205 self.__dict__.clear()
206
207 def copy(self):
208 """Return a (shallow) copy of a Struct."""
209 return Struct(self.__dict__.copy())
210
211 def dict(self):
212 """Return the Struct's dictionary."""
213 return self.__dict__
214
215 def dictcopy(self):
216 """Return a (shallow) copy of the Struct's dictionary."""
217 return self.__dict__.copy()
218
219 def popitem(self):
220 """S.popitem() -> (k, v), remove and return some (key, value) pair as
221 a 2-tuple; but raise KeyError if S is empty."""
222 return self.__dict__.popitem()
223
224 def update(self,__loc_data__=None,**kw):
225 """Update (merge) with data from another Struct or from a dictionary.
226 Optionally, one or more key=value pairs can be given at the end for
227 direct update."""
228
229 # The funny name __loc_data__ is to prevent a common variable name which
230 # could be a fieled of a Struct to collide with this parameter. The problem
231 # would arise if the function is called with a keyword with this same name
232 # that a user means to add as a Struct field.
233 newdict = Struct.__make_dict(self,__loc_data__,**kw)
234 for k,v in newdict.items():
235 self[k] = v
236
237 def merge(self,__loc_data__=None,__conflict_solve=None,**kw):
238 """S.merge(data,conflict,k=v1,k=v2,...) -> merge data and k=v into S.
239
240 This is similar to update(), but much more flexible. First, a dict is
241 made from data+key=value pairs. When merging this dict with the Struct
242 S, the optional dictionary 'conflict' is used to decide what to do.
243
244 If conflict is not given, the default behavior is to preserve any keys
245 with their current value (the opposite of the update method's
246 behavior).
247
248 conflict is a dictionary of binary functions which will be used to
249 solve key conflicts. It must have the following structure:
250
251 conflict == { fn1 : [Skey1,Skey2,...], fn2 : [Skey3], etc }
252
253 Values must be lists or whitespace separated strings which are
254 automatically converted to lists of strings by calling string.split().
255
256 Each key of conflict is a function which defines a policy for
257 resolving conflicts when merging with the input data. Each fn must be
258 a binary function which returns the desired outcome for a key
259 conflict. These functions will be called as fn(old,new).
260
261 An example is probably in order. Suppose you are merging the struct S
262 with a dict D and the following conflict policy dict:
263
264 S.merge(D,{fn1:['a','b',4], fn2:'key_c key_d'})
265
266 If the key 'a' is found in both S and D, the merge method will call:
267
268 S['a'] = fn1(S['a'],D['a'])
269
270 As a convenience, merge() provides five (the most commonly needed)
271 pre-defined policies: preserve, update, add, add_flip and add_s. The
272 easiest explanation is their implementation:
273
274 preserve = lambda old,new: old
275 update = lambda old,new: new
276 add = lambda old,new: old + new
277 add_flip = lambda old,new: new + old # note change of order!
278 add_s = lambda old,new: old + ' ' + new # only works for strings!
279
280 You can use those four words (as strings) as keys in conflict instead
281 of defining them as functions, and the merge method will substitute
282 the appropriate functions for you. That is, the call
283
284 S.merge(D,{'preserve':'a b c','add':[4,5,'d'],my_function:[6]})
285
286 will automatically substitute the functions preserve and add for the
287 names 'preserve' and 'add' before making any function calls.
288
289 For more complicated conflict resolution policies, you still need to
290 construct your own functions. """
291
292 data_dict = Struct.__make_dict(self,__loc_data__,**kw)
293
294 # policies for conflict resolution: two argument functions which return
295 # the value that will go in the new struct
296 preserve = lambda old,new: old
297 update = lambda old,new: new
298 add = lambda old,new: old + new
299 add_flip = lambda old,new: new + old # note change of order!
300 add_s = lambda old,new: old + ' ' + new
301
302 # default policy is to keep current keys when there's a conflict
303 conflict_solve = list2dict2(self.keys(),default = preserve)
304
305 # the conflict_solve dictionary is given by the user 'inverted': we
306 # need a name-function mapping, it comes as a function -> names
307 # dict. Make a local copy (b/c we'll make changes), replace user
308 # strings for the three builtin policies and invert it.
309 if __conflict_solve:
310 inv_conflict_solve_user = __conflict_solve.copy()
311 for name, func in [('preserve',preserve), ('update',update),
312 ('add',add), ('add_flip',add_flip), ('add_s',add_s)]:
313 if name in inv_conflict_solve_user.keys():
314 inv_conflict_solve_user[func] = inv_conflict_solve_user[name]
315 del inv_conflict_solve_user[name]
316 conflict_solve.update(Struct.__dict_invert(self,inv_conflict_solve_user))
317 #print 'merge. conflict_solve: '; pprint(conflict_solve) # dbg
318 # after Python 2.2, use iterators: for key in data_dict will then work
319 #print '*'*50,'in merger. conflict_solver:'; pprint(conflict_solve)
320 for key in data_dict.keys():
321 if key not in self:
322 self[key] = data_dict[key]
323 else:
324 self[key] = conflict_solve[key](self[key],data_dict[key])
325
326 def has_key(self,key):
327 """Like has_key() dictionary method."""
328 return self.__dict__.has_key(key)
329
330 def hasattr(self,key):
331 """hasattr function available as a method.
332
333 Implemented like has_key, to make sure that all available keys in the
334 internal dictionary of the Struct appear also as attributes (even
335 numeric keys)."""
336 return self.__dict__.has_key(key)
337
338 def items(self):
339 """Return the items in the Struct's dictionary, in the same format
340 as a call to {}.items()."""
341 return self.__dict__.items()
342
343 def keys(self):
344 """Return the keys in the Struct's dictionary, in the same format
345 as a call to {}.keys()."""
346 return self.__dict__.keys()
347
348 def values(self,keys=None):
349 """Return the values in the Struct's dictionary, in the same format
350 as a call to {}.values().
351
352 Can be called with an optional argument keys, which must be a list or
353 tuple of keys. In this case it returns only the values corresponding
354 to those keys (allowing a form of 'slicing' for Structs)."""
355 if not keys:
356 return self.__dict__.values()
357 else:
358 ret=[]
359 for k in keys:
360 ret.append(self[k])
361 return ret
362
363 def get(self,attr,val=None):
364 """S.get(k[,d]) -> S[k] if S.has_key(k), else d. d defaults to None."""
365 try:
366 return self[attr]
367 except KeyError:
368 return val
369
370 def setdefault(self,attr,val=None):
371 """S.setdefault(k[,d]) -> S.get(k,d), also set S[k]=d if not S.has_key(k)"""
372 if not self.has_key(attr):
373 self[attr] = val
374 return self.get(attr,val)
375 # end class Struct
376
This diff has been collapsed as it changes many lines, (546 lines changed) Show them Hide them
@@ -0,0 +1,546 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 596 2005-06-01 17:01:13Z fperez $
3
4 #***************************************************************************
5 #
6 # Configuration file for IPython -- ipythonrc format
7 #
8 # The format of this file is simply one of 'key value' lines.
9 # Lines containing only whitespace at the beginning and then a # are ignored
10 # as comments. But comments can NOT be put on lines with data.
11
12 # The meaning and use of each key are explained below.
13
14 #---------------------------------------------------------------------------
15 # Section: included files
16
17 # Put one or more *config* files (with the syntax of this file) you want to
18 # include. For keys with a unique value the outermost file has precedence. For
19 # keys with multiple values, they all get assembled into a list which then
20 # gets loaded by IPython.
21
22 # In this file, all lists of things should simply be space-separated.
23
24 # This allows you to build hierarchies of files which recursively load
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 # should only keep here basic things you always want available. Then you can
27 # include it in every other special-purpose config file you create.
28 include
29
30 #---------------------------------------------------------------------------
31 # Section: startup setup
32
33 # These are mostly things which parallel a command line option of the same
34 # name.
35
36 # Keys in this section should only appear once. If any key from this section
37 # is encountered more than once, the last value remains, all earlier ones get
38 # discarded.
39
40 # Automatic calling of callable objects. If set to true, callable objects are
41 # automatically called when invoked at the command line, even if you don't
42 # type parentheses. IPython adds the parentheses for you. For example:
43
44 #In [1]: str 45
45 #------> str(45)
46 #Out[1]: '45'
47
48 # IPython reprints your line with '---->' indicating that it added
49 # parentheses. While this option is very convenient for interactive use, it
50 # may occasionally cause problems with objects which have side-effects if
51 # called unexpectedly. Set it to 0 if you want to disable it.
52
53 # Note that even with autocall off, you can still use '/' at the start of a
54 # line to treat the first argument on the command line as a function and add
55 # parentheses to it:
56
57 #In [8]: /str 43
58 #------> str(43)
59 #Out[8]: '43'
60
61 autocall 1
62
63 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
64 # line, while also un-indenting automatically after 'raise' or 'return'.
65
66 # This feature uses the readline library, so it will honor your ~/.inputrc
67 # configuration (or whatever file your INPUTRC variable points to). Adding
68 # the following lines to your .inputrc file can make indent/unindenting more
69 # convenient (M-i indents, M-u unindents):
70
71 # $if Python
72 # "\M-i": " "
73 # "\M-u": "\d\d\d\d"
74 # $endif
75
76 # The feature is potentially a bit dangerous, because it can cause problems
77 # with pasting of indented code (the pasted code gets re-indented on each
78 # line). But it's a huge time-saver when working interactively. The magic
79 # function @autoindent allows you to toggle it on/off at runtime.
80
81 autoindent 1
82
83 # Auto-magic. This gives you access to all the magic functions without having
84 # to prepend them with an @ sign. If you define a variable with the same name
85 # as a magic function (say who=1), you will need to access the magic function
86 # with @ (@who in this example). However, if later you delete your variable
87 # (del who), you'll recover the automagic calling form.
88
89 # Considering that many magic functions provide a lot of shell-like
90 # functionality, automagic gives you something close to a full Python+system
91 # shell environment (and you can extend it further if you want).
92
93 automagic 1
94
95 # Size of the output cache. After this many entries are stored, the cache will
96 # get flushed. Depending on the size of your intermediate calculations, you
97 # may have memory problems if you make it too big, since keeping things in the
98 # cache prevents Python from reclaiming the memory for old results. Experiment
99 # with a value that works well for you.
100
101 # If you choose cache_size 0 IPython will revert to python's regular >>>
102 # unnumbered prompt. You will still have _, __ and ___ for your last three
103 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
104 # you are running on a slow machine or with very limited memory, this may
105 # help.
106
107 cache_size 1000
108
109 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
110 # but that's your choice! Classic 1 -> same as IPython -classic.
111 # Note that this is _not_ the normal python interpreter, it's simply
112 # IPython emulating most of the classic interpreter's behavior.
113 classic 0
114
115 # colors - Coloring option for prompts and traceback printouts.
116
117 # Currently available schemes: NoColor, Linux, LightBG.
118
119 # This option allows coloring the prompts and traceback printouts. This
120 # requires a terminal which can properly handle color escape sequences. If you
121 # are having problems with this, use the NoColor scheme (uses no color escapes
122 # at all).
123
124 # The Linux option works well in linux console type environments: dark
125 # background with light fonts.
126
127 # LightBG is similar to Linux but swaps dark/light colors to be more readable
128 # in light background terminals.
129
130 # keep uncommented only the one you want:
131 colors Linux
132 #colors LightBG
133 #colors NoColor
134
135 ########################
136 # Note to Windows users
137 #
138 # Color and readline support is avaialble to Windows users via Gary Bishop's
139 # readline library. You can find Gary's tools at
140 # http://sourceforge.net/projects/uncpythontools.
141 # Note that his readline module requires in turn the ctypes library, available
142 # at http://starship.python.net/crew/theller/ctypes.
143 ########################
144
145 # color_info: IPython can display information about objects via a set of
146 # functions, and optionally can use colors for this, syntax highlighting
147 # source code and various other elements. This information is passed through a
148 # pager (it defaults to 'less' if $PAGER is not set).
149
150 # If your pager has problems, try to setting it to properly handle escapes
151 # (see the less manpage for detail), or disable this option. The magic
152 # function @color_info allows you to toggle this interactively for testing.
153
154 color_info 1
155
156 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
157 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
158 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
159 # any confirmation.
160
161 confirm_exit 1
162
163 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
164 # still available as dreload() and appears as a builtin.
165
166 deep_reload 0
167
168 # Which editor to use with the @edit command. If you leave this at 0, IPython
169 # will honor your EDITOR environment variable. Since this editor is invoked on
170 # the fly by ipython and is meant for editing small code snippets, you may
171 # want to use a small, lightweight editor here.
172
173 # For Emacs users, setting up your Emacs server properly as described in the
174 # manual is a good idea. An alternative is to use jed, a very light editor
175 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
176
177 editor 0
178
179 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
180 log 0
181
182 # Same as ipython -Logfile YourLogfileName.
183 # Don't use with log 1 (use one or the other)
184 logfile ''
185
186 # banner 0 -> same as ipython -nobanner
187 banner 1
188
189 # messages 0 -> same as ipython -nomessages
190 messages 1
191
192 # Automatically call the pdb debugger after every uncaught exception. If you
193 # are used to debugging using pdb, this puts you automatically inside of it
194 # after any call (either in IPython or in code called by it) which triggers an
195 # exception which goes uncaught.
196 pdb 0
197
198 # Enable the pprint module for printing. pprint tends to give a more readable
199 # display (than print) for complex nested data structures.
200 pprint 1
201
202 # Prompt strings
203
204 # Most bash-like escapes can be used to customize IPython's prompts, as well as
205 # a few additional ones which are IPython-specific. All valid prompt escapes
206 # are described in detail in the Customization section of the IPython HTML/PDF
207 # manual.
208
209 # Use \# to represent the current prompt number, and quote them to protect
210 # spaces.
211 prompt_in1 'In [\#]: '
212
213 # \D is replaced by as many dots as there are digits in the
214 # current value of \#.
215 prompt_in2 ' .\D.: '
216
217 prompt_out 'Out[\#]: '
218
219 # Select whether to left-pad the output prompts to match the length of the
220 # input ones. This allows you for example to use a simple '>' as an output
221 # prompt, and yet have the output line up with the input. If set to false,
222 # the output prompts will be unpadded (flush left).
223 prompts_pad_left 1
224
225 # quick 1 -> same as ipython -quick
226 quick 0
227
228 # Use the readline library (1) or not (0). Most users will want this on, but
229 # if you experience strange problems with line management (mainly when using
230 # IPython inside Emacs buffers) you may try disabling it. Not having it on
231 # prevents you from getting command history with the arrow keys, searching and
232 # name completion using TAB.
233
234 readline 1
235
236 # Screen Length: number of lines of your screen. This is used to control
237 # printing of very long strings. Strings longer than this number of lines will
238 # be paged with the less command instead of directly printed.
239
240 # The default value for this is 0, which means IPython will auto-detect your
241 # screen size every time it needs to print. If for some reason this isn't
242 # working well (it needs curses support), specify it yourself. Otherwise don't
243 # change the default.
244
245 screen_length 0
246
247 # Prompt separators for input and output.
248 # Use \n for newline explicitly, without quotes.
249 # Use 0 (like at the cmd line) to turn off a given separator.
250
251 # The structure of prompt printing is:
252 # (SeparateIn)Input....
253 # (SeparateOut)Output...
254 # (SeparateOut2), # that is, no newline is printed after Out2
255 # By choosing these you can organize your output any way you want.
256
257 separate_in \n
258 separate_out 0
259 separate_out2 0
260
261 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
262 # Simply removes all input/output separators, overriding the choices above.
263 nosep 0
264
265 # xmode - Exception reporting mode.
266
267 # Valid modes: Plain, Context and Verbose.
268
269 # Plain: similar to python's normal traceback printing.
270
271 # Context: prints 5 lines of context source code around each line in the
272 # traceback.
273
274 # Verbose: similar to Context, but additionally prints the variables currently
275 # visible where the exception happened (shortening their strings if too
276 # long). This can potentially be very slow, if you happen to have a huge data
277 # structure whose string representation is complex to compute. Your computer
278 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
279 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
280
281 #xmode Plain
282 xmode Context
283 #xmode Verbose
284
285 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
286 # !cmd) to be used in multi-line input (like for loops). For example, if you
287 # have this active, the following is valid in IPython:
288 #
289 #In [17]: for i in range(3):
290 # ....: mkdir $i
291 # ....: !touch $i/hello
292 # ....: ls -l $i
293
294 multi_line_specials 1
295
296 #---------------------------------------------------------------------------
297 # Section: Readline configuration (readline is not available for MS-Windows)
298
299 # This is done via the following options:
300
301 # (i) readline_parse_and_bind: this option can appear as many times as you
302 # want, each time defining a string to be executed via a
303 # readline.parse_and_bind() command. The syntax for valid commands of this
304 # kind can be found by reading the documentation for the GNU readline library,
305 # as these commands are of the kind which readline accepts in its
306 # configuration file.
307
308 # The TAB key can be used to complete names at the command line in one of two
309 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
310 # completes as much as possible while 'menu-complete' cycles through all
311 # possible completions. Leave the one you prefer uncommented.
312
313 readline_parse_and_bind tab: complete
314 #readline_parse_and_bind tab: menu-complete
315
316 # This binds Control-l to printing the list of all possible completions when
317 # there is more than one (what 'complete' does when hitting TAB twice, or at
318 # the first TAB if show-all-if-ambiguous is on)
319 readline_parse_and_bind "\C-l": possible-completions
320
321 # This forces readline to automatically print the above list when tab
322 # completion is set to 'complete'. You can still get this list manually by
323 # using the key bound to 'possible-completions' (Control-l by default) or by
324 # hitting TAB twice. Turning this on makes the printing happen at the first
325 # TAB.
326 readline_parse_and_bind set show-all-if-ambiguous on
327
328 # If you have TAB set to complete names, you can rebind any key (Control-o by
329 # default) to insert a true TAB character.
330 readline_parse_and_bind "\C-o": tab-insert
331
332 # These commands allow you to indent/unindent easily, with the 4-space
333 # convention of the Python coding standards. Since IPython's internal
334 # auto-indent system also uses 4 spaces, you should not change the number of
335 # spaces in the code below.
336 readline_parse_and_bind "\M-i": " "
337 readline_parse_and_bind "\M-o": "\d\d\d\d"
338 readline_parse_and_bind "\M-I": "\d\d\d\d"
339
340 # Bindings for incremental searches in the history. These searches use the
341 # string typed so far on the command line and search anything in the previous
342 # input history containing them.
343 readline_parse_and_bind "\C-r": reverse-search-history
344 readline_parse_and_bind "\C-s": forward-search-history
345
346 # Bindings for completing the current line in the history of previous
347 # commands. This allows you to recall any previous command by typing its first
348 # few letters and hitting Control-p, bypassing all intermediate commands which
349 # may be in the history (much faster than hitting up-arrow 50 times!)
350 readline_parse_and_bind "\C-p": history-search-backward
351 readline_parse_and_bind "\C-n": history-search-forward
352
353 # I also like to have the same functionality on the plain arrow keys. If you'd
354 # rather have the arrows use all the history (and not just match what you've
355 # typed so far), comment out or delete the next two lines.
356 readline_parse_and_bind "\e[A": history-search-backward
357 readline_parse_and_bind "\e[B": history-search-forward
358
359 # (ii) readline_remove_delims: a string of characters to be removed from the
360 # default word-delimiters list used by readline, so that completions may be
361 # performed on strings which contain them.
362
363 readline_remove_delims -/~
364
365 # (iii) readline_merge_completions: whether to merge the result of all
366 # possible completions or not. If true, IPython will complete filenames,
367 # python names and aliases and return all possible completions. If you set it
368 # to false, each completer is used at a time, and only if it doesn't return
369 # any completions is the next one used.
370
371 # The default order is: [python_matches, file_matches, alias_matches]
372
373 readline_merge_completions 1
374
375 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
376 # will complete all attributes of an object, including all the special methods
377 # whose names start with single or double underscores (like __getitem__ or
378 # __class__).
379
380 # This variable allows you to control this completion behavior:
381
382 # readline_omit__names 1 -> completion will omit showing any names starting
383 # with two __, but it will still show names starting with one _.
384
385 # readline_omit__names 2 -> completion will omit all names beginning with one
386 # _ (which obviously means filtering out the double __ ones).
387
388 # Even when this option is set, you can still see those names by explicitly
389 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
390 # complete attribute names starting with '_'.
391
392 # This option is off by default so that new users see all attributes of any
393 # objects they are dealing with.
394
395 readline_omit__names 0
396
397 #---------------------------------------------------------------------------
398 # Section: modules to be loaded with 'import ...'
399
400 # List, separated by spaces, the names of the modules you want to import
401
402 # Example:
403 # import_mod sys os
404 # will produce internally the statements
405 # import sys
406 # import os
407
408 # Each import is executed in its own try/except block, so if one module
409 # fails to load the others will still be ok.
410
411 import_mod
412
413 #---------------------------------------------------------------------------
414 # Section: modules to import some functions from: 'from ... import ...'
415
416 # List, one per line, the modules for which you want only to import some
417 # functions. Give the module name first and then the name of functions to be
418 # imported from that module.
419
420 # Example:
421
422 # import_some IPython.genutils timing timings
423 # will produce internally the statement
424 # from IPython.genutils import timing, timings
425
426 # timing() and timings() are two IPython utilities for timing the execution of
427 # your own functions, which you may find useful. Just commment out the above
428 # line if you want to test them.
429
430 # If you have more than one modules_some line, each gets its own try/except
431 # block (like modules, see above).
432
433 import_some
434
435 #---------------------------------------------------------------------------
436 # Section: modules to import all from : 'from ... import *'
437
438 # List (same syntax as import_mod above) those modules for which you want to
439 # import all functions. Remember, this is a potentially dangerous thing to do,
440 # since it is very easy to overwrite names of things you need. Use with
441 # caution.
442
443 # Example:
444 # import_all sys os
445 # will produce internally the statements
446 # from sys import *
447 # from os import *
448
449 # As before, each will be called in a separate try/except block.
450
451 import_all
452
453 #---------------------------------------------------------------------------
454 # Section: Python code to execute.
455
456 # Put here code to be explicitly executed (keep it simple!)
457 # Put one line of python code per line. All whitespace is removed (this is a
458 # feature, not a bug), so don't get fancy building loops here.
459 # This is just for quick convenient creation of things you want available.
460
461 # Example:
462 # execute x = 1
463 # execute print 'hello world'; y = z = 'a'
464 # will produce internally
465 # x = 1
466 # print 'hello world'; y = z = 'a'
467 # and each *line* (not each statement, we don't do python syntax parsing) is
468 # executed in its own try/except block.
469
470 execute
471
472 # Note for the adventurous: you can use this to define your own names for the
473 # magic functions, by playing some namespace tricks:
474
475 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
476
477 # defines @pf as a new name for @profile.
478
479 #---------------------------------------------------------------------------
480 # Section: Pyhton files to load and execute.
481
482 # Put here the full names of files you want executed with execfile(file). If
483 # you want complicated initialization, just write whatever you want in a
484 # regular python file and load it from here.
485
486 # Filenames defined here (which *must* include the extension) are searched for
487 # through all of sys.path. Since IPython adds your .ipython directory to
488 # sys.path, they can also be placed in your .ipython dir and will be
489 # found. Otherwise (if you want to execute things not in .ipyton nor in
490 # sys.path) give a full path (you can use ~, it gets expanded)
491
492 # Example:
493 # execfile file1.py ~/file2.py
494 # will generate
495 # execfile('file1.py')
496 # execfile('_path_to_your_home/file2.py')
497
498 # As before, each file gets its own try/except block.
499
500 execfile
501
502 # If you are feeling adventurous, you can even add functionality to IPython
503 # through here. IPython works through a global variable called __ip which
504 # exists at the time when these files are read. If you know what you are doing
505 # (read the source) you can add functions to __ip in files loaded here.
506
507 # The file example-magic.py contains a simple but correct example. Try it:
508
509 # execfile example-magic.py
510
511 # Look at the examples in IPython/iplib.py for more details on how these magic
512 # functions need to process their arguments.
513
514 #---------------------------------------------------------------------------
515 # Section: aliases for system shell commands
516
517 # Here you can define your own names for system commands. The syntax is
518 # similar to that of the builtin @alias function:
519
520 # alias alias_name command_string
521
522 # The resulting aliases are auto-generated magic functions (hence usable as
523 # @alias_name)
524
525 # For example:
526
527 # alias myls ls -la
528
529 # will define 'myls' as an alias for executing the system command 'ls -la'.
530 # This allows you to customize IPython's environment to have the same aliases
531 # you are accustomed to from your own shell.
532
533 # You can also define aliases with parameters using %s specifiers (one per
534 # parameter):
535
536 # alias parts echo first %s second %s
537
538 # will give you in IPython:
539 # >>> @parts A B
540 # first A second B
541
542 # Use one 'alias' statement per alias you wish to define.
543
544 # alias
545
546 #************************* end of file <ipythonrc> ************************
@@ -0,0 +1,36 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 #***************************************************************************
3 #
4 # Configuration file for ipython -- ipythonrc format
5 #
6 # The format of this file is one of 'key value' lines.
7 # Lines containing only whitespace at the beginning and then a # are ignored
8 # as comments. But comments can NOT be put on lines with data.
9 #***************************************************************************
10
11 # This is an example of a 'profile' file which includes a base file and adds
12 # some customizaton for a particular purpose.
13
14 # If this file is found in the user's ~/.ipython directory as ipythonrc-math,
15 # it can be loaded by calling passing the '-profile math' (or '-p math')
16 # option to IPython.
17
18 # This example is a light customization to have ipython have basic math functions
19 # readily available, effectively making the python prompt a very capable scientific
20 # calculator
21
22 # include base config and only add some extras
23 include ipythonrc
24
25 # load the complex math functions but keep them in a separate namespace
26 import_mod cmath
27
28 # from ... import *
29 # load the real math functions in the global namespace for convenience
30 import_all math
31
32 # from ... import ...
33 import_some
34
35 # code to execute
36 execute print "*** math functions available globally, cmath as a module"
@@ -0,0 +1,57 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 #***************************************************************************
3 #
4 # Configuration file for ipython -- ipythonrc format
5 #
6 # The format of this file is one of 'key value' lines.
7 # Lines containing only whitespace at the beginning and then a # are ignored
8 # as comments. But comments can NOT be put on lines with data.
9 #***************************************************************************
10
11 # This is an example of a 'profile' file which includes a base file and adds
12 # some customizaton for a particular purpose.
13
14 # If this file is found in the user's ~/.ipython directory as
15 # ipythonrc-numeric, it can be loaded by calling passing the '-profile
16 # numeric' (or '-p numeric') option to IPython.
17
18 # A simple alias numpy -> 'ipython -p numeric' makes life very convenient.
19
20 # This example is meant to load several modules to turn IPython into a very
21 # capable environment for high-end numerical work, similar to IDL or MatLab
22 # but with the beauty and flexibility of the Python language.
23
24 # Load the user's basic configuration
25 include ipythonrc
26
27 # import ...
28
29 # Load Numeric by itself so that 'help Numeric' works
30 import_mod Numeric
31
32 # from ... import *
33 # GnuplotRuntime loads Gnuplot and adds enhancements for use in IPython
34 import_all Numeric IPython.numutils IPython.GnuplotInteractive
35
36 # a simple line at zero, often useful for an x-axis
37 execute xaxis=gpfunc('0',title='',with='lines lt -1')
38
39 # Below are optional things off by default. Uncomment them if desired.
40
41 # MA (MaskedArray) modifies the Numeric printing mechanism so that huge arrays
42 # are only summarized and not printed (which may freeze the machine for a
43 # _long_ time).
44
45 #import_mod MA
46
47
48 # gracePlot is a Python interface to the plotting package Grace.
49 # For more details go to: http://www.idyll.org/~n8gray/code/index.html
50 # Uncomment lines below if you have grace and its python support code
51
52 #import_mod gracePlot
53 #execute grace = gracePlot.gracePlot # alias to make gracePlot instances
54 #execute print '*** grace is an alias for gracePlot.gracePlot'
55
56 # Files to execute
57 execfile
@@ -0,0 +1,43 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 #***************************************************************************
3 #
4 # Configuration file for ipython -- ipythonrc format
5 #
6 # The format of this file is one of 'key value' lines.
7 # Lines containing only whitespace at the beginning and then a # are ignored
8 # as comments. But comments can NOT be put on lines with data.
9 #***************************************************************************
10
11 # If this file is found in the user's ~/.ipython directory as
12 # ipythonrc-physics, it can be loaded by calling passing the '-profile
13 # physics' (or '-p physics') option to IPython.
14
15 # This profile loads modules useful for doing interactive calculations with
16 # physical quantities (with units). It relies on modules from Konrad Hinsen's
17 # ScientificPython (http://starship.python.net/crew/hinsen/)
18
19 # First load basic user configuration
20 include ipythonrc
21
22 # import ...
23 # Module with alternate input syntax for PhysicalQuantity objects.
24 import_mod IPython.Extensions.PhysicalQInput
25
26 # from ... import *
27 # math CANNOT be imported after PhysicalQInteractive. It will override the
28 # functions defined there.
29 import_all math IPython.Extensions.PhysicalQInteractive
30
31 # from ... import ...
32 import_some
33
34 # code
35 execute q = PhysicalQuantityInteractive
36 execute g = PhysicalQuantityInteractive('9.8 m/s**2')
37 ececute rad = pi/180.
38 execute print '*** q is an alias for PhysicalQuantityInteractive'
39 execute print '*** g = 9.8 m/s^2 has been defined'
40 execute print '*** rad = pi/180 has been defined'
41
42 # Files to execute
43 execfile
@@ -0,0 +1,94 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 #***************************************************************************
3 # Configuration file for ipython -- ipythonrc format
4 #
5 # The format of this file is one of 'key value' lines.
6 # Lines containing only whitespace at the beginning and then a # are ignored
7 # as comments. But comments can NOT be put on lines with data.
8 #***************************************************************************
9
10 # If this file is found in the user's ~/.ipython directory as ipythonrc-pysh,
11 # it can be loaded by calling passing the '-profile pysh' (or '-p pysh')
12 # option to IPython.
13
14 # This profile turns IPython into a lightweight system shell with python
15 # syntax.
16
17 # We only set a few options here, the rest is done in the companion pysh.py
18 # file. In the future _all_ of IPython's configuration will be done via
19 # proper python code.
20
21 ############################################################################
22 # First load common user configuration
23 include ipythonrc
24
25 ############################################################################
26 # Load all the actual syntax extensions for shell-like operation, which live
27 # in the InterpreterExec standard extension.
28 import_all IPython.Extensions.InterpreterExec
29
30 ############################################################################
31 # PROMPTS
32 #
33 # Configure prompt for more shell-like usage.
34
35 # Most bash-like escapes can be used to customize IPython's prompts, as well as
36 # a few additional ones which are IPython-specific. All valid prompt escapes
37 # are described in detail in the Customization section of the IPython HTML/PDF
38 # manual.
39
40 prompt_in1 '\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
41 prompt_in2 '\C_Green|\C_LightGreen\D\C_Green> '
42 prompt_out '<\#> '
43
44 # Here's a more complex prompt, showing the hostname and more path depth (\Y3)
45 #prompt_in1 '\C_LightRed\u\C_Blue@\C_Red\h\C_LightBlue[\C_LightCyan\Y3\C_LightBlue]\C_LightGreen\#> '
46
47 # Select whether to left-pad the output prompts to match the length of the
48 # input ones. This allows you for example to use a simple '>' as an output
49 # prompt, and yet have the output line up with the input. If set to false,
50 # the output prompts will be unpadded (flush left).
51 prompts_pad_left 1
52
53
54 # Remove all blank lines in between prompts, like a normal shell.
55 separate_in 0
56 separate_out 0
57 separate_out2 0
58
59 # Allow special syntax (!, magics and aliases) in multiline input
60 multi_line_specials 1
61
62 ############################################################################
63 # ALIASES
64
65 # Declare some common aliases. Type alias? at an ipython prompt for details on
66 # the syntax, use @unalias to delete existing aliases.
67
68 # Don't go too crazy here, the file pysh.py called below runs @rehash, which
69 # loads ALL of your $PATH as aliases (except for Python keywords and
70 # builtins).
71
72 # Some examples:
73
74 # A simple alias without arguments
75 #alias cl clear
76
77 # An alias which expands the full line before the end of the alias. This
78 # lists only directories:
79 #alias ldir pwd;ls -oF --color %l | grep /$
80
81 # An alias with two positional arguments:
82 #alias parts echo 'First <%s> Second <%s>'
83
84 # In use these two aliases give (note that ldir is already built into IPython
85 # for Unix):
86
87 #fperez[IPython]16> ldir
88 #/usr/local/home/fperez/ipython/ipython/IPython
89 #drwxr-xr-x 2 fperez 4096 Jun 21 01:01 CVS/
90 #drwxr-xr-x 3 fperez 4096 Jun 21 01:10 Extensions/
91 #drwxr-xr-x 3 fperez 4096 Jun 21 01:27 UserConfig/
92
93 #fperez[IPython]17> parts Hello world and goodbye
94 #First <Hello> Second <world> and goodbye
@@ -0,0 +1,43 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 #***************************************************************************
3 #
4 # Configuration file for ipython -- ipythonrc format
5 #
6 # The format of this file is one of 'key value' lines.
7 # Lines containing only whitespace at the beginning and then a # are ignored
8 # as comments. But comments can NOT be put on lines with data.
9 #***************************************************************************
10
11 # This is an example of a 'profile' file which includes a base file and adds
12 # some customizaton for a particular purpose.
13
14 # If this file is found in the user's ~/.ipython directory as ipythonrc-scipy,
15 # it can be loaded by calling passing the '-profile scipy' (or '-p scipy')
16 # option to IPython.
17
18 # This example is meant to load several modules to turn ipython into a very
19 # capable environment for high-end numerical work, similar to IDL or MatLab
20 # but with the beauty of the Python language.
21
22 # load our basic configuration with generic options
23 include ipythonrc
24
25 # import ...
26 # Load SciPy by itself so that 'help scipy' works
27 import_mod scipy
28
29 # from ... import ...
30 import_some
31
32 # Now we load all of SciPy
33 # from ... import *
34 import_all scipy IPython.numutils
35
36 # code
37 execute print 'Welcome to the SciPy Scientific Computing Environment.'
38 execute scipy.alter_numeric()
39
40 # File with alternate printer system for Numeric Arrays.
41 # Files in the 'Extensions' directory will be found by IPython automatically
42 # (otherwise give the explicit path):
43 execfile Extensions/numeric_formats.py
@@ -0,0 +1,37 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 #***************************************************************************
3 #
4 # Configuration file for ipython -- ipythonrc format
5 #
6 # The format of this file is one of 'key value' lines.
7 # Lines containing only whitespace at the beginning and then a # are ignored
8 # as comments. But comments can NOT be put on lines with data.
9 #***************************************************************************
10
11 # If this file is found in the user's ~/.ipython directory as
12 # ipythonrc-tutorial, it can be loaded by calling passing the '-profile
13 # tutorial' (or '-p tutorial') option to IPython.
14
15 # This profile loads a special input line filter to allow typing lines which
16 # begin with '>>> ' or '... '. These two strings, if present at the start of
17 # the input line, are stripped. This allows for direct pasting of code from
18 # examples such as those available in the standard Python tutorial.
19
20 # First load basic user configuration
21 include ipythonrc
22
23 # import ...
24 # Module with alternate input syntax for pasting python input
25 import_mod IPython.Extensions.InterpreterPasteInput
26
27 # from ... import *
28 import_all
29
30 # from ... import ...
31 import_some
32
33 # code
34 execute
35
36 # Files to execute
37 execfile
@@ -0,0 +1,63 b''
1 # -*- coding: utf-8 -*-
2 """
3 IPython -- An enhanced Interactive Python
4
5 One of Python's nicest features is its interactive interpreter. This allows
6 very fast testing of ideas without the overhead of creating test files as is
7 typical in most programming languages. However, the interpreter supplied with
8 the standard Python distribution is fairly primitive (and IDLE isn't really
9 much better).
10
11 IPython tries to:
12
13 i - provide an efficient environment for interactive work in Python
14 programming. It tries to address what we see as shortcomings of the standard
15 Python prompt, and adds many features to make interactive work much more
16 efficient.
17
18 ii - offer a flexible framework so that it can be used as the base
19 environment for other projects and problems where Python can be the
20 underlying language. Specifically scientific environments like Mathematica,
21 IDL and Mathcad inspired its design, but similar ideas can be useful in many
22 fields. Python is a fabulous language for implementing this kind of system
23 (due to its dynamic and introspective features), and with suitable libraries
24 entire systems could be built leveraging Python's power.
25
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
27
28 IPython requires Python 2.2 or newer.
29
30 $Id: __init__.py 530 2005-03-02 07:11:15Z fperez $"""
31
32 #*****************************************************************************
33 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
34 #
35 # Distributed under the terms of the BSD License. The full license is in
36 # the file COPYING, distributed as part of this software.
37 #*****************************************************************************
38
39 # Enforce proper version requirements
40 import sys
41 if sys.version[0:3] < '2.2':
42 raise ImportError, 'Python Version 2.2 or above is required.'
43
44 # Define what gets imported with a 'from IPython import *'
45 __all__ = ['deep_reload','genutils','ultraTB','DPyGetOpt','Itpl','hooks',
46 'ConfigLoader','OutputTrap','Release','Struct','Shell']
47
48 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
49 # access to them via IPython.<name>
50 glob,loc = globals(),locals()
51 for name in __all__:
52 __import__(name,glob,loc,[])
53
54 # Release data
55 from IPython import Release # do it explicitly so pydoc can see it - pydoc bug
56 __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
57 ( Release.authors['Fernando'] + Release.authors['Janko'] + \
58 Release.authors['Nathan'] )
59 __license__ = Release.license
60 __version__ = Release.version
61
62 # Namespace cleanup
63 del name,glob,loc
This diff has been collapsed as it changes many lines, (504 lines changed) Show them Hide them
@@ -0,0 +1,504 b''
1 # -*- coding: utf-8 -*-
2 """Manage background (threaded) jobs conveniently from an interactive shell.
3
4 This module provides a BackgroundJobManager class. This is the main class
5 meant for public usage, it implements an object which can create and manage
6 new background jobs.
7
8 It also provides the actual job classes managed by these BackgroundJobManager
9 objects, see their docstrings below.
10
11
12 This system was inspired by discussions with B. Granger and the
13 BackgroundCommand class described in the book Python Scripting for
14 Computational Science, by H. P. Langtangen:
15
16 http://folk.uio.no/hpl/scripting
17
18 (although ultimately no code from this text was used, as IPython's system is a
19 separate implementation).
20
21 $Id: background_jobs.py 515 2005-02-15 07:41:41Z fperez $
22 """
23
24 #*****************************************************************************
25 # Copyright (C) 2005 Fernando Perez <fperez@colorado.edu>
26 #
27 # Distributed under the terms of the BSD License. The full license is in
28 # the file COPYING, distributed as part of this software.
29 #*****************************************************************************
30
31 from IPython import Release
32 __author__ = '%s <%s>' % Release.authors['Fernando']
33 __license__ = Release.license
34
35 # Code begins
36 import threading,sys
37
38 from IPython.ultraTB import AutoFormattedTB
39 from IPython.genutils import warn,error
40
41 # declares Python 2.2 compatibility symbols:
42 try:
43 basestring
44 except NameError:
45 import types
46 basestring = (types.StringType, types.UnicodeType)
47 True = 1==1
48 False = 1==0
49
50 class BackgroundJobManager:
51 """Class to manage a pool of backgrounded threaded jobs.
52
53 Below, we assume that 'jobs' is a BackgroundJobManager instance.
54
55 Usage summary (see the method docstrings for details):
56
57 jobs.new(...) -> start a new job
58
59 jobs() or jobs.status() -> print status summary of all jobs
60
61 jobs[N] -> returns job number N.
62
63 foo = jobs[N].result -> assign to variable foo the result of job N
64
65 jobs[N].traceback() -> print the traceback of dead job N
66
67 jobs.remove(N) -> remove (finished) job N
68
69 jobs.flush_finished() -> remove all finished jobs
70
71 As a convenience feature, BackgroundJobManager instances provide the
72 utility result and traceback methods which retrieve the corresponding
73 information from the jobs list:
74
75 jobs.result(N) <--> jobs[N].result
76 jobs.traceback(N) <--> jobs[N].traceback()
77
78 While this appears minor, it allows you to use tab completion
79 interactively on the job manager instance.
80
81 In interactive mode, IPython provides the magic fuction %bg for quick
82 creation of backgrounded expression-based jobs. Type bg? for details."""
83
84 def __init__(self):
85 # Lists for job management
86 self.jobs_run = []
87 self.jobs_comp = []
88 self.jobs_dead = []
89 # A dict of all jobs, so users can easily access any of them
90 self.jobs_all = {}
91 # For reporting
92 self._comp_report = []
93 self._dead_report = []
94 # Store status codes locally for fast lookups
95 self._s_created = BackgroundJobBase.stat_created_c
96 self._s_running = BackgroundJobBase.stat_running_c
97 self._s_completed = BackgroundJobBase.stat_completed_c
98 self._s_dead = BackgroundJobBase.stat_dead_c
99
100 def new(self,func_or_exp,*args,**kwargs):
101 """Add a new background job and start it in a separate thread.
102
103 There are two types of jobs which can be created:
104
105 1. Jobs based on expressions which can be passed to an eval() call.
106 The expression must be given as a string. For example:
107
108 job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
109
110 The given expression is passed to eval(), along with the optional
111 global/local dicts provided. If no dicts are given, they are
112 extracted automatically from the caller's frame.
113
114 A Python statement is NOT a valid eval() expression. Basically, you
115 can only use as an eval() argument something which can go on the right
116 of an '=' sign and be assigned to a variable.
117
118 For example,"print 'hello'" is not valid, but '2+3' is.
119
120 2. Jobs given a function object, optionally passing additional
121 positional arguments:
122
123 job_manager.new(myfunc,x,y)
124
125 The function is called with the given arguments.
126
127 If you need to pass keyword arguments to your function, you must
128 supply them as a dict named kw:
129
130 job_manager.new(myfunc,x,y,kw=dict(z=1))
131
132 The reason for this assymmetry is that the new() method needs to
133 maintain access to its own keywords, and this prevents name collisions
134 between arguments to new() and arguments to your own functions.
135
136 In both cases, the result is stored in the job.result field of the
137 background job object.
138
139
140 Notes and caveats:
141
142 1. All threads running share the same standard output. Thus, if your
143 background jobs generate output, it will come out on top of whatever
144 you are currently writing. For this reason, background jobs are best
145 used with silent functions which simply return their output.
146
147 2. Threads also all work within the same global namespace, and this
148 system does not lock interactive variables. So if you send job to the
149 background which operates on a mutable object for a long time, and
150 start modifying that same mutable object interactively (or in another
151 backgrounded job), all sorts of bizarre behaviour will occur.
152
153 3. If a background job is spending a lot of time inside a C extension
154 module which does not release the Python Global Interpreter Lock
155 (GIL), this will block the IPython prompt. This is simply because the
156 Python interpreter can only switch between threads at Python
157 bytecodes. While the execution is inside C code, the interpreter must
158 simply wait unless the extension module releases the GIL.
159
160 4. There is no way, due to limitations in the Python threads library,
161 to kill a thread once it has started."""
162
163 if callable(func_or_exp):
164 kw = kwargs.get('kw',{})
165 job = BackgroundJobFunc(func_or_exp,*args,**kw)
166 elif isinstance(func_or_exp,basestring):
167 if not args:
168 frame = sys._getframe(1)
169 glob, loc = frame.f_globals, frame.f_locals
170 elif len(args)==1:
171 glob = loc = args[0]
172 elif len(args)==2:
173 glob,loc = args
174 else:
175 raise ValueError,\
176 'Expression jobs take at most 2 args (globals,locals)'
177 job = BackgroundJobExpr(func_or_exp,glob,loc)
178 else:
179 raise
180 jkeys = self.jobs_all.keys()
181 if jkeys:
182 job.num = max(jkeys)+1
183 else:
184 job.num = 0
185 self.jobs_run.append(job)
186 self.jobs_all[job.num] = job
187 print 'Starting job # %s in a separate thread.' % job.num
188 job.start()
189 return job
190
191 def __getitem__(self,key):
192 return self.jobs_all[key]
193
194 def __call__(self):
195 """An alias to self.status(),
196
197 This allows you to simply call a job manager instance much like the
198 Unix jobs shell command."""
199
200 return self.status()
201
202 def _update_status(self):
203 """Update the status of the job lists.
204
205 This method moves finished jobs to one of two lists:
206 - self.jobs_comp: jobs which completed successfully
207 - self.jobs_dead: jobs which finished but died.
208
209 It also copies those jobs to corresponding _report lists. These lists
210 are used to report jobs completed/dead since the last update, and are
211 then cleared by the reporting function after each call."""
212
213 run,comp,dead = self._s_running,self._s_completed,self._s_dead
214 jobs_run = self.jobs_run
215 for num in range(len(jobs_run)):
216 job = jobs_run[num]
217 stat = job.stat_code
218 if stat == run:
219 continue
220 elif stat == comp:
221 self.jobs_comp.append(job)
222 self._comp_report.append(job)
223 jobs_run[num] = False
224 elif stat == dead:
225 self.jobs_dead.append(job)
226 self._dead_report.append(job)
227 jobs_run[num] = False
228 self.jobs_run = filter(None,self.jobs_run)
229
230 def _group_report(self,group,name):
231 """Report summary for a given job group.
232
233 Return True if the group had any elements."""
234
235 if group:
236 print '%s jobs:' % name
237 for job in group:
238 print '%s : %s' % (job.num,job)
239 print
240 return True
241
242 def _group_flush(self,group,name):
243 """Flush a given job group
244
245 Return True if the group had any elements."""
246
247 njobs = len(group)
248 if njobs:
249 plural = {1:''}.setdefault(njobs,'s')
250 print 'Flushing %s %s job%s.' % (njobs,name,plural)
251 group[:] = []
252 return True
253
254 def _status_new(self):
255 """Print the status of newly finished jobs.
256
257 Return True if any new jobs are reported.
258
259 This call resets its own state every time, so it only reports jobs
260 which have finished since the last time it was called."""
261
262 self._update_status()
263 new_comp = self._group_report(self._comp_report,'Completed')
264 new_dead = self._group_report(self._dead_report,
265 'Dead, call job.traceback() for details')
266 self._comp_report[:] = []
267 self._dead_report[:] = []
268 return new_comp or new_dead
269
270 def status(self,verbose=0):
271 """Print a status of all jobs currently being managed."""
272
273 self._update_status()
274 self._group_report(self.jobs_run,'Running')
275 self._group_report(self.jobs_comp,'Completed')
276 self._group_report(self.jobs_dead,'Dead')
277 # Also flush the report queues
278 self._comp_report[:] = []
279 self._dead_report[:] = []
280
281 def remove(self,num):
282 """Remove a finished (completed or dead) job."""
283
284 try:
285 job = self.jobs_all[num]
286 except KeyError:
287 error('Job #%s not found' % num)
288 else:
289 stat_code = job.stat_code
290 if stat_code == self._s_running:
291 error('Job #%s is still running, it can not be removed.' % num)
292 return
293 elif stat_code == self._s_completed:
294 self.jobs_comp.remove(job)
295 elif stat_code == self._s_dead:
296 self.jobs_dead.remove(job)
297
298 def flush_finished(self):
299 """Flush all jobs finished (completed and dead) from lists.
300
301 Running jobs are never flushed.
302
303 It first calls _status_new(), to update info. If any jobs have
304 completed since the last _status_new() call, the flush operation
305 aborts."""
306
307 if self._status_new():
308 error('New jobs completed since last '\
309 '_status_new(), aborting flush.')
310 return
311
312 # Remove the finished jobs from the master dict
313 jobs_all = self.jobs_all
314 for job in self.jobs_comp+self.jobs_dead:
315 del(jobs_all[job.num])
316
317 # Now flush these lists completely
318 fl_comp = self._group_flush(self.jobs_comp,'Completed')
319 fl_dead = self._group_flush(self.jobs_dead,'Dead')
320 if not (fl_comp or fl_dead):
321 print 'No jobs to flush.'
322
323 def result(self,num):
324 """result(N) -> return the result of job N."""
325 try:
326 return self.jobs_all[num].result
327 except KeyError:
328 error('Job #%s not found' % num)
329
330 def traceback(self,num):
331 try:
332 self.jobs_all[num].traceback()
333 except KeyError:
334 error('Job #%s not found' % num)
335
336
337 class BackgroundJobBase(threading.Thread):
338 """Base class to build BackgroundJob classes.
339
340 The derived classes must implement:
341
342 - Their own __init__, since the one here raises NotImplementedError. The
343 derived constructor must call self._init() at the end, to provide common
344 initialization.
345
346 - A strform attribute used in calls to __str__.
347
348 - A call() method, which will make the actual execution call and must
349 return a value to be held in the 'result' field of the job object."""
350
351 # Class constants for status, in string and as numerical codes (when
352 # updating jobs lists, we don't want to do string comparisons). This will
353 # be done at every user prompt, so it has to be as fast as possible
354 stat_created = 'Created'; stat_created_c = 0
355 stat_running = 'Running'; stat_running_c = 1
356 stat_completed = 'Completed'; stat_completed_c = 2
357 stat_dead = 'Dead (Exception), call job.traceback() for details'
358 stat_dead_c = -1
359
360 def __init__(self):
361 raise NotImplementedError, \
362 "This class can not be instantiated directly."
363
364 def _init(self):
365 """Common initialization for all BackgroundJob objects"""
366
367 for attr in ['call','strform']:
368 assert hasattr(self,attr), "Missing attribute <%s>" % attr
369
370 # The num tag can be set by an external job manager
371 self.num = None
372
373 self.status = BackgroundJobBase.stat_created
374 self.stat_code = BackgroundJobBase.stat_created_c
375 self.finished = False
376 self.result = '<BackgroundJob has not completed>'
377 # reuse the ipython traceback handler if we can get to it, otherwise
378 # make a new one
379 try:
380 self._make_tb = __IPYTHON__.InteractiveTB.text
381 except:
382 self._make_tb = AutoFormattedTB(mode = 'Context',
383 color_scheme='NoColor',
384 tb_offset = 1).text
385 # Hold a formatted traceback if one is generated.
386 self._tb = None
387
388 threading.Thread.__init__(self)
389
390 def __str__(self):
391 return self.strform
392
393 def __repr__(self):
394 return '<BackgroundJob: %s>' % self.strform
395
396 def traceback(self):
397 print self._tb
398
399 def run(self):
400 try:
401 self.status = BackgroundJobBase.stat_running
402 self.stat_code = BackgroundJobBase.stat_running_c
403 self.result = self.call()
404 except:
405 self.status = BackgroundJobBase.stat_dead
406 self.stat_code = BackgroundJobBase.stat_dead_c
407 self.finished = None
408 self.result = ('<BackgroundJob died, call job.traceback() for details>')
409 self._tb = self._make_tb()
410 else:
411 self.status = BackgroundJobBase.stat_completed
412 self.stat_code = BackgroundJobBase.stat_completed_c
413 self.finished = True
414
415 class BackgroundJobExpr(BackgroundJobBase):
416 """Evaluate an expression as a background job (uses a separate thread)."""
417
418 def __init__(self,expression,glob=None,loc=None):
419 """Create a new job from a string which can be fed to eval().
420
421 global/locals dicts can be provided, which will be passed to the eval
422 call."""
423
424 # fail immediately if the given expression can't be compiled
425 self.code = compile(expression,'<BackgroundJob compilation>','eval')
426
427 if glob is None:
428 glob = {}
429 if loc is None:
430 loc = {}
431
432 self.expression = self.strform = expression
433 self.glob = glob
434 self.loc = loc
435 self._init()
436
437 def call(self):
438 return eval(self.code,self.glob,self.loc)
439
440 class BackgroundJobFunc(BackgroundJobBase):
441 """Run a function call as a background job (uses a separate thread)."""
442
443 def __init__(self,func,*args,**kwargs):
444 """Create a new job from a callable object.
445
446 Any positional arguments and keyword args given to this constructor
447 after the initial callable are passed directly to it."""
448
449 assert callable(func),'first argument must be callable'
450
451 if args is None:
452 args = []
453 if kwargs is None:
454 kwargs = {}
455
456 self.func = func
457 self.args = args
458 self.kwargs = kwargs
459 # The string form will only include the function passed, because
460 # generating string representations of the arguments is a potentially
461 # _very_ expensive operation (e.g. with large arrays).
462 self.strform = str(func)
463 self._init()
464
465 def call(self):
466 return self.func(*self.args,**self.kwargs)
467
468
469 if __name__=='__main__':
470
471 import time
472
473 def sleepfunc(interval=2,*a,**kw):
474 args = dict(interval=interval,
475 args=a,
476 kwargs=kw)
477 time.sleep(interval)
478 return args
479
480 def diefunc(interval=2,*a,**kw):
481 time.sleep(interval)
482 die
483
484 def printfunc(interval=1,reps=5):
485 for n in range(reps):
486 time.sleep(interval)
487 print 'In the background...'
488
489 jobs = BackgroundJobManager()
490 # first job will have # 0
491 jobs.new(sleepfunc,4)
492 jobs.new(sleepfunc,kw={'reps':2})
493 # This makes a job which will die
494 jobs.new(diefunc,1)
495 jobs.new('printfunc(1,3)')
496
497 # after a while, you can get the traceback of a dead job. Run the line
498 # below again interactively until it prints a traceback (check the status
499 # of the job):
500 print jobs[1].status
501 jobs[1].traceback()
502
503 # Run this line again until the printed result changes
504 print "The result of job #0 is:",jobs[0].result
@@ -0,0 +1,184 b''
1 # -*- coding: utf-8 -*-
2 """
3 A module to change reload() so that it acts recursively.
4 To enable it type:
5 >>> import __builtin__, deep_reload
6 >>> __builtin__.reload = deep_reload.reload
7 You can then disable it with:
8 >>> __builtin__.reload = deep_reload.original_reload
9
10 Alternatively, you can add a dreload builtin alongside normal reload with:
11 >>> __builtin__.dreload = deep_reload.reload
12
13 This code is almost entirely based on knee.py from the standard library.
14
15 $Id: deep_reload.py 410 2004-11-04 07:58:17Z fperez $"""
16
17 #*****************************************************************************
18 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
19 #
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
22 #*****************************************************************************
23
24 from IPython import Release # do it explicitly so pydoc can see it - pydoc bug
25 __author__ = '%s <%s>' % Release.authors['Nathan']
26 __license__ = Release.license
27 __version__ = "0.5"
28 __date__ = "21 August 2001"
29
30 import sys, imp, __builtin__
31
32 # Replacement for __import__()
33 def deep_import_hook(name, globals=None, locals=None, fromlist=None):
34 parent = determine_parent(globals)
35 q, tail = find_head_package(parent, name)
36 m = load_tail(q, tail)
37 if not fromlist:
38 return q
39 if hasattr(m, "__path__"):
40 ensure_fromlist(m, fromlist)
41 return m
42
43 def determine_parent(globals):
44 if not globals or not globals.has_key("__name__"):
45 return None
46 pname = globals['__name__']
47 if globals.has_key("__path__"):
48 parent = sys.modules[pname]
49 assert globals is parent.__dict__
50 return parent
51 if '.' in pname:
52 i = pname.rfind('.')
53 pname = pname[:i]
54 parent = sys.modules[pname]
55 assert parent.__name__ == pname
56 return parent
57 return None
58
59 def find_head_package(parent, name):
60 # Import the first
61 if '.' in name:
62 # 'some.nested.package' -> head = 'some', tail = 'nested.package'
63 i = name.find('.')
64 head = name[:i]
65 tail = name[i+1:]
66 else:
67 # 'packagename' -> head = 'packagename', tail = ''
68 head = name
69 tail = ""
70 if parent:
71 # If this is a subpackage then qname = parent's name + head
72 qname = "%s.%s" % (parent.__name__, head)
73 else:
74 qname = head
75 q = import_module(head, qname, parent)
76 if q: return q, tail
77 if parent:
78 qname = head
79 parent = None
80 q = import_module(head, qname, parent)
81 if q: return q, tail
82 raise ImportError, "No module named " + qname
83
84 def load_tail(q, tail):
85 m = q
86 while tail:
87 i = tail.find('.')
88 if i < 0: i = len(tail)
89 head, tail = tail[:i], tail[i+1:]
90
91 # fperez: fix dotted.name reloading failures by changing:
92 #mname = "%s.%s" % (m.__name__, head)
93 # to:
94 mname = m.__name__
95 # This needs more testing!!! (I don't understand this module too well)
96
97 #print '** head,tail=|%s|->|%s|, mname=|%s|' % (head,tail,mname) # dbg
98 m = import_module(head, mname, m)
99 if not m:
100 raise ImportError, "No module named " + mname
101 return m
102
103 def ensure_fromlist(m, fromlist, recursive=0):
104 for sub in fromlist:
105 if sub == "*":
106 if not recursive:
107 try:
108 all = m.__all__
109 except AttributeError:
110 pass
111 else:
112 ensure_fromlist(m, all, 1)
113 continue
114 if sub != "*" and not hasattr(m, sub):
115 subname = "%s.%s" % (m.__name__, sub)
116 submod = import_module(sub, subname, m)
117 if not submod:
118 raise ImportError, "No module named " + subname
119
120 # Need to keep track of what we've already reloaded to prevent cyclic evil
121 found_now = {}
122
123 def import_module(partname, fqname, parent):
124 global found_now
125 if found_now.has_key(fqname):
126 try:
127 return sys.modules[fqname]
128 except KeyError:
129 pass
130
131 print 'Reloading', fqname #, sys.excepthook is sys.__excepthook__, \
132 #sys.displayhook is sys.__displayhook__
133
134 found_now[fqname] = 1
135 try:
136 fp, pathname, stuff = imp.find_module(partname,
137 parent and parent.__path__)
138 except ImportError:
139 return None
140
141 try:
142 m = imp.load_module(fqname, fp, pathname, stuff)
143 finally:
144 if fp: fp.close()
145
146 if parent:
147 setattr(parent, partname, m)
148
149 return m
150
151 def deep_reload_hook(module):
152 name = module.__name__
153 if '.' not in name:
154 return import_module(name, name, None)
155 i = name.rfind('.')
156 pname = name[:i]
157 parent = sys.modules[pname]
158 return import_module(name[i+1:], name, parent)
159
160 # Save the original hooks
161 original_reload = __builtin__.reload
162
163 # Replacement for reload()
164 def reload(module, exclude=['sys', '__builtin__', '__main__']):
165 """Recursively reload all modules used in the given module. Optionally
166 takes a list of modules to exclude from reloading. The default exclude
167 list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
168 display, exception, and io hooks.
169 """
170 global found_now
171 for i in exclude:
172 found_now[i] = 1
173 original_import = __builtin__.__import__
174 __builtin__.__import__ = deep_import_hook
175 try:
176 ret = deep_reload_hook(module)
177 finally:
178 __builtin__.__import__ = original_import
179 found_now = {}
180 return ret
181
182 # Uncomment the following to automatically activate deep reloading whenever
183 # this module is imported
184 #__builtin__.reload = reload
This diff has been collapsed as it changes many lines, (1519 lines changed) Show them Hide them
@@ -0,0 +1,1519 b''
1 # -*- coding: utf-8 -*-
2 """
3 General purpose utilities.
4
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.
7
8 $Id: genutils.py 543 2005-03-18 09:23:48Z fperez $"""
9
10 #*****************************************************************************
11 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
16
17 from IPython import Release
18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __license__ = Release.license
20
21 #****************************************************************************
22 # required modules
23 import __main__
24 import types,commands,time,sys,os,re,shutil
25 import tempfile
26 from IPython.Itpl import Itpl,itpl,printpl
27 from IPython import DPyGetOpt
28
29 #****************************************************************************
30 # Exceptions
31 class Error(Exception):
32 """Base class for exceptions in this module."""
33 pass
34
35 #----------------------------------------------------------------------------
36 class Stream:
37 """Simple class to hold the various I/O streams in Term"""
38
39 def __init__(self,stream,name):
40 self.stream = stream
41 self.name = name
42 try:
43 self.fileno = stream.fileno()
44 except AttributeError:
45 msg = ("Stream <%s> looks suspicious: it lacks a 'fileno' attribute."
46 % name)
47 print >> sys.stderr, 'WARNING:',msg
48 try:
49 self.mode = stream.mode
50 except AttributeError:
51 msg = ("Stream <%s> looks suspicious: it lacks a 'mode' attribute."
52 % name)
53 print >> sys.stderr, 'WARNING:',msg
54
55 class Term:
56 """ Term holds the file or file-like objects for handling I/O operations.
57
58 These are normally just sys.stdin, sys.stdout and sys.stderr but for
59 Windows they can can replaced to allow editing the strings before they are
60 displayed."""
61
62 # In the future, having IPython channel all its I/O operations through
63 # this class will make it easier to embed it into other environments which
64 # are not a normal terminal (such as a GUI-based shell)
65 in_s = Stream(sys.stdin,'cin')
66 out_s = Stream(sys.stdout,'cout')
67 err_s = Stream(sys.stderr,'cerr')
68
69 # Store the three streams in (err,out,in) order so that if we need to reopen
70 # them, the error channel is reopened first to provide info.
71 streams = [err_s,out_s,in_s]
72
73 # The class globals should be the actual 'bare' streams for normal I/O to work
74 cin = streams[2].stream
75 cout = streams[1].stream
76 cerr = streams[0].stream
77
78 def reopen_all(cls):
79 """Reopen all streams if necessary.
80
81 This should only be called if it is suspected that someting closed
82 accidentally one of the I/O streams."""
83
84 any_closed = 0
85
86 for sn in range(len(cls.streams)):
87 st = cls.streams[sn]
88 if st.stream.closed:
89 any_closed = 1
90 new_stream = os.fdopen(os.dup(st.fileno), st.mode,0)
91 cls.streams[sn] = Stream(new_stream,st.name)
92 print >> cls.streams[0].stream, \
93 '\nWARNING:\nStream Term.%s had to be reopened!' % st.name
94
95 # Rebuild the class globals
96 cls.cin = cls.streams[2].stream
97 cls.cout = cls.streams[1].stream
98 cls.cerr = cls.streams[0].stream
99
100 reopen_all = classmethod(reopen_all)
101
102 def set_stdout(cls,stream):
103 """Set the stream """
104 cls.cout = stream
105 set_stdout = classmethod(set_stdout)
106
107 def set_stderr(cls,stream):
108 cls.cerr = stream
109 set_stderr = classmethod(set_stderr)
110
111 # Windows-specific code to load Gary Bishop's readline and configure it
112 # automatically for the users
113 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
114 # windows. Cygwin returns 'cygwin' for sys.platform.
115 if os.name == 'nt':
116 try:
117 import readline
118 except ImportError:
119 pass
120 else:
121 try:
122 _out = readline.GetOutputFile()
123 except AttributeError:
124 pass
125 else:
126 Term.set_stdout(_out)
127 Term.set_stderr(_out)
128 del _out
129
130 #****************************************************************************
131 # Generic warning/error printer, used by everything else
132 def warn(msg,level=2,exit_val=1):
133 """Standard warning printer. Gives formatting consistency.
134
135 Output is sent to Term.cerr (sys.stderr by default).
136
137 Options:
138
139 -level(2): allows finer control:
140 0 -> Do nothing, dummy function.
141 1 -> Print message.
142 2 -> Print 'WARNING:' + message. (Default level).
143 3 -> Print 'ERROR:' + message.
144 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
145
146 -exit_val (1): exit value returned by sys.exit() for a level 4
147 warning. Ignored for all other levels."""
148
149 if level>0:
150 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
151 print >> Term.cerr, '%s%s' % (header[level],msg)
152 if level == 4:
153 print >> Term.cerr,'Exiting.\n'
154 sys.exit(exit_val)
155
156 def info(msg):
157 """Equivalent to warn(msg,level=1)."""
158
159 warn(msg,level=1)
160
161 def error(msg):
162 """Equivalent to warn(msg,level=3)."""
163
164 warn(msg,level=3)
165
166 def fatal(msg,exit_val=1):
167 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
168
169 warn(msg,exit_val=exit_val,level=4)
170
171 #----------------------------------------------------------------------------
172 StringTypes = types.StringTypes
173
174 # Basic timing functionality
175
176 # If possible (Unix), use the resource module instead of time.clock()
177 try:
178 import resource
179 def clock():
180 """clock() -> floating point number
181
182 Return the CPU time in seconds (user time only, system time is
183 ignored) since the start of the process. This is done via a call to
184 resource.getrusage, so it avoids the wraparound problems in
185 time.clock()."""
186
187 return resource.getrusage(resource.RUSAGE_SELF)[0]
188
189 def clock2():
190 """clock2() -> (t_user,t_system)
191
192 Similar to clock(), but return a tuple of user/system times."""
193 return resource.getrusage(resource.RUSAGE_SELF)[:2]
194
195 except ImportError:
196 clock = time.clock
197 def clock2():
198 """Under windows, system CPU time can't be measured.
199
200 This just returns clock() and zero."""
201 return time.clock(),0.0
202
203 def timings_out(reps,func,*args,**kw):
204 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
205
206 Execute a function reps times, return a tuple with the elapsed total
207 CPU time in seconds, the time per call and the function's output.
208
209 Under Unix, the return value is the sum of user+system time consumed by
210 the process, computed via the resource module. This prevents problems
211 related to the wraparound effect which the time.clock() function has.
212
213 Under Windows the return value is in wall clock seconds. See the
214 documentation for the time module for more details."""
215
216 reps = int(reps)
217 assert reps >=1, 'reps must be >= 1'
218 if reps==1:
219 start = clock()
220 out = func(*args,**kw)
221 tot_time = clock()-start
222 else:
223 rng = xrange(reps-1) # the last time is executed separately to store output
224 start = clock()
225 for dummy in rng: func(*args,**kw)
226 out = func(*args,**kw) # one last time
227 tot_time = clock()-start
228 av_time = tot_time / reps
229 return tot_time,av_time,out
230
231 def timings(reps,func,*args,**kw):
232 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
233
234 Execute a function reps times, return a tuple with the elapsed total CPU
235 time in seconds and the time per call. These are just the first two values
236 in timings_out()."""
237
238 return timings_out(reps,func,*args,**kw)[0:2]
239
240 def timing(func,*args,**kw):
241 """timing(func,*args,**kw) -> t_total
242
243 Execute a function once, return the elapsed total CPU time in
244 seconds. This is just the first value in timings_out()."""
245
246 return timings_out(1,func,*args,**kw)[0]
247
248 #****************************************************************************
249 # file and system
250
251 def system(cmd,verbose=0,debug=0,header=''):
252 """Execute a system command, return its exit status.
253
254 Options:
255
256 - verbose (0): print the command to be executed.
257
258 - debug (0): only print, do not actually execute.
259
260 - header (''): Header to print on screen prior to the executed command (it
261 is only prepended to the command, no newlines are added).
262
263 Note: a stateful version of this function is available through the
264 SystemExec class."""
265
266 stat = 0
267 if verbose or debug: print header+cmd
268 sys.stdout.flush()
269 if not debug: stat = os.system(cmd)
270 return stat
271
272 def shell(cmd,verbose=0,debug=0,header=''):
273 """Execute a command in the system shell, always return None.
274
275 Options:
276
277 - verbose (0): print the command to be executed.
278
279 - debug (0): only print, do not actually execute.
280
281 - header (''): Header to print on screen prior to the executed command (it
282 is only prepended to the command, no newlines are added).
283
284 Note: this is similar to genutils.system(), but it returns None so it can
285 be conveniently used in interactive loops without getting the return value
286 (typically 0) printed many times."""
287
288 stat = 0
289 if verbose or debug: print header+cmd
290 # flush stdout so we don't mangle python's buffering
291 sys.stdout.flush()
292 if not debug:
293 os.system(cmd)
294
295 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
296 """Dummy substitute for perl's backquotes.
297
298 Executes a command and returns the output.
299
300 Accepts the same arguments as system(), plus:
301
302 - split(0): if true, the output is returned as a list split on newlines.
303
304 Note: a stateful version of this function is available through the
305 SystemExec class."""
306
307 if verbose or debug: print header+cmd
308 if not debug:
309 output = commands.getoutput(cmd)
310 if split:
311 return output.split('\n')
312 else:
313 return output
314
315 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
316 """Return (standard output,standard error) of executing cmd in a shell.
317
318 Accepts the same arguments as system(), plus:
319
320 - split(0): if true, each of stdout/err is returned as a list split on
321 newlines.
322
323 Note: a stateful version of this function is available through the
324 SystemExec class."""
325
326 if verbose or debug: print header+cmd
327 if not cmd:
328 if split:
329 return [],[]
330 else:
331 return '',''
332 if not debug:
333 pin,pout,perr = os.popen3(cmd)
334 tout = pout.read().rstrip()
335 terr = perr.read().rstrip()
336 pin.close()
337 pout.close()
338 perr.close()
339 if split:
340 return tout.split('\n'),terr.split('\n')
341 else:
342 return tout,terr
343
344 # for compatibility with older naming conventions
345 xsys = system
346 bq = getoutput
347
348 class SystemExec:
349 """Access the system and getoutput functions through a stateful interface.
350
351 Note: here we refer to the system and getoutput functions from this
352 library, not the ones from the standard python library.
353
354 This class offers the system and getoutput functions as methods, but the
355 verbose, debug and header parameters can be set for the instance (at
356 creation time or later) so that they don't need to be specified on each
357 call.
358
359 For efficiency reasons, there's no way to override the parameters on a
360 per-call basis other than by setting instance attributes. If you need
361 local overrides, it's best to directly call system() or getoutput().
362
363 The following names are provided as alternate options:
364 - xsys: alias to system
365 - bq: alias to getoutput
366
367 An instance can then be created as:
368 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
369
370 And used as:
371 >>> sysexec.xsys('pwd')
372 >>> dirlist = sysexec.bq('ls -l')
373 """
374
375 def __init__(self,verbose=0,debug=0,header='',split=0):
376 """Specify the instance's values for verbose, debug and header."""
377 setattr_list(self,'verbose debug header split')
378
379 def system(self,cmd):
380 """Stateful interface to system(), with the same keyword parameters."""
381
382 system(cmd,self.verbose,self.debug,self.header)
383
384 def shell(self,cmd):
385 """Stateful interface to shell(), with the same keyword parameters."""
386
387 shell(cmd,self.verbose,self.debug,self.header)
388
389 xsys = system # alias
390
391 def getoutput(self,cmd):
392 """Stateful interface to getoutput()."""
393
394 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
395
396 def getoutputerror(self,cmd):
397 """Stateful interface to getoutputerror()."""
398
399 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
400
401 bq = getoutput # alias
402
403 #-----------------------------------------------------------------------------
404 def mutex_opts(dict,ex_op):
405 """Check for presence of mutually exclusive keys in a dict.
406
407 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
408 for op1,op2 in ex_op:
409 if op1 in dict and op2 in dict:
410 raise ValueError,'\n*** ERROR in Arguments *** '\
411 'Options '+op1+' and '+op2+' are mutually exclusive.'
412
413 #-----------------------------------------------------------------------------
414 def filefind(fname,alt_dirs = None):
415 """Return the given filename either in the current directory, if it
416 exists, or in a specified list of directories.
417
418 ~ expansion is done on all file and directory names.
419
420 Upon an unsuccessful search, raise an IOError exception."""
421
422 if alt_dirs is None:
423 try:
424 alt_dirs = get_home_dir()
425 except HomeDirError:
426 alt_dirs = os.getcwd()
427 search = [fname] + list_strings(alt_dirs)
428 search = map(os.path.expanduser,search)
429 #print 'search list for',fname,'list:',search # dbg
430 fname = search[0]
431 if os.path.isfile(fname):
432 return fname
433 for direc in search[1:]:
434 testname = os.path.join(direc,fname)
435 #print 'testname',testname # dbg
436 if os.path.isfile(testname):
437 return testname
438 raise IOError,'File' + `fname` + \
439 ' not found in current or supplied directories:' + `alt_dirs`
440
441 #----------------------------------------------------------------------------
442 def target_outdated(target,deps):
443 """Determine whether a target is out of date.
444
445 target_outdated(target,deps) -> 1/0
446
447 deps: list of filenames which MUST exist.
448 target: single filename which may or may not exist.
449
450 If target doesn't exist or is older than any file listed in deps, return
451 true, otherwise return false.
452 """
453 try:
454 target_time = os.path.getmtime(target)
455 except os.error:
456 return 1
457 for dep in deps:
458 dep_time = os.path.getmtime(dep)
459 if dep_time > target_time:
460 #print "For target",target,"Dep failed:",dep # dbg
461 #print "times (dep,tar):",dep_time,target_time # dbg
462 return 1
463 return 0
464
465 #-----------------------------------------------------------------------------
466 def target_update(target,deps,cmd):
467 """Update a target with a given command given a list of dependencies.
468
469 target_update(target,deps,cmd) -> runs cmd if target is outdated.
470
471 This is just a wrapper around target_outdated() which calls the given
472 command if target is outdated."""
473
474 if target_outdated(target,deps):
475 xsys(cmd)
476
477 #----------------------------------------------------------------------------
478 def unquote_ends(istr):
479 """Remove a single pair of quotes from the endpoints of a string."""
480
481 if not istr:
482 return istr
483 if (istr[0]=="'" and istr[-1]=="'") or \
484 (istr[0]=='"' and istr[-1]=='"'):
485 return istr[1:-1]
486 else:
487 return istr
488
489 #----------------------------------------------------------------------------
490 def process_cmdline(argv,names=[],defaults={},usage=''):
491 """ Process command-line options and arguments.
492
493 Arguments:
494
495 - argv: list of arguments, typically sys.argv.
496
497 - names: list of option names. See DPyGetOpt docs for details on options
498 syntax.
499
500 - defaults: dict of default values.
501
502 - usage: optional usage notice to print if a wrong argument is passed.
503
504 Return a dict of options and a list of free arguments."""
505
506 getopt = DPyGetOpt.DPyGetOpt()
507 getopt.setIgnoreCase(0)
508 getopt.parseConfiguration(names)
509
510 try:
511 getopt.processArguments(argv)
512 except:
513 print usage
514 warn(`sys.exc_value`,level=4)
515
516 defaults.update(getopt.optionValues)
517 args = getopt.freeValues
518
519 return defaults,args
520
521 #----------------------------------------------------------------------------
522 def optstr2types(ostr):
523 """Convert a string of option names to a dict of type mappings.
524
525 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
526
527 This is used to get the types of all the options in a string formatted
528 with the conventions of DPyGetOpt. The 'type' None is used for options
529 which are strings (they need no further conversion). This function's main
530 use is to get a typemap for use with read_dict().
531 """
532
533 typeconv = {None:'',int:'',float:''}
534 typemap = {'s':None,'i':int,'f':float}
535 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
536
537 for w in ostr.split():
538 oname,alias,otype = opt_re.match(w).groups()
539 if otype == '' or alias == '!': # simple switches are integers too
540 otype = 'i'
541 typeconv[typemap[otype]] += oname + ' '
542 return typeconv
543
544 #----------------------------------------------------------------------------
545 def read_dict(filename,type_conv=None,**opt):
546
547 """Read a dictionary of key=value pairs from an input file, optionally
548 performing conversions on the resulting values.
549
550 read_dict(filename,type_conv,**opt) -> dict
551
552 Only one value per line is accepted, the format should be
553 # optional comments are ignored
554 key value\n
555
556 Args:
557
558 - type_conv: A dictionary specifying which keys need to be converted to
559 which types. By default all keys are read as strings. This dictionary
560 should have as its keys valid conversion functions for strings
561 (int,long,float,complex, or your own). The value for each key
562 (converter) should be a whitespace separated string containing the names
563 of all the entries in the file to be converted using that function. For
564 keys to be left alone, use None as the conversion function (only needed
565 with purge=1, see below).
566
567 - opt: dictionary with extra options as below (default in parens)
568
569 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
570 of the dictionary to be returned. If purge is going to be used, the
571 set of keys to be left as strings also has to be explicitly specified
572 using the (non-existent) conversion function None.
573
574 fs(None): field separator. This is the key/value separator to be used
575 when parsing the file. The None default means any whitespace [behavior
576 of string.split()].
577
578 strip(0): if 1, strip string values of leading/trailinig whitespace.
579
580 warn(1): warning level if requested keys are not found in file.
581 - 0: silently ignore.
582 - 1: inform but proceed.
583 - 2: raise KeyError exception.
584
585 no_empty(0): if 1, remove keys with whitespace strings as a value.
586
587 unique([]): list of keys (or space separated string) which can't be
588 repeated. If one such key is found in the file, each new instance
589 overwrites the previous one. For keys not listed here, the behavior is
590 to make a list of all appearances.
591
592 Example:
593 If the input file test.ini has:
594 i 3
595 x 4.5
596 y 5.5
597 s hi ho
598 Then:
599
600 >>> type_conv={int:'i',float:'x',None:'s'}
601 >>> read_dict('test.ini')
602 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
603 >>> read_dict('test.ini',type_conv)
604 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
605 >>> read_dict('test.ini',type_conv,purge=1)
606 {'i': 3, 's': 'hi ho', 'x': 4.5}
607 """
608
609 # starting config
610 opt.setdefault('purge',0)
611 opt.setdefault('fs',None) # field sep defaults to any whitespace
612 opt.setdefault('strip',0)
613 opt.setdefault('warn',1)
614 opt.setdefault('no_empty',0)
615 opt.setdefault('unique','')
616 if type(opt['unique']) in StringTypes:
617 unique_keys = qw(opt['unique'])
618 elif type(opt['unique']) in (types.TupleType,types.ListType):
619 unique_keys = opt['unique']
620 else:
621 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
622
623 dict = {}
624 # first read in table of values as strings
625 file = open(filename,'r')
626 for line in file.readlines():
627 line = line.strip()
628 if len(line) and line[0]=='#': continue
629 if len(line)>0:
630 lsplit = line.split(opt['fs'],1)
631 try:
632 key,val = lsplit
633 except ValueError:
634 key,val = lsplit[0],''
635 key = key.strip()
636 if opt['strip']: val = val.strip()
637 if val == "''" or val == '""': val = ''
638 if opt['no_empty'] and (val=='' or val.isspace()):
639 continue
640 # if a key is found more than once in the file, build a list
641 # unless it's in the 'unique' list. In that case, last found in file
642 # takes precedence. User beware.
643 try:
644 if dict[key] and key in unique_keys:
645 dict[key] = val
646 elif type(dict[key]) is types.ListType:
647 dict[key].append(val)
648 else:
649 dict[key] = [dict[key],val]
650 except KeyError:
651 dict[key] = val
652 # purge if requested
653 if opt['purge']:
654 accepted_keys = qwflat(type_conv.values())
655 for key in dict.keys():
656 if key in accepted_keys: continue
657 del(dict[key])
658 # now convert if requested
659 if type_conv==None: return dict
660 conversions = type_conv.keys()
661 try: conversions.remove(None)
662 except: pass
663 for convert in conversions:
664 for val in qw(type_conv[convert]):
665 try:
666 dict[val] = convert(dict[val])
667 except KeyError,e:
668 if opt['warn'] == 0:
669 pass
670 elif opt['warn'] == 1:
671 print >>sys.stderr, 'Warning: key',val,\
672 'not found in file',filename
673 elif opt['warn'] == 2:
674 raise KeyError,e
675 else:
676 raise ValueError,'Warning level must be 0,1 or 2'
677
678 return dict
679
680 #----------------------------------------------------------------------------
681 def flag_calls(func):
682 """Wrap a function to detect and flag when it gets called.
683
684 This is a decorator which takes a function and wraps it in a function with
685 a 'called' attribute. wrapper.called is initialized to False.
686
687 The wrapper.called attribute is set to False right before each call to the
688 wrapped function, so if the call fails it remains False. After the call
689 completes, wrapper.called is set to True and the output is returned.
690
691 Testing for truth in wrapper.called allows you to determine if a call to
692 func() was attempted and succeeded."""
693
694 def wrapper(*args,**kw):
695 wrapper.called = False
696 out = func(*args,**kw)
697 wrapper.called = True
698 return out
699
700 wrapper.called = False
701 wrapper.__doc__ = func.__doc__
702 return wrapper
703
704 #----------------------------------------------------------------------------
705 class HomeDirError(Error):
706 pass
707
708 def get_home_dir():
709 """Return the closest possible equivalent to a 'home' directory.
710
711 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
712
713 Currently only Posix and NT are implemented, a HomeDirError exception is
714 raised for all other OSes. """ #'
715
716 try:
717 return os.environ['HOME']
718 except KeyError:
719 if os.name == 'posix':
720 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
721 elif os.name == 'nt':
722 # For some strange reason, win9x returns 'nt' for os.name.
723 try:
724 return os.path.join(os.environ['HOMEDRIVE'],os.environ['HOMEPATH'])
725 except:
726 try:
727 # Use the registry to get the 'My Documents' folder.
728 import _winreg as wreg
729 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
730 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
731 homedir = wreg.QueryValueEx(key,'Personal')[0]
732 key.Close()
733 return homedir
734 except:
735 return 'C:\\'
736 elif os.name == 'dos':
737 # Desperate, may do absurd things in classic MacOS. May work under DOS.
738 return 'C:\\'
739 else:
740 raise HomeDirError,'support for your operating system not implemented.'
741
742 #****************************************************************************
743 # strings and text
744
745 class LSString(str):
746 """String derivative with a special access attributes.
747
748 These are normal strings, but with the special attributes:
749
750 .l (or .list) : value as list (split on newlines).
751 .n (or .nlstr): original value (the string itself).
752 .s (or .spstr): value as whitespace-separated string.
753
754 Any values which require transformations are computed only once and
755 cached.
756
757 Such strings are very useful to efficiently interact with the shell, which
758 typically only understands whitespace-separated options for commands."""
759
760 def get_list(self):
761 try:
762 return self.__list
763 except AttributeError:
764 self.__list = self.split('\n')
765 return self.__list
766
767 l = list = property(get_list)
768
769 def get_spstr(self):
770 try:
771 return self.__spstr
772 except AttributeError:
773 self.__spstr = self.replace('\n',' ')
774 return self.__spstr
775
776 s = spstr = property(get_spstr)
777
778 def get_nlstr(self):
779 return self
780
781 n = nlstr = property(get_nlstr)
782
783 class SList(list):
784 """List derivative with a special access attributes.
785
786 These are normal lists, but with the special attributes:
787
788 .l (or .list) : value as list (the list itself).
789 .n (or .nlstr): value as a string, joined on newlines.
790 .s (or .spstr): value as a string, joined on spaces.
791
792 Any values which require transformations are computed only once and
793 cached."""
794
795 def get_list(self):
796 return self
797
798 l = list = property(get_list)
799
800 def get_spstr(self):
801 try:
802 return self.__spstr
803 except AttributeError:
804 self.__spstr = ' '.join(self)
805 return self.__spstr
806
807 s = spstr = property(get_spstr)
808
809 def get_nlstr(self):
810 try:
811 return self.__nlstr
812 except AttributeError:
813 self.__nlstr = '\n'.join(self)
814 return self.__nlstr
815
816 n = nlstr = property(get_nlstr)
817
818 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
819 """Take multiple lines of input.
820
821 A list with each line of input as a separate element is returned when a
822 termination string is entered (defaults to a single '.'). Input can also
823 terminate via EOF (^D in Unix, ^Z-RET in Windows).
824
825 Lines of input which end in \\ are joined into single entries (and a
826 secondary continuation prompt is issued as long as the user terminates
827 lines with \\). This allows entering very long strings which are still
828 meant to be treated as single entities.
829 """
830
831 try:
832 if header:
833 header += '\n'
834 lines = [raw_input(header + ps1)]
835 except EOFError:
836 return []
837 terminate = [terminate_str]
838 try:
839 while lines[-1:] != terminate:
840 new_line = raw_input(ps1)
841 while new_line.endswith('\\'):
842 new_line = new_line[:-1] + raw_input(ps2)
843 lines.append(new_line)
844
845 return lines[:-1] # don't return the termination command
846 except EOFError:
847 print
848 return lines
849
850 #----------------------------------------------------------------------------
851 def raw_input_ext(prompt='', ps2='... '):
852 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
853
854 line = raw_input(prompt)
855 while line.endswith('\\'):
856 line = line[:-1] + raw_input(ps2)
857 return line
858
859 #----------------------------------------------------------------------------
860 def ask_yes_no(prompt,default=None):
861 """Asks a question and returns an integer 1/0 (y/n) answer.
862
863 If default is given (one of 'y','n'), it is used if the user input is
864 empty. Otherwise the question is repeated until an answer is given.
865 If EOF occurs 20 times consecutively, the default answer is assumed,
866 or if there is no default, an exception is raised to prevent infinite
867 loops.
868
869 Valid answers are: y/yes/n/no (match is not case sensitive)."""
870
871 answers = {'y':1,'n':0,'yes':1,'no':0}
872 ans = None
873 eofs, max_eofs = 0, 20
874 while ans not in answers.keys():
875 try:
876 ans = raw_input(prompt+' ').lower()
877 if not ans: # response was an empty string
878 ans = default
879 eofs = 0
880 except (EOFError,KeyboardInterrupt):
881 eofs = eofs + 1
882 if eofs >= max_eofs:
883 if default in answers.keys():
884 ans = default
885 else:
886 raise
887
888 return answers[ans]
889
890 #----------------------------------------------------------------------------
891 class EvalDict:
892 """
893 Emulate a dict which evaluates its contents in the caller's frame.
894
895 Usage:
896 >>>number = 19
897 >>>text = "python"
898 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
899 """
900
901 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
902 # modified (shorter) version of:
903 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
904 # Skip Montanaro (skip@pobox.com).
905
906 def __getitem__(self, name):
907 frame = sys._getframe(1)
908 return eval(name, frame.f_globals, frame.f_locals)
909
910 EvalString = EvalDict # for backwards compatibility
911 #----------------------------------------------------------------------------
912 def qw(words,flat=0,sep=None,maxsplit=-1):
913 """Similar to Perl's qw() operator, but with some more options.
914
915 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
916
917 words can also be a list itself, and with flat=1, the output will be
918 recursively flattened. Examples:
919
920 >>> qw('1 2')
921 ['1', '2']
922 >>> qw(['a b','1 2',['m n','p q']])
923 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
924 >>> qw(['a b','1 2',['m n','p q']],flat=1)
925 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
926
927 if type(words) in StringTypes:
928 return [word.strip() for word in words.split(sep,maxsplit)
929 if word and not word.isspace() ]
930 if flat:
931 return flatten(map(qw,words,[1]*len(words)))
932 return map(qw,words)
933
934 #----------------------------------------------------------------------------
935 def qwflat(words,sep=None,maxsplit=-1):
936 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
937 return qw(words,1,sep,maxsplit)
938
939 #-----------------------------------------------------------------------------
940 def list_strings(arg):
941 """Always return a list of strings, given a string or list of strings
942 as input."""
943
944 if type(arg) in StringTypes: return [arg]
945 else: return arg
946
947 #----------------------------------------------------------------------------
948 def grep(pat,list,case=1):
949 """Simple minded grep-like function.
950 grep(pat,list) returns occurrences of pat in list, None on failure.
951
952 It only does simple string matching, with no support for regexps. Use the
953 option case=0 for case-insensitive matching."""
954
955 # This is pretty crude. At least it should implement copying only references
956 # to the original data in case it's big. Now it copies the data for output.
957 out=[]
958 if case:
959 for term in list:
960 if term.find(pat)>-1: out.append(term)
961 else:
962 lpat=pat.lower()
963 for term in list:
964 if term.lower().find(lpat)>-1: out.append(term)
965
966 if len(out): return out
967 else: return None
968
969 #----------------------------------------------------------------------------
970 def dgrep(pat,*opts):
971 """Return grep() on dir()+dir(__builtins__).
972
973 A very common use of grep() when working interactively."""
974
975 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
976
977 #----------------------------------------------------------------------------
978 def idgrep(pat):
979 """Case-insensitive dgrep()"""
980
981 return dgrep(pat,0)
982
983 #----------------------------------------------------------------------------
984 def igrep(pat,list):
985 """Synonym for case-insensitive grep."""
986
987 return grep(pat,list,case=0)
988
989 #----------------------------------------------------------------------------
990 def indent(str,nspaces=4,ntabs=0):
991 """Indent a string a given number of spaces or tabstops.
992
993 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
994 """
995 if str is None:
996 return
997 ind = '\t'*ntabs+' '*nspaces
998 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
999 if outstr.endswith(os.linesep+ind):
1000 return outstr[:-len(ind)]
1001 else:
1002 return outstr
1003
1004 #-----------------------------------------------------------------------------
1005 def native_line_ends(filename,backup=1):
1006 """Convert (in-place) a file to line-ends native to the current OS.
1007
1008 If the optional backup argument is given as false, no backup of the
1009 original file is left. """
1010
1011 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1012
1013 bak_filename = filename + backup_suffixes[os.name]
1014
1015 original = open(filename).read()
1016 shutil.copy2(filename,bak_filename)
1017 try:
1018 new = open(filename,'wb')
1019 new.write(os.linesep.join(original.splitlines()))
1020 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1021 new.close()
1022 except:
1023 os.rename(bak_filename,filename)
1024 if not backup:
1025 try:
1026 os.remove(bak_filename)
1027 except:
1028 pass
1029
1030 #----------------------------------------------------------------------------
1031 def get_pager_cmd(pager_cmd = None):
1032 """Return a pager command.
1033
1034 Makes some attempts at finding an OS-correct one."""
1035
1036 if os.name == 'posix':
1037 default_pager_cmd = 'less -r' # -r for color control sequences
1038 elif os.name in ['nt','dos']:
1039 default_pager_cmd = 'type'
1040
1041 if pager_cmd is None:
1042 try:
1043 pager_cmd = os.environ['PAGER']
1044 except:
1045 pager_cmd = default_pager_cmd
1046 return pager_cmd
1047
1048 #-----------------------------------------------------------------------------
1049 def get_pager_start(pager,start):
1050 """Return the string for paging files with an offset.
1051
1052 This is the '+N' argument which less and more (under Unix) accept.
1053 """
1054
1055 if pager in ['less','more']:
1056 if start:
1057 start_string = '+' + str(start)
1058 else:
1059 start_string = ''
1060 else:
1061 start_string = ''
1062 return start_string
1063
1064 #----------------------------------------------------------------------------
1065 def page_dumb(strng,start=0,screen_lines=25):
1066 """Very dumb 'pager' in Python, for when nothing else works.
1067
1068 Only moves forward, same interface as page(), except for pager_cmd and
1069 mode."""
1070
1071 out_ln = strng.splitlines()[start:]
1072 screens = chop(out_ln,screen_lines-1)
1073 if len(screens) == 1:
1074 print >>Term.cout, os.linesep.join(screens[0])
1075 else:
1076 for scr in screens[0:-1]:
1077 print >>Term.cout, os.linesep.join(scr)
1078 ans = raw_input('---Return to continue, q to quit--- ')
1079 if ans.lower().startswith('q'):
1080 return
1081 print >>Term.cout, os.linesep.join(screens[-1])
1082
1083 #----------------------------------------------------------------------------
1084 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1085 """Print a string, piping through a pager after a certain length.
1086
1087 The screen_lines parameter specifies the number of *usable* lines of your
1088 terminal screen (total lines minus lines you need to reserve to show other
1089 information).
1090
1091 If you set screen_lines to a number <=0, page() will try to auto-determine
1092 your screen size and will only use up to (screen_size+screen_lines) for
1093 printing, paging after that. That is, if you want auto-detection but need
1094 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1095 auto-detection without any lines reserved simply use screen_lines = 0.
1096
1097 If a string won't fit in the allowed lines, it is sent through the
1098 specified pager command. If none given, look for PAGER in the environment,
1099 and ultimately default to less.
1100
1101 If no system pager works, the string is sent through a 'dumb pager'
1102 written in python, very simplistic.
1103 """
1104
1105 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1106 TERM = os.environ.get('TERM','dumb')
1107 if TERM in ['dumb','emacs'] and os.name != 'nt':
1108 print strng
1109 return
1110 # chop off the topmost part of the string we don't want to see
1111 str_lines = strng.split(os.linesep)[start:]
1112 str_toprint = os.linesep.join(str_lines)
1113 num_newlines = len(str_lines)
1114 len_str = len(str_toprint)
1115
1116 # Dumb heuristics to guesstimate number of on-screen lines the string
1117 # takes. Very basic, but good enough for docstrings in reasonable
1118 # terminals. If someone later feels like refining it, it's not hard.
1119 numlines = max(num_newlines,int(len_str/80)+1)
1120
1121 screen_lines_def = 25 # default value if we can't auto-determine
1122
1123 # auto-determine screen size
1124 if screen_lines <= 0:
1125 if TERM=='xterm':
1126 try:
1127 import curses
1128 if hasattr(curses,'initscr'):
1129 use_curses = 1
1130 else:
1131 use_curses = 0
1132 except ImportError:
1133 use_curses = 0
1134 else:
1135 # curses causes problems on many terminals other than xterm.
1136 use_curses = 0
1137 if use_curses:
1138 scr = curses.initscr()
1139 screen_lines_real,screen_cols = scr.getmaxyx()
1140 curses.endwin()
1141 screen_lines += screen_lines_real
1142 #print '***Screen size:',screen_lines_real,'lines x',\
1143 #screen_cols,'columns.' # dbg
1144 else:
1145 screen_lines += screen_lines_def
1146
1147 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1148 if numlines <= screen_lines :
1149 #print '*** normal print' # dbg
1150 print >>Term.cout, str_toprint
1151 else:
1152 # Try to open pager and default to internal one if that fails.
1153 # All failure modes are tagged as 'retval=1', to match the return
1154 # value of a failed system command. If any intermediate attempt
1155 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1156 pager_cmd = get_pager_cmd(pager_cmd)
1157 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1158 if os.name == 'nt':
1159 if pager_cmd.startswith('type'):
1160 # The default WinXP 'type' command is failing on complex strings.
1161 retval = 1
1162 else:
1163 tmpname = tempfile.mktemp('.txt')
1164 tmpfile = file(tmpname,'wt')
1165 tmpfile.write(strng)
1166 tmpfile.close()
1167 cmd = "%s < %s" % (pager_cmd,tmpname)
1168 if os.system(cmd):
1169 retval = 1
1170 else:
1171 retval = None
1172 os.remove(tmpname)
1173 else:
1174 try:
1175 retval = None
1176 # if I use popen4, things hang. No idea why.
1177 #pager,shell_out = os.popen4(pager_cmd)
1178 pager = os.popen(pager_cmd,'w')
1179 pager.write(strng)
1180 pager.close()
1181 retval = pager.close() # success returns None
1182 except IOError,msg: # broken pipe when user quits
1183 if msg.args == (32,'Broken pipe'):
1184 retval = None
1185 else:
1186 retval = 1
1187 except OSError:
1188 # Other strange problems, sometimes seen in Win2k/cygwin
1189 retval = 1
1190 if retval is not None:
1191 page_dumb(strng,screen_lines=screen_lines)
1192
1193 #----------------------------------------------------------------------------
1194 def page_file(fname,start = 0, pager_cmd = None):
1195 """Page a file, using an optional pager command and starting line.
1196 """
1197
1198 pager_cmd = get_pager_cmd(pager_cmd)
1199 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1200
1201 try:
1202 if os.environ['TERM'] in ['emacs','dumb']:
1203 raise EnvironmentError
1204 xsys(pager_cmd + ' ' + fname)
1205 except:
1206 try:
1207 if start > 0:
1208 start -= 1
1209 page(open(fname).read(),start)
1210 except:
1211 print 'Unable to show file',`fname`
1212
1213 #----------------------------------------------------------------------------
1214 def snip_print(str,width = 75,print_full = 0,header = ''):
1215 """Print a string snipping the midsection to fit in width.
1216
1217 print_full: mode control:
1218 - 0: only snip long strings
1219 - 1: send to page() directly.
1220 - 2: snip long strings and ask for full length viewing with page()
1221 Return 1 if snipping was necessary, 0 otherwise."""
1222
1223 if print_full == 1:
1224 page(header+str)
1225 return 0
1226
1227 print header,
1228 if len(str) < width:
1229 print str
1230 snip = 0
1231 else:
1232 whalf = int((width -5)/2)
1233 print str[:whalf] + ' <...> ' + str[-whalf:]
1234 snip = 1
1235 if snip and print_full == 2:
1236 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1237 page(str)
1238 return snip
1239
1240 #****************************************************************************
1241 # lists, dicts and structures
1242
1243 def belong(candidates,checklist):
1244 """Check whether a list of items appear in a given list of options.
1245
1246 Returns a list of 1 and 0, one for each candidate given."""
1247
1248 return [x in checklist for x in candidates]
1249
1250 #----------------------------------------------------------------------------
1251 def uniq_stable(elems):
1252 """uniq_stable(elems) -> list
1253
1254 Return from an iterable, a list of all the unique elements in the input,
1255 but maintaining the order in which they first appear.
1256
1257 A naive solution to this problem which just makes a dictionary with the
1258 elements as keys fails to respect the stability condition, since
1259 dictionaries are unsorted by nature.
1260
1261 Note: All elements in the input must be valid dictionary keys for this
1262 routine to work, as it internally uses a dictionary for efficiency
1263 reasons."""
1264
1265 unique = []
1266 unique_dict = {}
1267 for nn in elems:
1268 if nn not in unique_dict:
1269 unique.append(nn)
1270 unique_dict[nn] = None
1271 return unique
1272
1273 #----------------------------------------------------------------------------
1274 class NLprinter:
1275 """Print an arbitrarily nested list, indicating index numbers.
1276
1277 An instance of this class called nlprint is available and callable as a
1278 function.
1279
1280 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1281 and using 'sep' to separate the index from the value. """
1282
1283 def __init__(self):
1284 self.depth = 0
1285
1286 def __call__(self,lst,pos='',**kw):
1287 """Prints the nested list numbering levels."""
1288 kw.setdefault('indent',' ')
1289 kw.setdefault('sep',': ')
1290 kw.setdefault('start',0)
1291 kw.setdefault('stop',len(lst))
1292 # we need to remove start and stop from kw so they don't propagate
1293 # into a recursive call for a nested list.
1294 start = kw['start']; del kw['start']
1295 stop = kw['stop']; del kw['stop']
1296 if self.depth == 0 and 'header' in kw.keys():
1297 print kw['header']
1298
1299 for idx in range(start,stop):
1300 elem = lst[idx]
1301 if type(elem)==type([]):
1302 self.depth += 1
1303 self.__call__(elem,itpl('$pos$idx,'),**kw)
1304 self.depth -= 1
1305 else:
1306 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1307
1308 nlprint = NLprinter()
1309 #----------------------------------------------------------------------------
1310 def all_belong(candidates,checklist):
1311 """Check whether a list of items ALL appear in a given list of options.
1312
1313 Returns a single 1 or 0 value."""
1314
1315 return 1-(0 in [x in checklist for x in candidates])
1316
1317 #----------------------------------------------------------------------------
1318 def sort_compare(lst1,lst2,inplace = 1):
1319 """Sort and compare two lists.
1320
1321 By default it does it in place, thus modifying the lists. Use inplace = 0
1322 to avoid that (at the cost of temporary copy creation)."""
1323 if not inplace:
1324 lst1 = lst1[:]
1325 lst2 = lst2[:]
1326 lst1.sort(); lst2.sort()
1327 return lst1 == lst2
1328
1329 #----------------------------------------------------------------------------
1330 def mkdict(**kwargs):
1331 """Return a dict from a keyword list.
1332
1333 It's just syntactic sugar for making ditcionary creation more convenient:
1334 # the standard way
1335 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1336 # a cleaner way
1337 >>>data = dict(red=1, green=2, blue=3)
1338
1339 If you need more than this, look at the Struct() class."""
1340
1341 return kwargs
1342
1343 #----------------------------------------------------------------------------
1344 def list2dict(lst):
1345 """Takes a list of (key,value) pairs and turns it into a dict."""
1346
1347 dic = {}
1348 for k,v in lst: dic[k] = v
1349 return dic
1350
1351 #----------------------------------------------------------------------------
1352 def list2dict2(lst,default=''):
1353 """Takes a list and turns it into a dict.
1354 Much slower than list2dict, but more versatile. This version can take
1355 lists with sublists of arbitrary length (including sclars)."""
1356
1357 dic = {}
1358 for elem in lst:
1359 if type(elem) in (types.ListType,types.TupleType):
1360 size = len(elem)
1361 if size == 0:
1362 pass
1363 elif size == 1:
1364 dic[elem] = default
1365 else:
1366 k,v = elem[0], elem[1:]
1367 if len(v) == 1: v = v[0]
1368 dic[k] = v
1369 else:
1370 dic[elem] = default
1371 return dic
1372
1373 #----------------------------------------------------------------------------
1374 def flatten(seq):
1375 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1376
1377 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1378
1379 # if the x=0 isn't made, a *global* variable x is left over after calling
1380 # this function, with the value of the last element in the return
1381 # list. This does seem like a bug big time to me.
1382
1383 # the problem is fixed with the x=0, which seems to force the creation of
1384 # a local name
1385
1386 x = 0
1387 return [x for subseq in seq for x in subseq]
1388
1389 #----------------------------------------------------------------------------
1390 def get_slice(seq,start=0,stop=None,step=1):
1391 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1392 if stop == None:
1393 stop = len(seq)
1394 item = lambda i: seq[i]
1395 return map(item,xrange(start,stop,step))
1396
1397 #----------------------------------------------------------------------------
1398 def chop(seq,size):
1399 """Chop a sequence into chunks of the given size."""
1400 chunk = lambda i: seq[i:i+size]
1401 return map(chunk,xrange(0,len(seq),size))
1402
1403 #----------------------------------------------------------------------------
1404 def with(object, **args):
1405 """Set multiple attributes for an object, similar to Pascal's with.
1406
1407 Example:
1408 with(jim,
1409 born = 1960,
1410 haircolour = 'Brown',
1411 eyecolour = 'Green')
1412
1413 Credit: Greg Ewing, in
1414 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1415
1416 object.__dict__.update(args)
1417
1418 #----------------------------------------------------------------------------
1419 def setattr_list(obj,alist,nspace = None):
1420 """Set a list of attributes for an object taken from a namespace.
1421
1422 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1423 alist with their values taken from nspace, which must be a dict (something
1424 like locals() will often do) If nspace isn't given, locals() of the
1425 *caller* is used, so in most cases you can omit it.
1426
1427 Note that alist can be given as a string, which will be automatically
1428 split into a list on whitespace. If given as a list, it must be a list of
1429 *strings* (the variable names themselves), not of variables."""
1430
1431 # this grabs the local variables from the *previous* call frame -- that is
1432 # the locals from the function that called setattr_list().
1433 # - snipped from weave.inline()
1434 if nspace is None:
1435 call_frame = sys._getframe().f_back
1436 nspace = call_frame.f_locals
1437
1438 if type(alist) in StringTypes:
1439 alist = alist.split()
1440 for attr in alist:
1441 val = eval(attr,nspace)
1442 setattr(obj,attr,val)
1443
1444 #----------------------------------------------------------------------------
1445 def getattr_list(obj,alist,*args):
1446 """getattr_list(obj,alist[, default]) -> attribute list.
1447
1448 Get a list of named attributes for an object. When a default argument is
1449 given, it is returned when the attribute doesn't exist; without it, an
1450 exception is raised in that case.
1451
1452 Note that alist can be given as a string, which will be automatically
1453 split into a list on whitespace. If given as a list, it must be a list of
1454 *strings* (the variable names themselves), not of variables."""
1455
1456 if type(alist) in StringTypes:
1457 alist = alist.split()
1458 if args:
1459 if len(args)==1:
1460 default = args[0]
1461 return map(lambda attr: getattr(obj,attr,default),alist)
1462 else:
1463 raise ValueError,'getattr_list() takes only one optional argument'
1464 else:
1465 return map(lambda attr: getattr(obj,attr),alist)
1466
1467 #----------------------------------------------------------------------------
1468 def map_method(method,object_list,*argseq,**kw):
1469 """map_method(method,object_list,*args,**kw) -> list
1470
1471 Return a list of the results of applying the methods to the items of the
1472 argument sequence(s). If more than one sequence is given, the method is
1473 called with an argument list consisting of the corresponding item of each
1474 sequence. All sequences must be of the same length.
1475
1476 Keyword arguments are passed verbatim to all objects called.
1477
1478 This is Python code, so it's not nearly as fast as the builtin map()."""
1479
1480 out_list = []
1481 idx = 0
1482 for object in object_list:
1483 try:
1484 handler = getattr(object, method)
1485 except AttributeError:
1486 out_list.append(None)
1487 else:
1488 if argseq:
1489 args = map(lambda lst:lst[idx],argseq)
1490 #print 'ob',object,'hand',handler,'ar',args # dbg
1491 out_list.append(handler(args,**kw))
1492 else:
1493 out_list.append(handler(**kw))
1494 idx += 1
1495 return out_list
1496
1497 #----------------------------------------------------------------------------
1498 # Proposed popitem() extension, written as a method
1499
1500 class NotGiven: pass
1501
1502 def popkey(dct,key,default=NotGiven):
1503 """Return dct[key] and delete dct[key].
1504
1505 If default is given, return it if dct[key] doesn't exist, otherwise raise
1506 KeyError. """
1507
1508 try:
1509 val = dct[key]
1510 except KeyError:
1511 if default is NotGiven:
1512 raise
1513 else:
1514 return default
1515 else:
1516 del dct[key]
1517 return val
1518 #*************************** end of file <genutils.py> **********************
1519
@@ -0,0 +1,72 b''
1 """hooks for IPython.
2
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
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
7 overridden by the user.
8
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
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
13
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
16 from within your ipythonrc configuration.
17
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
20
21 import os
22 def calljed(self,filename, linenum):
23 "My editor hook calls the jed editor directly."
24 print "Calling my own editor, jed ..."
25 os.system('jed +%d %s' % (linenum,filename))
26
27 You can then execute the following line of code to make it the new IPython
28 editor hook, after having imported 'myiphooks':
29
30 ip_set_hook('editor',myiphooks.calljed)
31
32 The ip_set_hook function is put by IPython into the builtin namespace, so it
33 is always available from all running code.
34
35 $Id: hooks.py 535 2005-03-02 08:42:25Z fperez $"""
36
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
43
44 from IPython import Release
45 __author__ = '%s <%s>' % Release.authors['Fernando']
46 __license__ = Release.license
47 __version__ = Release.version
48
49 import os
50
51 # List here all the default hooks. For now it's just the editor, but over
52 # time we'll move here all the public API for user-accessible things.
53 __all__ = ['editor']
54
55 def editor(self,filename, linenum):
56 """Open the default editor at the given filename and linenumber.
57
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
60 new editor hook, call ip_set_hook('editor',yourfunc)."""
61
62 # IPython configures a default editor at startup by reading $EDITOR from
63 # the environment, and falling back on vi (unix) or notepad (win32).
64 editor = self.rc.editor
65
66 # marker for at which line to open the file (for existing objects)
67 if linenum is None or editor=='notepad':
68 linemark = ''
69 else:
70 linemark = '+%d' % linenum
71 # Call the actual editor
72 os.system('%s %s %s' % (editor,linemark,filename))
This diff has been collapsed as it changes many lines, (2084 lines changed) Show them Hide them
@@ -0,0 +1,2084 b''
1 # -*- coding: utf-8 -*-
2 """
3 IPython -- An enhanced Interactive Python
4
5 Requires Python 2.1 or newer.
6
7 This file contains all the classes and helper functions specific to IPython.
8
9 $Id: iplib.py 602 2005-06-09 03:02:30Z fperez $
10 """
11
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
15 #
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, much of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 # nice to acknowledge credit where credit is due.
24 #*****************************************************************************
25
26 #****************************************************************************
27 # Modules and globals
28
29 from __future__ import generators # for 2.2 backwards-compatibility
30
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
35 __version__ = Release.version
36
37 # Python standard modules
38 import __main__
39 import __builtin__
40 import exceptions
41 import keyword
42 import new
43 import os, sys, shutil
44 import code, glob, types, re
45 import string, StringIO
46 import inspect, pydoc
47 import bdb, pdb
48 import UserList # don't subclass list so this works with Python2.1
49 from pprint import pprint, pformat
50 import cPickle as pickle
51 import traceback
52
53 # IPython's own modules
54 import IPython
55 from IPython import OInspect,PyColorize,ultraTB
56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
57 from IPython.Logger import Logger
58 from IPython.Magic import Magic,magic2python,shlex_split
59 from IPython.usage import cmd_line_usage,interactive_usage
60 from IPython.Struct import Struct
61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 from IPython.FakeModule import FakeModule
63 from IPython.background_jobs import BackgroundJobManager
64 from IPython.genutils import *
65
66 # Global pointer to the running
67
68 # store the builtin raw_input globally, and use this always, in case user code
69 # overwrites it (like wx.py.PyShell does)
70 raw_input_original = raw_input
71
72 # declares Python 2.2 compatibility symbols:
73 try:
74 enumerate
75 except NameError:
76 def enumerate(obj):
77 i = -1
78 for item in obj:
79 i += 1
80 yield i, item
81 #****************************************************************************
82 # Some utility function definitions
83
84 class Bunch: pass
85
86 def esc_quotes(strng):
87 """Return the input string with single and double quotes escaped out"""
88
89 return strng.replace('"','\\"').replace("'","\\'")
90
91 def import_fail_info(mod_name,fns=None):
92 """Inform load failure for a module."""
93
94 if fns == None:
95 warn("Loading of %s failed.\n" % (mod_name,))
96 else:
97 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
98
99 def qw_lol(indata):
100 """qw_lol('a b') -> [['a','b']],
101 otherwise it's just a call to qw().
102
103 We need this to make sure the modules_some keys *always* end up as a
104 list of lists."""
105
106 if type(indata) in StringTypes:
107 return [qw(indata)]
108 else:
109 return qw(indata)
110
111 def ipmagic(arg_s):
112 """Call a magic function by name.
113
114 Input: a string containing the name of the magic function to call and any
115 additional arguments to be passed to the magic.
116
117 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
118 prompt:
119
120 In[1]: %name -opt foo bar
121
122 To call a magic without arguments, simply use ipmagic('name').
123
124 This provides a proper Python function to call IPython's magics in any
125 valid Python code you can type at the interpreter, including loops and
126 compound statements. It is added by IPython to the Python builtin
127 namespace upon initialization."""
128
129 args = arg_s.split(' ',1)
130 magic_name = args[0]
131 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
132 magic_name = magic_name[1:]
133 try:
134 magic_args = args[1]
135 except IndexError:
136 magic_args = ''
137 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
138 if fn is None:
139 error("Magic function `%s` not found." % magic_name)
140 else:
141 magic_args = __IPYTHON__.var_expand(magic_args)
142 return fn(magic_args)
143
144 def ipalias(arg_s):
145 """Call an alias by name.
146
147 Input: a string containing the name of the alias to call and any
148 additional arguments to be passed to the magic.
149
150 ipalias('name -opt foo bar') is equivalent to typing at the ipython
151 prompt:
152
153 In[1]: name -opt foo bar
154
155 To call an alias without arguments, simply use ipalias('name').
156
157 This provides a proper Python function to call IPython's aliases in any
158 valid Python code you can type at the interpreter, including loops and
159 compound statements. It is added by IPython to the Python builtin
160 namespace upon initialization."""
161
162 args = arg_s.split(' ',1)
163 alias_name = args[0]
164 try:
165 alias_args = args[1]
166 except IndexError:
167 alias_args = ''
168 if alias_name in __IPYTHON__.alias_table:
169 __IPYTHON__.call_alias(alias_name,alias_args)
170 else:
171 error("Alias `%s` not found." % alias_name)
172
173 #-----------------------------------------------------------------------------
174 # Local use classes
175 try:
176 from IPython import FlexCompleter
177
178 class MagicCompleter(FlexCompleter.Completer):
179 """Extension of the completer class to work on %-prefixed lines."""
180
181 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
182 """MagicCompleter() -> completer
183
184 Return a completer object suitable for use by the readline library
185 via readline.set_completer().
186
187 Inputs:
188
189 - shell: a pointer to the ipython shell itself. This is needed
190 because this completer knows about magic functions, and those can
191 only be accessed via the ipython instance.
192
193 - namespace: an optional dict where completions are performed.
194
195 - The optional omit__names parameter sets the completer to omit the
196 'magic' names (__magicname__) for python objects unless the text
197 to be completed explicitly starts with one or more underscores.
198
199 - If alias_table is supplied, it should be a dictionary of aliases
200 to complete. """
201
202 FlexCompleter.Completer.__init__(self,namespace)
203 self.magic_prefix = shell.name+'.magic_'
204 self.magic_escape = shell.ESC_MAGIC
205 self.readline = FlexCompleter.readline
206 delims = self.readline.get_completer_delims()
207 delims = delims.replace(self.magic_escape,'')
208 self.readline.set_completer_delims(delims)
209 self.get_line_buffer = self.readline.get_line_buffer
210 self.omit__names = omit__names
211 self.merge_completions = shell.rc.readline_merge_completions
212
213 if alias_table is None:
214 alias_table = {}
215 self.alias_table = alias_table
216 # Regexp to split filenames with spaces in them
217 self.space_name_re = re.compile(r'([^\\] )')
218 # Hold a local ref. to glob.glob for speed
219 self.glob = glob.glob
220 # Special handling of backslashes needed in win32 platforms
221 if sys.platform == "win32":
222 self.clean_glob = self._clean_glob_win32
223 else:
224 self.clean_glob = self._clean_glob
225 self.matchers = [self.python_matches,
226 self.file_matches,
227 self.alias_matches,
228 self.python_func_kw_matches]
229
230 # Code contributed by Alex Schmolck, for ipython/emacs integration
231 def all_completions(self, text):
232 """Return all possible completions for the benefit of emacs."""
233
234 completions = []
235 try:
236 for i in xrange(sys.maxint):
237 res = self.complete(text, i)
238
239 if not res: break
240
241 completions.append(res)
242 #XXX workaround for ``notDefined.<tab>``
243 except NameError:
244 pass
245 return completions
246 # /end Alex Schmolck code.
247
248 def _clean_glob(self,text):
249 return self.glob("%s*" % text)
250
251 def _clean_glob_win32(self,text):
252 return [f.replace("\\","/")
253 for f in self.glob("%s*" % text)]
254
255 def file_matches(self, text):
256 """Match filneames, expanding ~USER type strings.
257
258 Most of the seemingly convoluted logic in this completer is an
259 attempt to handle filenames with spaces in them. And yet it's not
260 quite perfect, because Python's readline doesn't expose all of the
261 GNU readline details needed for this to be done correctly.
262
263 For a filename with a space in it, the printed completions will be
264 only the parts after what's already been typed (instead of the
265 full completions, as is normally done). I don't think with the
266 current (as of Python 2.3) Python readline it's possible to do
267 better."""
268
269 #print 'Completer->file_matches: <%s>' % text # dbg
270
271 # chars that require escaping with backslash - i.e. chars
272 # that readline treats incorrectly as delimiters, but we
273 # don't want to treat as delimiters in filename matching
274 # when escaped with backslash
275
276 protectables = ' ()[]{}'
277
278 def protect_filename(s):
279 return "".join([(ch in protectables and '\\' + ch or ch)
280 for ch in s])
281
282 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
283 open_quotes = 0 # track strings with open quotes
284 try:
285 lsplit = shlex_split(lbuf)[-1]
286 except ValueError:
287 # typically an unmatched ", or backslash without escaped char.
288 if lbuf.count('"')==1:
289 open_quotes = 1
290 lsplit = lbuf.split('"')[-1]
291 elif lbuf.count("'")==1:
292 open_quotes = 1
293 lsplit = lbuf.split("'")[-1]
294 else:
295 return None
296 except IndexError:
297 # tab pressed on empty line
298 lsplit = ""
299
300 if lsplit != protect_filename(lsplit):
301 # if protectables are found, do matching on the whole escaped
302 # name
303 has_protectables = 1
304 text0,text = text,lsplit
305 else:
306 has_protectables = 0
307 text = os.path.expanduser(text)
308
309 if text == "":
310 return [protect_filename(f) for f in self.glob("*")]
311
312 m0 = self.clean_glob(text.replace('\\',''))
313 if has_protectables:
314 # If we had protectables, we need to revert our changes to the
315 # beginning of filename so that we don't double-write the part
316 # of the filename we have so far
317 len_lsplit = len(lsplit)
318 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
319 else:
320 if open_quotes:
321 # if we have a string with an open quote, we don't need to
322 # protect the names at all (and we _shouldn't_, as it
323 # would cause bugs when the filesystem call is made).
324 matches = m0
325 else:
326 matches = [protect_filename(f) for f in m0]
327 if len(matches) == 1 and os.path.isdir(matches[0]):
328 # Takes care of links to directories also. Use '/'
329 # explicitly, even under Windows, so that name completions
330 # don't end up escaped.
331 matches[0] += '/'
332 return matches
333
334 def alias_matches(self, text):
335 """Match internal system aliases"""
336 #print 'Completer->alias_matches:',text # dbg
337 text = os.path.expanduser(text)
338 aliases = self.alias_table.keys()
339 if text == "":
340 return aliases
341 else:
342 return [alias for alias in aliases if alias.startswith(text)]
343
344 def python_matches(self,text):
345 """Match attributes or global python names"""
346 #print 'Completer->python_matches' # dbg
347 if "." in text:
348 try:
349 matches = self.attr_matches(text)
350 if text.endswith('.') and self.omit__names:
351 if self.omit__names == 1:
352 # true if txt is _not_ a __ name, false otherwise:
353 no__name = (lambda txt:
354 re.match(r'.*\.__.*?__',txt) is None)
355 else:
356 # true if txt is _not_ a _ name, false otherwise:
357 no__name = (lambda txt:
358 re.match(r'.*\._.*?',txt) is None)
359 matches = filter(no__name, matches)
360 except NameError:
361 # catches <undefined attributes>.<tab>
362 matches = []
363 else:
364 matches = self.global_matches(text)
365 # this is so completion finds magics when automagic is on:
366 if matches == [] and not text.startswith(os.sep):
367 matches = self.attr_matches(self.magic_prefix+text)
368 return matches
369
370 def _default_arguments(self, obj):
371 """Return the list of default arguments of obj if it is callable,
372 or empty list otherwise."""
373
374 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
375 # for classes, check for __init__,__new__
376 if inspect.isclass(obj):
377 obj = (getattr(obj,'__init__',None) or
378 getattr(obj,'__new__',None))
379 # for all others, check if they are __call__able
380 elif hasattr(obj, '__call__'):
381 obj = obj.__call__
382 # XXX: is there a way to handle the builtins ?
383 try:
384 args,_,_1,defaults = inspect.getargspec(obj)
385 if defaults:
386 return args[-len(defaults):]
387 except TypeError: pass
388 return []
389
390 def python_func_kw_matches(self,text):
391 """Match named parameters (kwargs) of the last open function"""
392
393 if "." in text: # a parameter cannot be dotted
394 return []
395 try: regexp = self.__funcParamsRegex
396 except AttributeError:
397 regexp = self.__funcParamsRegex = re.compile(r'''
398 '.*?' | # single quoted strings or
399 ".*?" | # double quoted strings or
400 \w+ | # identifier
401 \S # other characters
402 ''', re.VERBOSE | re.DOTALL)
403 # 1. find the nearest identifier that comes before an unclosed
404 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
405 tokens = regexp.findall(self.get_line_buffer())
406 tokens.reverse()
407 iterTokens = iter(tokens); openPar = 0
408 for token in iterTokens:
409 if token == ')':
410 openPar -= 1
411 elif token == '(':
412 openPar += 1
413 if openPar > 0:
414 # found the last unclosed parenthesis
415 break
416 else:
417 return []
418 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
419 ids = []
420 isId = re.compile(r'\w+$').match
421 while True:
422 try:
423 ids.append(iterTokens.next())
424 if not isId(ids[-1]):
425 ids.pop(); break
426 if not iterTokens.next() == '.':
427 break
428 except StopIteration:
429 break
430 # lookup the candidate callable matches either using global_matches
431 # or attr_matches for dotted names
432 if len(ids) == 1:
433 callableMatches = self.global_matches(ids[0])
434 else:
435 callableMatches = self.attr_matches('.'.join(ids[::-1]))
436 argMatches = []
437 for callableMatch in callableMatches:
438 try: namedArgs = self._default_arguments(eval(callableMatch,
439 self.namespace))
440 except: continue
441 for namedArg in namedArgs:
442 if namedArg.startswith(text):
443 argMatches.append("%s=" %namedArg)
444 return argMatches
445
446 def complete(self, text, state):
447 """Return the next possible completion for 'text'.
448
449 This is called successively with state == 0, 1, 2, ... until it
450 returns None. The completion should begin with 'text'. """
451
452 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
453 magic_escape = self.magic_escape
454 magic_prefix = self.magic_prefix
455
456 try:
457 if text.startswith(magic_escape):
458 text = text.replace(magic_escape,magic_prefix)
459 elif text.startswith('~'):
460 text = os.path.expanduser(text)
461 if state == 0:
462 # Extend the list of completions with the results of each
463 # matcher, so we return results to the user from all
464 # namespaces.
465 if self.merge_completions:
466 self.matches = []
467 for matcher in self.matchers:
468 self.matches.extend(matcher(text))
469 else:
470 for matcher in self.matchers:
471 self.matches = matcher(text)
472 if self.matches:
473 break
474
475 try:
476 return self.matches[state].replace(magic_prefix,magic_escape)
477 except IndexError:
478 return None
479 except:
480 # If completion fails, don't annoy the user.
481 pass
482
483 except ImportError:
484 pass # no readline support
485
486 except KeyError:
487 pass # Windows doesn't set TERM, it doesn't matter
488
489
490 class InputList(UserList.UserList):
491 """Class to store user input.
492
493 It's basically a list, but slices return a string instead of a list, thus
494 allowing things like (assuming 'In' is an instance):
495
496 exec In[4:7]
497
498 or
499
500 exec In[5:9] + In[14] + In[21:25]"""
501
502 def __getslice__(self,i,j):
503 return ''.join(UserList.UserList.__getslice__(self,i,j))
504
505 #****************************************************************************
506 # Local use exceptions
507 class SpaceInInput(exceptions.Exception):
508 pass
509
510 #****************************************************************************
511 # Main IPython class
512
513 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
514 """An enhanced console for Python."""
515
516 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
517 user_ns = None,banner2='',
518 custom_exceptions=((),None)):
519
520 # Put a reference to self in builtins so that any form of embedded or
521 # imported code can test for being inside IPython.
522 __builtin__.__IPYTHON__ = self
523
524 # And load into builtins ipmagic/ipalias as well
525 __builtin__.ipmagic = ipmagic
526 __builtin__.ipalias = ipalias
527
528 # Add to __builtin__ other parts of IPython's public API
529 __builtin__.ip_set_hook = self.set_hook
530
531 # Keep in the builtins a flag for when IPython is active. We set it
532 # with setdefault so that multiple nested IPythons don't clobber one
533 # another. Each will increase its value by one upon being activated,
534 # which also gives us a way to determine the nesting level.
535 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
536
537 # Inform the user of ipython's fast exit magics.
538 _exit = ' Use %Exit or %Quit to exit without confirmation.'
539 __builtin__.exit += _exit
540 __builtin__.quit += _exit
541
542 # Create the namespace where the user will operate:
543
544 # FIXME. For some strange reason, __builtins__ is showing up at user
545 # level as a dict instead of a module. This is a manual fix, but I
546 # should really track down where the problem is coming from. Alex
547 # Schmolck reported this problem first.
548
549 # A useful post by Alex Martelli on this topic:
550 # Re: inconsistent value from __builtins__
551 # Von: Alex Martelli <aleaxit@yahoo.com>
552 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
553 # Gruppen: comp.lang.python
554 # Referenzen: 1
555
556 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
557 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
558 # > <type 'dict'>
559 # > >>> print type(__builtins__)
560 # > <type 'module'>
561 # > Is this difference in return value intentional?
562
563 # Well, it's documented that '__builtins__' can be either a dictionary
564 # or a module, and it's been that way for a long time. Whether it's
565 # intentional (or sensible), I don't know. In any case, the idea is that
566 # if you need to access the built-in namespace directly, you should start
567 # with "import __builtin__" (note, no 's') which will definitely give you
568 # a module. Yeah, it's somewhat confusing:-(.
569
570 if user_ns is None:
571 # Set __name__ to __main__ to better match the behavior of the
572 # normal interpreter.
573 self.user_ns = {'__name__' :'__main__',
574 '__builtins__' : __builtin__,
575 }
576 else:
577 self.user_ns = user_ns
578
579 # The user namespace MUST have a pointer to the shell itself.
580 self.user_ns[name] = self
581
582 # We need to insert into sys.modules something that looks like a
583 # module but which accesses the IPython namespace, for shelve and
584 # pickle to work interactively. Normally they rely on getting
585 # everything out of __main__, but for embedding purposes each IPython
586 # instance has its own private namespace, so we can't go shoving
587 # everything into __main__.
588
589 try:
590 main_name = self.user_ns['__name__']
591 except KeyError:
592 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
593 else:
594 #print "pickle hack in place" # dbg
595 sys.modules[main_name] = FakeModule(self.user_ns)
596
597 # List of input with multi-line handling.
598 # Fill its zero entry, user counter starts at 1
599 self.input_hist = InputList(['\n'])
600
601 # list of visited directories
602 self.dir_hist = [os.getcwd()]
603
604 # dict of output history
605 self.output_hist = {}
606
607 # dict of names to be treated as system aliases. Each entry in the
608 # alias table must be a 2-tuple of the form (N,name), where N is the
609 # number of positional arguments of the alias.
610 self.alias_table = {}
611
612 # dict of things NOT to alias (keywords and builtins)
613 self.no_alias = {}
614 for key in keyword.kwlist:
615 self.no_alias[key] = 1
616 self.no_alias.update(__builtin__.__dict__)
617
618 # make global variables for user access to these
619 self.user_ns['_ih'] = self.input_hist
620 self.user_ns['_oh'] = self.output_hist
621 self.user_ns['_dh'] = self.dir_hist
622
623 # user aliases to input and output histories
624 self.user_ns['In'] = self.input_hist
625 self.user_ns['Out'] = self.output_hist
626
627 # Store the actual shell's name
628 self.name = name
629
630 # Object variable to store code object waiting execution. This is
631 # used mainly by the multithreaded shells, but it can come in handy in
632 # other situations. No need to use a Queue here, since it's a single
633 # item which gets cleared once run.
634 self.code_to_run = None
635 self.code_to_run_src = '' # corresponding source
636
637 # Job manager (for jobs run as background threads)
638 self.jobs = BackgroundJobManager()
639 # Put the job manager into builtins so it's always there.
640 __builtin__.jobs = self.jobs
641
642 # escapes for automatic behavior on the command line
643 self.ESC_SHELL = '!'
644 self.ESC_HELP = '?'
645 self.ESC_MAGIC = '%'
646 self.ESC_QUOTE = ','
647 self.ESC_QUOTE2 = ';'
648 self.ESC_PAREN = '/'
649
650 # And their associated handlers
651 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
652 self.ESC_QUOTE:self.handle_auto,
653 self.ESC_QUOTE2:self.handle_auto,
654 self.ESC_MAGIC:self.handle_magic,
655 self.ESC_HELP:self.handle_help,
656 self.ESC_SHELL:self.handle_shell_escape,
657 }
658
659 # class initializations
660 code.InteractiveConsole.__init__(self,locals = self.user_ns)
661 Logger.__init__(self,log_ns = self.user_ns)
662 Magic.__init__(self,self)
663
664 # an ugly hack to get a pointer to the shell, so I can start writing
665 # magic code via this pointer instead of the current mixin salad.
666 Magic.set_shell(self,self)
667
668 # hooks holds pointers used for user-side customizations
669 self.hooks = Struct()
670
671 # Set all default hooks, defined in the IPython.hooks module.
672 hooks = IPython.hooks
673 for hook_name in hooks.__all__:
674 self.set_hook(hook_name,getattr(hooks,hook_name))
675
676 # Flag to mark unconditional exit
677 self.exit_now = False
678
679 self.usage_min = """\
680 An enhanced console for Python.
681 Some of its features are:
682 - Readline support if the readline library is present.
683 - Tab completion in the local namespace.
684 - Logging of input, see command-line options.
685 - System shell escape via ! , eg !ls.
686 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
687 - Keeps track of locally defined variables via %who, %whos.
688 - Show object information with a ? eg ?x or x? (use ?? for more info).
689 """
690 if usage: self.usage = usage
691 else: self.usage = self.usage_min
692
693 # Storage
694 self.rc = rc # This will hold all configuration information
695 self.inputcache = []
696 self._boundcache = []
697 self.pager = 'less'
698 # temporary files used for various purposes. Deleted at exit.
699 self.tempfiles = []
700
701 # for pushd/popd management
702 try:
703 self.home_dir = get_home_dir()
704 except HomeDirError,msg:
705 fatal(msg)
706
707 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
708
709 # Functions to call the underlying shell.
710
711 # utility to expand user variables via Itpl
712 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
713 self.user_ns))
714 # The first is similar to os.system, but it doesn't return a value,
715 # and it allows interpolation of variables in the user's namespace.
716 self.system = lambda cmd: shell(self.var_expand(cmd),
717 header='IPython system call: ',
718 verbose=self.rc.system_verbose)
719 # These are for getoutput and getoutputerror:
720 self.getoutput = lambda cmd: \
721 getoutput(self.var_expand(cmd),
722 header='IPython system call: ',
723 verbose=self.rc.system_verbose)
724 self.getoutputerror = lambda cmd: \
725 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
726 self.user_ns)),
727 header='IPython system call: ',
728 verbose=self.rc.system_verbose)
729
730 # RegExp for splitting line contents into pre-char//first
731 # word-method//rest. For clarity, each group in on one line.
732
733 # WARNING: update the regexp if the above escapes are changed, as they
734 # are hardwired in.
735
736 # Don't get carried away with trying to make the autocalling catch too
737 # much: it's better to be conservative rather than to trigger hidden
738 # evals() somewhere and end up causing side effects.
739
740 self.line_split = re.compile(r'^([\s*,;/])'
741 r'([\?\w\.]+\w*\s*)'
742 r'(\(?.*$)')
743
744 # Original re, keep around for a while in case changes break something
745 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
746 # r'(\s*[\?\w\.]+\w*\s*)'
747 # r'(\(?.*$)')
748
749 # RegExp to identify potential function names
750 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
751 # RegExp to exclude strings with this start from autocalling
752 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
753 # try to catch also methods for stuff in lists/tuples/dicts: off
754 # (experimental). For this to work, the line_split regexp would need
755 # to be modified so it wouldn't break things at '['. That line is
756 # nasty enough that I shouldn't change it until I can test it _well_.
757 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
758
759 # keep track of where we started running (mainly for crash post-mortem)
760 self.starting_dir = os.getcwd()
761
762 # Attributes for Logger mixin class, make defaults here
763 self._dolog = 0
764 self.LOG = ''
765 self.LOGDEF = '.InteractiveShell.log'
766 self.LOGMODE = 'over'
767 self.LOGHEAD = Itpl(
768 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
769 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
770 #log# opts = $self.rc.opts
771 #log# args = $self.rc.args
772 #log# It is safe to make manual edits below here.
773 #log#-----------------------------------------------------------------------
774 """)
775 # Various switches which can be set
776 self.CACHELENGTH = 5000 # this is cheap, it's just text
777 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
778 self.banner2 = banner2
779
780 # TraceBack handlers:
781 # Need two, one for syntax errors and one for other exceptions.
782 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
783 # This one is initialized with an offset, meaning we always want to
784 # remove the topmost item in the traceback, which is our own internal
785 # code. Valid modes: ['Plain','Context','Verbose']
786 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
787 color_scheme='NoColor',
788 tb_offset = 1)
789 # and add any custom exception handlers the user may have specified
790 self.set_custom_exc(*custom_exceptions)
791
792 # Object inspector
793 ins_colors = OInspect.InspectColors
794 code_colors = PyColorize.ANSICodeColors
795 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
796 self.autoindent = 0
797
798 # Make some aliases automatically
799 # Prepare list of shell aliases to auto-define
800 if os.name == 'posix':
801 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
802 'mv mv -i','rm rm -i','cp cp -i',
803 'cat cat','less less','clear clear',
804 # a better ls
805 'ls ls -F',
806 # long ls
807 'll ls -lF',
808 # color ls
809 'lc ls -F -o --color',
810 # ls normal files only
811 'lf ls -F -o --color %l | grep ^-',
812 # ls symbolic links
813 'lk ls -F -o --color %l | grep ^l',
814 # directories or links to directories,
815 'ldir ls -F -o --color %l | grep /$',
816 # things which are executable
817 'lx ls -F -o --color %l | grep ^-..x',
818 )
819 elif os.name in ['nt','dos']:
820 auto_alias = ('dir dir /on', 'ls dir /on',
821 'ddir dir /ad /on', 'ldir dir /ad /on',
822 'mkdir mkdir','rmdir rmdir','echo echo',
823 'ren ren','cls cls','copy copy')
824 else:
825 auto_alias = ()
826 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
827 # Call the actual (public) initializer
828 self.init_auto_alias()
829 # end __init__
830
831 def set_hook(self,name,hook):
832 """set_hook(name,hook) -> sets an internal IPython hook.
833
834 IPython exposes some of its internal API as user-modifiable hooks. By
835 resetting one of these hooks, you can modify IPython's behavior to
836 call at runtime your own routines."""
837
838 # At some point in the future, this should validate the hook before it
839 # accepts it. Probably at least check that the hook takes the number
840 # of args it's supposed to.
841 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
842
843 def set_custom_exc(self,exc_tuple,handler):
844 """set_custom_exc(exc_tuple,handler)
845
846 Set a custom exception handler, which will be called if any of the
847 exceptions in exc_tuple occur in the mainloop (specifically, in the
848 runcode() method.
849
850 Inputs:
851
852 - exc_tuple: a *tuple* of valid exceptions to call the defined
853 handler for. It is very important that you use a tuple, and NOT A
854 LIST here, because of the way Python's except statement works. If
855 you only want to trap a single exception, use a singleton tuple:
856
857 exc_tuple == (MyCustomException,)
858
859 - handler: this must be defined as a function with the following
860 basic interface: def my_handler(self,etype,value,tb).
861
862 This will be made into an instance method (via new.instancemethod)
863 of IPython itself, and it will be called if any of the exceptions
864 listed in the exc_tuple are caught. If the handler is None, an
865 internal basic one is used, which just prints basic info.
866
867 WARNING: by putting in your own exception handler into IPython's main
868 execution loop, you run a very good chance of nasty crashes. This
869 facility should only be used if you really know what you are doing."""
870
871 assert type(exc_tuple)==type(()) , \
872 "The custom exceptions must be given AS A TUPLE."
873
874 def dummy_handler(self,etype,value,tb):
875 print '*** Simple custom exception handler ***'
876 print 'Exception type :',etype
877 print 'Exception value:',value
878 print 'Traceback :',tb
879 print 'Source code :',self.code_to_run_src
880
881 if handler is None: handler = dummy_handler
882
883 self.CustomTB = new.instancemethod(handler,self,self.__class__)
884 self.custom_exceptions = exc_tuple
885
886 def set_custom_completer(self,completer,pos=0):
887 """set_custom_completer(completer,pos=0)
888
889 Adds a new custom completer function.
890
891 The position argument (defaults to 0) is the index in the completers
892 list where you want the completer to be inserted."""
893
894 newcomp = new.instancemethod(completer,self.Completer,
895 self.Completer.__class__)
896 self.Completer.matchers.insert(pos,newcomp)
897
898 def post_config_initialization(self):
899 """Post configuration init method
900
901 This is called after the configuration files have been processed to
902 'finalize' the initialization."""
903
904 # dynamic data that survives through sessions
905 # XXX make the filename a config option?
906 persist_base = 'persist'
907 if self.rc.profile:
908 persist_base += '_%s' % self.rc.profile
909 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
910
911 try:
912 self.persist = pickle.load(file(self.persist_fname))
913 except:
914 self.persist = {}
915
916 def init_auto_alias(self):
917 """Define some aliases automatically.
918
919 These are ALL parameter-less aliases"""
920 for alias,cmd in self.auto_alias:
921 self.alias_table[alias] = (0,cmd)
922
923 def alias_table_validate(self,verbose=0):
924 """Update information about the alias table.
925
926 In particular, make sure no Python keywords/builtins are in it."""
927
928 no_alias = self.no_alias
929 for k in self.alias_table.keys():
930 if k in no_alias:
931 del self.alias_table[k]
932 if verbose:
933 print ("Deleting alias <%s>, it's a Python "
934 "keyword or builtin." % k)
935
936 def set_autoindent(self,value=None):
937 """Set the autoindent flag, checking for readline support.
938
939 If called with no arguments, it acts as a toggle."""
940
941 if not self.has_readline:
942 if os.name == 'posix':
943 warn("The auto-indent feature requires the readline library")
944 self.autoindent = 0
945 return
946 if value is None:
947 self.autoindent = not self.autoindent
948 else:
949 self.autoindent = value
950
951 def rc_set_toggle(self,rc_field,value=None):
952 """Set or toggle a field in IPython's rc config. structure.
953
954 If called with no arguments, it acts as a toggle.
955
956 If called with a non-existent field, the resulting AttributeError
957 exception will propagate out."""
958
959 rc_val = getattr(self.rc,rc_field)
960 if value is None:
961 value = not rc_val
962 setattr(self.rc,rc_field,value)
963
964 def user_setup(self,ipythondir,rc_suffix,mode='install'):
965 """Install the user configuration directory.
966
967 Can be called when running for the first time or to upgrade the user's
968 .ipython/ directory with the mode parameter. Valid modes are 'install'
969 and 'upgrade'."""
970
971 def wait():
972 try:
973 raw_input("Please press <RETURN> to start IPython.")
974 except EOFError:
975 print >> Term.cout
976 print '*'*70
977
978 cwd = os.getcwd() # remember where we started
979 glb = glob.glob
980 print '*'*70
981 if mode == 'install':
982 print \
983 """Welcome to IPython. I will try to create a personal configuration directory
984 where you can customize many aspects of IPython's functionality in:\n"""
985 else:
986 print 'I am going to upgrade your configuration in:'
987
988 print ipythondir
989
990 rcdirend = os.path.join('IPython','UserConfig')
991 cfg = lambda d: os.path.join(d,rcdirend)
992 try:
993 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
994 except IOError:
995 warning = """
996 Installation error. IPython's directory was not found.
997
998 Check the following:
999
1000 The ipython/IPython directory should be in a directory belonging to your
1001 PYTHONPATH environment variable (that is, it should be in a directory
1002 belonging to sys.path). You can copy it explicitly there or just link to it.
1003
1004 IPython will proceed with builtin defaults.
1005 """
1006 warn(warning)
1007 wait()
1008 return
1009
1010 if mode == 'install':
1011 try:
1012 shutil.copytree(rcdir,ipythondir)
1013 os.chdir(ipythondir)
1014 rc_files = glb("ipythonrc*")
1015 for rc_file in rc_files:
1016 os.rename(rc_file,rc_file+rc_suffix)
1017 except:
1018 warning = """
1019
1020 There was a problem with the installation:
1021 %s
1022 Try to correct it or contact the developers if you think it's a bug.
1023 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1024 warn(warning)
1025 wait()
1026 return
1027
1028 elif mode == 'upgrade':
1029 try:
1030 os.chdir(ipythondir)
1031 except:
1032 print """
1033 Can not upgrade: changing to directory %s failed. Details:
1034 %s
1035 """ % (ipythondir,sys.exc_info()[1])
1036 wait()
1037 return
1038 else:
1039 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1040 for new_full_path in sources:
1041 new_filename = os.path.basename(new_full_path)
1042 if new_filename.startswith('ipythonrc'):
1043 new_filename = new_filename + rc_suffix
1044 # The config directory should only contain files, skip any
1045 # directories which may be there (like CVS)
1046 if os.path.isdir(new_full_path):
1047 continue
1048 if os.path.exists(new_filename):
1049 old_file = new_filename+'.old'
1050 if os.path.exists(old_file):
1051 os.remove(old_file)
1052 os.rename(new_filename,old_file)
1053 shutil.copy(new_full_path,new_filename)
1054 else:
1055 raise ValueError,'unrecognized mode for install:',`mode`
1056
1057 # Fix line-endings to those native to each platform in the config
1058 # directory.
1059 try:
1060 os.chdir(ipythondir)
1061 except:
1062 print """
1063 Problem: changing to directory %s failed.
1064 Details:
1065 %s
1066
1067 Some configuration files may have incorrect line endings. This should not
1068 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1069 wait()
1070 else:
1071 for fname in glb('ipythonrc*'):
1072 try:
1073 native_line_ends(fname,backup=0)
1074 except IOError:
1075 pass
1076
1077 if mode == 'install':
1078 print """
1079 Successful installation!
1080
1081 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1082 IPython manual (there are both HTML and PDF versions supplied with the
1083 distribution) to make sure that your system environment is properly configured
1084 to take advantage of IPython's features."""
1085 else:
1086 print """
1087 Successful upgrade!
1088
1089 All files in your directory:
1090 %(ipythondir)s
1091 which would have been overwritten by the upgrade were backed up with a .old
1092 extension. If you had made particular customizations in those files you may
1093 want to merge them back into the new files.""" % locals()
1094 wait()
1095 os.chdir(cwd)
1096 # end user_setup()
1097
1098 def atexit_operations(self):
1099 """This will be executed at the time of exit.
1100
1101 Saving of persistent data should be performed here. """
1102
1103 # input history
1104 self.savehist()
1105
1106 # Cleanup all tempfiles left around
1107 for tfile in self.tempfiles:
1108 try:
1109 os.unlink(tfile)
1110 except OSError:
1111 pass
1112
1113 # save the "persistent data" catch-all dictionary
1114 try:
1115 pickle.dump(self.persist, open(self.persist_fname,"w"))
1116 except:
1117 print "*** ERROR *** persistent data saving failed."
1118
1119 def savehist(self):
1120 """Save input history to a file (via readline library)."""
1121 try:
1122 self.readline.write_history_file(self.histfile)
1123 except:
1124 print 'Unable to save IPython command history to file: ' + \
1125 `self.histfile`
1126
1127 def pre_readline(self):
1128 """readline hook to be used at the start of each line.
1129
1130 Currently it handles auto-indent only."""
1131
1132 self.readline.insert_text(' '* self.readline_indent)
1133
1134 def init_readline(self):
1135 """Command history completion/saving/reloading."""
1136 try:
1137 import readline
1138 self.Completer = MagicCompleter(self,
1139 self.user_ns,
1140 self.rc.readline_omit__names,
1141 self.alias_table)
1142 except ImportError,NameError:
1143 # If FlexCompleter failed to import, MagicCompleter won't be
1144 # defined. This can happen because of a problem with readline
1145 self.has_readline = 0
1146 # no point in bugging windows users with this every time:
1147 if os.name == 'posix':
1148 warn('Readline services not available on this platform.')
1149 else:
1150 import atexit
1151
1152 # Platform-specific configuration
1153 if os.name == 'nt':
1154 # readline under Windows modifies the default exit behavior
1155 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1156 __builtin__.exit = __builtin__.quit = \
1157 ('Use Ctrl-D (i.e. EOF) to exit. '
1158 'Use %Exit or %Quit to exit without confirmation.')
1159 self.readline_startup_hook = readline.set_pre_input_hook
1160 else:
1161 self.readline_startup_hook = readline.set_startup_hook
1162
1163 # Load user's initrc file (readline config)
1164 inputrc_name = os.environ.get('INPUTRC')
1165 if inputrc_name is None:
1166 home_dir = get_home_dir()
1167 if home_dir is not None:
1168 inputrc_name = os.path.join(home_dir,'.inputrc')
1169 if os.path.isfile(inputrc_name):
1170 try:
1171 readline.read_init_file(inputrc_name)
1172 except:
1173 warn('Problems reading readline initialization file <%s>'
1174 % inputrc_name)
1175
1176 self.has_readline = 1
1177 self.readline = readline
1178 self.readline_indent = 0 # for auto-indenting via readline
1179 # save this in sys so embedded copies can restore it properly
1180 sys.ipcompleter = self.Completer.complete
1181 readline.set_completer(self.Completer.complete)
1182
1183 # Configure readline according to user's prefs
1184 for rlcommand in self.rc.readline_parse_and_bind:
1185 readline.parse_and_bind(rlcommand)
1186
1187 # remove some chars from the delimiters list
1188 delims = readline.get_completer_delims()
1189 delims = delims.translate(string._idmap,
1190 self.rc.readline_remove_delims)
1191 readline.set_completer_delims(delims)
1192 # otherwise we end up with a monster history after a while:
1193 readline.set_history_length(1000)
1194 try:
1195 #print '*** Reading readline history' # dbg
1196 readline.read_history_file(self.histfile)
1197 except IOError:
1198 pass # It doesn't exist yet.
1199
1200 atexit.register(self.atexit_operations)
1201 del atexit
1202
1203 # Configure auto-indent for all platforms
1204 self.set_autoindent(self.rc.autoindent)
1205
1206 def showsyntaxerror(self, filename=None):
1207 """Display the syntax error that just occurred.
1208
1209 This doesn't display a stack trace because there isn't one.
1210
1211 If a filename is given, it is stuffed in the exception instead
1212 of what was there before (because Python's parser always uses
1213 "<string>" when reading from a string).
1214 """
1215 type, value, sys.last_traceback = sys.exc_info()
1216 sys.last_type = type
1217 sys.last_value = value
1218 if filename and type is SyntaxError:
1219 # Work hard to stuff the correct filename in the exception
1220 try:
1221 msg, (dummy_filename, lineno, offset, line) = value
1222 except:
1223 # Not the format we expect; leave it alone
1224 pass
1225 else:
1226 # Stuff in the right filename
1227 try:
1228 # Assume SyntaxError is a class exception
1229 value = SyntaxError(msg, (filename, lineno, offset, line))
1230 except:
1231 # If that failed, assume SyntaxError is a string
1232 value = msg, (filename, lineno, offset, line)
1233 self.SyntaxTB(type,value,[])
1234
1235 def debugger(self):
1236 """Call the pdb debugger."""
1237
1238 if not self.rc.pdb:
1239 return
1240 pdb.pm()
1241
1242 def showtraceback(self,exc_tuple = None):
1243 """Display the exception that just occurred."""
1244
1245 # Though this won't be called by syntax errors in the input line,
1246 # there may be SyntaxError cases whith imported code.
1247 if exc_tuple is None:
1248 type, value, tb = sys.exc_info()
1249 else:
1250 type, value, tb = exc_tuple
1251 if type is SyntaxError:
1252 self.showsyntaxerror()
1253 else:
1254 sys.last_type = type
1255 sys.last_value = value
1256 sys.last_traceback = tb
1257 self.InteractiveTB()
1258 if self.InteractiveTB.call_pdb and self.has_readline:
1259 # pdb mucks up readline, fix it back
1260 self.readline.set_completer(self.Completer.complete)
1261
1262 def update_cache(self, line):
1263 """puts line into cache"""
1264 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1265 if len(self.inputcache) >= self.CACHELENGTH:
1266 self.inputcache.pop() # This not :-)
1267
1268 def name_space_init(self):
1269 """Create local namespace."""
1270 # We want this to be a method to facilitate embedded initialization.
1271 code.InteractiveConsole.__init__(self,self.user_ns)
1272
1273 def mainloop(self,banner=None):
1274 """Creates the local namespace and starts the mainloop.
1275
1276 If an optional banner argument is given, it will override the
1277 internally created default banner."""
1278
1279 self.name_space_init()
1280 if self.rc.c: # Emulate Python's -c option
1281 self.exec_init_cmd()
1282 if banner is None:
1283 if self.rc.banner:
1284 banner = self.BANNER+self.banner2
1285 else:
1286 banner = ''
1287 self.interact(banner)
1288
1289 def exec_init_cmd(self):
1290 """Execute a command given at the command line.
1291
1292 This emulates Python's -c option."""
1293
1294 sys.argv = ['-c']
1295 self.push(self.rc.c)
1296
1297 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1298 """Embeds IPython into a running python program.
1299
1300 Input:
1301
1302 - header: An optional header message can be specified.
1303
1304 - local_ns, global_ns: working namespaces. If given as None, the
1305 IPython-initialized one is updated with __main__.__dict__, so that
1306 program variables become visible but user-specific configuration
1307 remains possible.
1308
1309 - stack_depth: specifies how many levels in the stack to go to
1310 looking for namespaces (when local_ns and global_ns are None). This
1311 allows an intermediate caller to make sure that this function gets
1312 the namespace from the intended level in the stack. By default (0)
1313 it will get its locals and globals from the immediate caller.
1314
1315 Warning: it's possible to use this in a program which is being run by
1316 IPython itself (via %run), but some funny things will happen (a few
1317 globals get overwritten). In the future this will be cleaned up, as
1318 there is no fundamental reason why it can't work perfectly."""
1319
1320 # Patch for global embedding to make sure that things don't overwrite
1321 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1322 # FIXME. Test this a bit more carefully (the if.. is new)
1323 if local_ns is None and global_ns is None:
1324 self.user_ns.update(__main__.__dict__)
1325
1326 # Get locals and globals from caller
1327 if local_ns is None or global_ns is None:
1328 call_frame = sys._getframe(stack_depth).f_back
1329
1330 if local_ns is None:
1331 local_ns = call_frame.f_locals
1332 if global_ns is None:
1333 global_ns = call_frame.f_globals
1334
1335 # Update namespaces and fire up interpreter
1336 self.user_ns.update(local_ns)
1337 self.interact(header)
1338
1339 # Remove locals from namespace
1340 for k in local_ns.keys():
1341 del self.user_ns[k]
1342
1343 def interact(self, banner=None):
1344 """Closely emulate the interactive Python console.
1345
1346 The optional banner argument specify the banner to print
1347 before the first interaction; by default it prints a banner
1348 similar to the one printed by the real Python interpreter,
1349 followed by the current class name in parentheses (so as not
1350 to confuse this with the real interpreter -- since it's so
1351 close!).
1352
1353 """
1354 cprt = 'Type "copyright", "credits" or "license" for more information.'
1355 if banner is None:
1356 self.write("Python %s on %s\n%s\n(%s)\n" %
1357 (sys.version, sys.platform, cprt,
1358 self.__class__.__name__))
1359 else:
1360 self.write(banner)
1361
1362 more = 0
1363
1364 # Mark activity in the builtins
1365 __builtin__.__dict__['__IPYTHON__active'] += 1
1366 while 1:
1367 # This is set by a call to %Exit or %Quit
1368 if self.exit_now:
1369 break
1370 try:
1371 if more:
1372 prompt = self.outputcache.prompt2
1373 if self.autoindent:
1374 self.readline_startup_hook(self.pre_readline)
1375 else:
1376 prompt = self.outputcache.prompt1
1377 try:
1378 line = self.raw_input(prompt)
1379 if self.autoindent:
1380 self.readline_startup_hook(None)
1381 except EOFError:
1382 if self.autoindent:
1383 self.readline_startup_hook(None)
1384 self.write("\n")
1385 if self.rc.confirm_exit:
1386 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1387 break
1388 else:
1389 break
1390 else:
1391 more = self.push(line)
1392 # Auto-indent management
1393 if self.autoindent:
1394 if line:
1395 ini_spaces = re.match('^(\s+)',line)
1396 if ini_spaces:
1397 nspaces = ini_spaces.end()
1398 else:
1399 nspaces = 0
1400 self.readline_indent = nspaces
1401
1402 if line[-1] == ':':
1403 self.readline_indent += 4
1404 elif re.match(r'^\s+raise|^\s+return',line):
1405 self.readline_indent -= 4
1406 else:
1407 self.readline_indent = 0
1408
1409 except KeyboardInterrupt:
1410 self.write("\nKeyboardInterrupt\n")
1411 self.resetbuffer()
1412 more = 0
1413 # keep cache in sync with the prompt counter:
1414 self.outputcache.prompt_count -= 1
1415
1416 if self.autoindent:
1417 self.readline_indent = 0
1418
1419 except bdb.BdbQuit:
1420 warn("The Python debugger has exited with a BdbQuit exception.\n"
1421 "Because of how pdb handles the stack, it is impossible\n"
1422 "for IPython to properly format this particular exception.\n"
1423 "IPython will resume normal operation.")
1424 except:
1425 # We should never get here except in fairly bizarre situations
1426 # (or b/c of an IPython bug). One reasonable exception is if
1427 # the user sets stdin/out/err to a broken object (or closes
1428 # any of them!)
1429
1430 fixed_in_out_err = 0
1431
1432 # Call the Term I/O class and have it reopen any stream which
1433 # the user might have closed.
1434 Term.reopen_all()
1435
1436 # Do the same manually for sys.stderr/out/in
1437
1438 # err first, so we can print at least warnings
1439 if sys.__stderr__.closed:
1440 sys.__stderr__ = os.fdopen(os.dup(2),'w',0)
1441 fixed_err_err = 1
1442 print >> sys.__stderr__,"""
1443 WARNING:
1444 sys.__stderr__ was closed!
1445 I've tried to reopen it, but bear in mind that things may not work normally
1446 from now. In particular, readline support may have broken.
1447 """
1448 # Next, check stdin/out
1449 if sys.__stdin__.closed:
1450 sys.__stdin__ = os.fdopen(os.dup(0),'r',0)
1451 fixed_in_out_err = 1
1452 print >> sys.__stderr__,"""
1453 WARNING:
1454 sys.__stdin__ was closed!
1455 I've tried to reopen it, but bear in mind that things may not work normally
1456 from now. In particular, readline support may have broken.
1457 """
1458 if sys.__stdout__.closed:
1459 sys.__stdout__ = os.fdopen(os.dup(1),'w',0)
1460 fixed_in_out_err = 1
1461 print >> sys.__stderr__,"""
1462 WARNING:
1463 sys.__stdout__ was closed!
1464 I've tried to reopen it, but bear in mind that things may not work normally
1465 from now. In particular, readline support may have broken.
1466 """
1467
1468 # Now, check mismatch of objects
1469 if sys.stdin is not sys.__stdin__:
1470 sys.stdin = sys.__stdin__
1471 fixed_in_out_err = 1
1472 print >> sys.__stderr__,"""
1473 WARNING:
1474 sys.stdin has been reset to sys.__stdin__.
1475 There seemed to be a problem with your sys.stdin.
1476 """
1477 if sys.stdout is not sys.__stdout__:
1478 sys.stdout = sys.__stdout__
1479 fixed_in_out_err = 1
1480 print >> sys.__stderr__,"""
1481 WARNING:
1482 sys.stdout has been reset to sys.__stdout__.
1483 There seemed to be a problem with your sys.stdout.
1484 """
1485
1486 if sys.stderr is not sys.__stderr__:
1487 sys.stderr = sys.__stderr__
1488 fixed_in_out_err = 1
1489 print >> sys.__stderr__,"""
1490 WARNING:
1491 sys.stderr has been reset to sys.__stderr__.
1492 There seemed to be a problem with your sys.stderr.
1493 """
1494 # If the problem wasn't a broken out/err, it's an IPython bug
1495 # I wish we could ask the user whether to crash or not, but
1496 # calling any function at this point messes up the stack.
1497 if not fixed_in_out_err:
1498 raise
1499
1500 # We are off again...
1501 __builtin__.__dict__['__IPYTHON__active'] -= 1
1502
1503 def excepthook(self, type, value, tb):
1504 """One more defense for GUI apps that call sys.excepthook.
1505
1506 GUI frameworks like wxPython trap exceptions and call
1507 sys.excepthook themselves. I guess this is a feature that
1508 enables them to keep running after exceptions that would
1509 otherwise kill their mainloop. This is a bother for IPython
1510 which excepts to catch all of the program exceptions with a try:
1511 except: statement.
1512
1513 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1514 any app directly invokes sys.excepthook, it will look to the user like
1515 IPython crashed. In order to work around this, we can disable the
1516 CrashHandler and replace it with this excepthook instead, which prints a
1517 regular traceback using our InteractiveTB. In this fashion, apps which
1518 call sys.excepthook will generate a regular-looking exception from
1519 IPython, and the CrashHandler will only be triggered by real IPython
1520 crashes.
1521
1522 This hook should be used sparingly, only in places which are not likely
1523 to be true IPython errors.
1524 """
1525
1526 self.InteractiveTB(type, value, tb, tb_offset=0)
1527 if self.InteractiveTB.call_pdb and self.has_readline:
1528 self.readline.set_completer(self.Completer.complete)
1529
1530 def call_alias(self,alias,rest=''):
1531 """Call an alias given its name and the rest of the line.
1532
1533 This function MUST be given a proper alias, because it doesn't make
1534 any checks when looking up into the alias table. The caller is
1535 responsible for invoking it only with a valid alias."""
1536
1537 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1538 nargs,cmd = self.alias_table[alias]
1539 # Expand the %l special to be the user's input line
1540 if cmd.find('%l') >= 0:
1541 cmd = cmd.replace('%l',rest)
1542 rest = ''
1543 if nargs==0:
1544 # Simple, argument-less aliases
1545 cmd = '%s %s' % (cmd,rest)
1546 else:
1547 # Handle aliases with positional arguments
1548 args = rest.split(None,nargs)
1549 if len(args)< nargs:
1550 error('Alias <%s> requires %s arguments, %s given.' %
1551 (alias,nargs,len(args)))
1552 return
1553 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1554 # Now call the macro, evaluating in the user's namespace
1555 try:
1556 self.system(cmd)
1557 except:
1558 self.showtraceback()
1559
1560 def runlines(self,lines):
1561 """Run a string of one or more lines of source.
1562
1563 This method is capable of running a string containing multiple source
1564 lines, as if they had been entered at the IPython prompt. Since it
1565 exposes IPython's processing machinery, the given strings can contain
1566 magic calls (%magic), special shell access (!cmd), etc."""
1567
1568 # We must start with a clean buffer, in case this is run from an
1569 # interactive IPython session (via a magic, for example).
1570 self.resetbuffer()
1571 lines = lines.split('\n')
1572 more = 0
1573 for line in lines:
1574 # skip blank lines so we don't mess up the prompt counter, but do
1575 # NOT skip even a blank line if we are in a code block (more is
1576 # true)
1577 if line or more:
1578 more = self.push((self.prefilter(line,more)))
1579 # IPython's runsource returns None if there was an error
1580 # compiling the code. This allows us to stop processing right
1581 # away, so the user gets the error message at the right place.
1582 if more is None:
1583 break
1584 # final newline in case the input didn't have it, so that the code
1585 # actually does get executed
1586 if more:
1587 self.push('\n')
1588
1589 def runsource(self, source, filename="<input>", symbol="single"):
1590 """Compile and run some source in the interpreter.
1591
1592 Arguments are as for compile_command().
1593
1594 One several things can happen:
1595
1596 1) The input is incorrect; compile_command() raised an
1597 exception (SyntaxError or OverflowError). A syntax traceback
1598 will be printed by calling the showsyntaxerror() method.
1599
1600 2) The input is incomplete, and more input is required;
1601 compile_command() returned None. Nothing happens.
1602
1603 3) The input is complete; compile_command() returned a code
1604 object. The code is executed by calling self.runcode() (which
1605 also handles run-time exceptions, except for SystemExit).
1606
1607 The return value is:
1608
1609 - True in case 2
1610
1611 - False in the other cases, unless an exception is raised, where
1612 None is returned instead. This can be used by external callers to
1613 know whether to continue feeding input or not.
1614
1615 The return value can be used to decide whether to use sys.ps1 or
1616 sys.ps2 to prompt the next line."""
1617 try:
1618 code = self.compile(source, filename, symbol)
1619 except (OverflowError, SyntaxError, ValueError):
1620 # Case 1
1621 self.showsyntaxerror(filename)
1622 return None
1623
1624 if code is None:
1625 # Case 2
1626 return True
1627
1628 # Case 3
1629 # We store the code source and object so that threaded shells and
1630 # custom exception handlers can access all this info if needed.
1631 self.code_to_run_src = source
1632 self.code_to_run = code
1633 # now actually execute the code object
1634 if self.runcode(code) == 0:
1635 return False
1636 else:
1637 return None
1638
1639 def runcode(self,code_obj):
1640 """Execute a code object.
1641
1642 When an exception occurs, self.showtraceback() is called to display a
1643 traceback.
1644
1645 Return value: a flag indicating whether the code to be run completed
1646 successfully:
1647
1648 - 0: successful execution.
1649 - 1: an error occurred.
1650 """
1651
1652 # Set our own excepthook in case the user code tries to call it
1653 # directly, so that the IPython crash handler doesn't get triggered
1654 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1655 outflag = 1 # happens in more places, so it's easier as default
1656 try:
1657 try:
1658 exec code_obj in self.locals
1659 finally:
1660 # Reset our crash handler in place
1661 sys.excepthook = old_excepthook
1662 except SystemExit:
1663 self.resetbuffer()
1664 self.showtraceback()
1665 warn( __builtin__.exit,level=1)
1666 except self.custom_exceptions:
1667 etype,value,tb = sys.exc_info()
1668 self.CustomTB(etype,value,tb)
1669 except:
1670 self.showtraceback()
1671 else:
1672 outflag = 0
1673 if code.softspace(sys.stdout, 0):
1674 print
1675 # Flush out code object which has been run (and source)
1676 self.code_to_run = None
1677 self.code_to_run_src = ''
1678 return outflag
1679
1680 def raw_input(self, prompt=""):
1681 """Write a prompt and read a line.
1682
1683 The returned line does not include the trailing newline.
1684 When the user enters the EOF key sequence, EOFError is raised.
1685
1686 The base implementation uses the built-in function
1687 raw_input(); a subclass may replace this with a different
1688 implementation.
1689 """
1690 return self.prefilter(raw_input_original(prompt),
1691 prompt==self.outputcache.prompt2)
1692
1693 def split_user_input(self,line):
1694 """Split user input into pre-char, function part and rest."""
1695
1696 lsplit = self.line_split.match(line)
1697 if lsplit is None: # no regexp match returns None
1698 try:
1699 iFun,theRest = line.split(None,1)
1700 except ValueError:
1701 iFun,theRest = line,''
1702 pre = re.match('^(\s*)(.*)',line).groups()[0]
1703 else:
1704 pre,iFun,theRest = lsplit.groups()
1705
1706 #print 'line:<%s>' % line # dbg
1707 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1708 return pre,iFun.strip(),theRest
1709
1710 def _prefilter(self, line, continue_prompt):
1711 """Calls different preprocessors, depending on the form of line."""
1712
1713 # All handlers *must* return a value, even if it's blank ('').
1714
1715 # Lines are NOT logged here. Handlers should process the line as
1716 # needed, update the cache AND log it (so that the input cache array
1717 # stays synced).
1718
1719 # This function is _very_ delicate, and since it's also the one which
1720 # determines IPython's response to user input, it must be as efficient
1721 # as possible. For this reason it has _many_ returns in it, trying
1722 # always to exit as quickly as it can figure out what it needs to do.
1723
1724 # This function is the main responsible for maintaining IPython's
1725 # behavior respectful of Python's semantics. So be _very_ careful if
1726 # making changes to anything here.
1727
1728 #.....................................................................
1729 # Code begins
1730
1731 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1732
1733 # save the line away in case we crash, so the post-mortem handler can
1734 # record it
1735 self._last_input_line = line
1736
1737 #print '***line: <%s>' % line # dbg
1738
1739 # the input history needs to track even empty lines
1740 if not line.strip():
1741 if not continue_prompt:
1742 self.outputcache.prompt_count -= 1
1743 return self.handle_normal('',continue_prompt)
1744
1745 # print '***cont',continue_prompt # dbg
1746 # special handlers are only allowed for single line statements
1747 if continue_prompt and not self.rc.multi_line_specials:
1748 return self.handle_normal(line,continue_prompt)
1749
1750 # For the rest, we need the structure of the input
1751 pre,iFun,theRest = self.split_user_input(line)
1752 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1753
1754 # First check for explicit escapes in the last/first character
1755 handler = None
1756 if line[-1] == self.ESC_HELP:
1757 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1758 if handler is None:
1759 # look at the first character of iFun, NOT of line, so we skip
1760 # leading whitespace in multiline input
1761 handler = self.esc_handlers.get(iFun[0:1])
1762 if handler is not None:
1763 return handler(line,continue_prompt,pre,iFun,theRest)
1764 # Emacs ipython-mode tags certain input lines
1765 if line.endswith('# PYTHON-MODE'):
1766 return self.handle_emacs(line,continue_prompt)
1767
1768 # Next, check if we can automatically execute this thing
1769
1770 # Allow ! in multi-line statements if multi_line_specials is on:
1771 if continue_prompt and self.rc.multi_line_specials and \
1772 iFun.startswith(self.ESC_SHELL):
1773 return self.handle_shell_escape(line,continue_prompt,
1774 pre=pre,iFun=iFun,
1775 theRest=theRest)
1776
1777 # Let's try to find if the input line is a magic fn
1778 oinfo = None
1779 if hasattr(self,'magic_'+iFun):
1780 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1781 if oinfo['ismagic']:
1782 # Be careful not to call magics when a variable assignment is
1783 # being made (ls='hi', for example)
1784 if self.rc.automagic and \
1785 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1786 (self.rc.multi_line_specials or not continue_prompt):
1787 return self.handle_magic(line,continue_prompt,
1788 pre,iFun,theRest)
1789 else:
1790 return self.handle_normal(line,continue_prompt)
1791
1792 # If the rest of the line begins with an (in)equality, assginment or
1793 # function call, we should not call _ofind but simply execute it.
1794 # This avoids spurious geattr() accesses on objects upon assignment.
1795 #
1796 # It also allows users to assign to either alias or magic names true
1797 # python variables (the magic/alias systems always take second seat to
1798 # true python code).
1799 if theRest and theRest[0] in '!=()':
1800 return self.handle_normal(line,continue_prompt)
1801
1802 if oinfo is None:
1803 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1804
1805 if not oinfo['found']:
1806 return self.handle_normal(line,continue_prompt)
1807 else:
1808 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1809 if oinfo['isalias']:
1810 return self.handle_alias(line,continue_prompt,
1811 pre,iFun,theRest)
1812
1813 if self.rc.autocall and \
1814 not self.re_exclude_auto.match(theRest) and \
1815 self.re_fun_name.match(iFun) and \
1816 callable(oinfo['obj']) :
1817 #print 'going auto' # dbg
1818 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1819 else:
1820 #print 'was callable?', callable(oinfo['obj']) # dbg
1821 return self.handle_normal(line,continue_prompt)
1822
1823 # If we get here, we have a normal Python line. Log and return.
1824 return self.handle_normal(line,continue_prompt)
1825
1826 def _prefilter_dumb(self, line, continue_prompt):
1827 """simple prefilter function, for debugging"""
1828 return self.handle_normal(line,continue_prompt)
1829
1830 # Set the default prefilter() function (this can be user-overridden)
1831 prefilter = _prefilter
1832
1833 def handle_normal(self,line,continue_prompt=None,
1834 pre=None,iFun=None,theRest=None):
1835 """Handle normal input lines. Use as a template for handlers."""
1836
1837 self.log(line,continue_prompt)
1838 self.update_cache(line)
1839 return line
1840
1841 def handle_alias(self,line,continue_prompt=None,
1842 pre=None,iFun=None,theRest=None):
1843 """Handle alias input lines. """
1844
1845 theRest = esc_quotes(theRest)
1846 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1847 self.log(line_out,continue_prompt)
1848 self.update_cache(line_out)
1849 return line_out
1850
1851 def handle_shell_escape(self, line, continue_prompt=None,
1852 pre=None,iFun=None,theRest=None):
1853 """Execute the line in a shell, empty return value"""
1854
1855 # Example of a special handler. Others follow a similar pattern.
1856 if continue_prompt: # multi-line statements
1857 if iFun.startswith('!!'):
1858 print 'SyntaxError: !! is not allowed in multiline statements'
1859 return pre
1860 else:
1861 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1862 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1863 else: # single-line input
1864 if line.startswith('!!'):
1865 # rewrite iFun/theRest to properly hold the call to %sx and
1866 # the actual command to be executed, so handle_magic can work
1867 # correctly
1868 theRest = '%s %s' % (iFun[2:],theRest)
1869 iFun = 'sx'
1870 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1871 continue_prompt,pre,iFun,theRest)
1872 else:
1873 cmd = esc_quotes(line[1:])
1874 line_out = '%s.system("%s")' % (self.name,cmd)
1875 # update cache/log and return
1876 self.log(line_out,continue_prompt)
1877 self.update_cache(line_out) # readline cache gets normal line
1878 return line_out
1879
1880 def handle_magic(self, line, continue_prompt=None,
1881 pre=None,iFun=None,theRest=None):
1882 """Execute magic functions.
1883
1884 Also log them with a prepended # so the log is clean Python."""
1885
1886 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1887 self.log(cmd,continue_prompt)
1888 self.update_cache(line)
1889 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1890 return cmd
1891
1892 def handle_auto(self, line, continue_prompt=None,
1893 pre=None,iFun=None,theRest=None):
1894 """Hande lines which can be auto-executed, quoting if requested."""
1895
1896 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1897
1898 # This should only be active for single-line input!
1899 if continue_prompt:
1900 return line
1901
1902 if pre == self.ESC_QUOTE:
1903 # Auto-quote splitting on whitespace
1904 newcmd = '%s("%s")\n' % (iFun,'", "'.join(theRest.split()) )
1905 elif pre == self.ESC_QUOTE2:
1906 # Auto-quote whole string
1907 newcmd = '%s("%s")\n' % (iFun,theRest)
1908 else:
1909 # Auto-paren
1910 if theRest[0:1] in ('=','['):
1911 # Don't autocall in these cases. They can be either
1912 # rebindings of an existing callable's name, or item access
1913 # for an object which is BOTH callable and implements
1914 # __getitem__.
1915 return '%s %s\n' % (iFun,theRest)
1916 if theRest.endswith(';'):
1917 newcmd = '%s(%s);\n' % (iFun.rstrip(),theRest[:-1])
1918 else:
1919 newcmd = '%s(%s)\n' % (iFun.rstrip(),theRest)
1920
1921 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd,
1922 # log what is now valid Python, not the actual user input (without the
1923 # final newline)
1924 self.log(newcmd.strip(),continue_prompt)
1925 return newcmd
1926
1927 def handle_help(self, line, continue_prompt=None,
1928 pre=None,iFun=None,theRest=None):
1929 """Try to get some help for the object.
1930
1931 obj? or ?obj -> basic information.
1932 obj?? or ??obj -> more details.
1933 """
1934
1935 # We need to make sure that we don't process lines which would be
1936 # otherwise valid python, such as "x=1 # what?"
1937 try:
1938 code.compile_command(line)
1939 except SyntaxError:
1940 # We should only handle as help stuff which is NOT valid syntax
1941 if line[0]==self.ESC_HELP:
1942 line = line[1:]
1943 elif line[-1]==self.ESC_HELP:
1944 line = line[:-1]
1945 self.log('#?'+line)
1946 self.update_cache(line)
1947 if line:
1948 self.magic_pinfo(line)
1949 else:
1950 page(self.usage,screen_lines=self.rc.screen_length)
1951 return '' # Empty string is needed here!
1952 except:
1953 # Pass any other exceptions through to the normal handler
1954 return self.handle_normal(line,continue_prompt)
1955 else:
1956 # If the code compiles ok, we should handle it normally
1957 return self.handle_normal(line,continue_prompt)
1958
1959 def handle_emacs(self,line,continue_prompt=None,
1960 pre=None,iFun=None,theRest=None):
1961 """Handle input lines marked by python-mode."""
1962
1963 # Currently, nothing is done. Later more functionality can be added
1964 # here if needed.
1965
1966 # The input cache shouldn't be updated
1967
1968 return line
1969
1970 def write(self,data):
1971 """Write a string to the default output"""
1972 Term.cout.write(data)
1973
1974 def write_err(self,data):
1975 """Write a string to the default error output"""
1976 Term.cerr.write(data)
1977
1978 def safe_execfile(self,fname,*where,**kw):
1979 fname = os.path.expanduser(fname)
1980
1981 # find things also in current directory
1982 dname = os.path.dirname(fname)
1983 if not sys.path.count(dname):
1984 sys.path.append(dname)
1985
1986 try:
1987 xfile = open(fname)
1988 except:
1989 print >> Term.cerr, \
1990 'Could not open file <%s> for safe execution.' % fname
1991 return None
1992
1993 kw.setdefault('islog',0)
1994 kw.setdefault('quiet',1)
1995 kw.setdefault('exit_ignore',0)
1996 first = xfile.readline()
1997 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1998 xfile.close()
1999 # line by line execution
2000 if first.startswith(_LOGHEAD) or kw['islog']:
2001 print 'Loading log file <%s> one line at a time...' % fname
2002 if kw['quiet']:
2003 stdout_save = sys.stdout
2004 sys.stdout = StringIO.StringIO()
2005 try:
2006 globs,locs = where[0:2]
2007 except:
2008 try:
2009 globs = locs = where[0]
2010 except:
2011 globs = locs = globals()
2012 badblocks = []
2013
2014 # we also need to identify indented blocks of code when replaying
2015 # logs and put them together before passing them to an exec
2016 # statement. This takes a bit of regexp and look-ahead work in the
2017 # file. It's easiest if we swallow the whole thing in memory
2018 # first, and manually walk through the lines list moving the
2019 # counter ourselves.
2020 indent_re = re.compile('\s+\S')
2021 xfile = open(fname)
2022 filelines = xfile.readlines()
2023 xfile.close()
2024 nlines = len(filelines)
2025 lnum = 0
2026 while lnum < nlines:
2027 line = filelines[lnum]
2028 lnum += 1
2029 # don't re-insert logger status info into cache
2030 if line.startswith('#log#'):
2031 continue
2032 elif line.startswith('#%s'% self.ESC_MAGIC):
2033 self.update_cache(line[1:])
2034 line = magic2python(line)
2035 elif line.startswith('#!'):
2036 self.update_cache(line[1:])
2037 else:
2038 # build a block of code (maybe a single line) for execution
2039 block = line
2040 try:
2041 next = filelines[lnum] # lnum has already incremented
2042 except:
2043 next = None
2044 while next and indent_re.match(next):
2045 block += next
2046 lnum += 1
2047 try:
2048 next = filelines[lnum]
2049 except:
2050 next = None
2051 # now execute the block of one or more lines
2052 try:
2053 exec block in globs,locs
2054 self.update_cache(block.rstrip())
2055 except SystemExit:
2056 pass
2057 except:
2058 badblocks.append(block.rstrip())
2059 if kw['quiet']: # restore stdout
2060 sys.stdout.close()
2061 sys.stdout = stdout_save
2062 print 'Finished replaying log file <%s>' % fname
2063 if badblocks:
2064 print >> sys.stderr, \
2065 '\nThe following lines/blocks in file <%s> reported errors:' \
2066 % fname
2067 for badline in badblocks:
2068 print >> sys.stderr, badline
2069 else: # regular file execution
2070 try:
2071 execfile(fname,*where)
2072 except SyntaxError:
2073 etype, evalue = sys.exc_info()[0:2]
2074 self.SyntaxTB(etype,evalue,[])
2075 warn('Failure executing file: <%s>' % fname)
2076 except SystemExit,status:
2077 if not kw['exit_ignore']:
2078 self.InteractiveTB()
2079 warn('Failure executing file: <%s>' % fname)
2080 except:
2081 self.InteractiveTB()
2082 warn('Failure executing file: <%s>' % fname)
2083
2084 #************************* end of file <iplib.py> *****************************
This diff has been collapsed as it changes many lines, (736 lines changed) Show them Hide them
@@ -0,0 +1,736 b''
1 # -*- coding: utf-8 -*-
2 """
3 IPython -- An enhanced Interactive Python
4
5 Requires Python 2.1 or better.
6
7 This file contains the main make_IPython() starter function.
8
9 $Id: ipmaker.py 582 2005-05-13 21:20:00Z fperez $"""
10
11 #*****************************************************************************
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
17
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
21 __version__ = Release.version
22
23 credits._Printer__data = """
24 Python: %s
25
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 See http://ipython.scipy.org for more information.""" \
28 % credits._Printer__data
29
30 copyright._Printer__data += """
31
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 All Rights Reserved."""
34
35 #****************************************************************************
36 # Required modules
37
38 # From the standard library
39 import __main__, __builtin__
40 import os,sys,types,re
41 from pprint import pprint,pformat
42
43 # Our own
44 from IPython import DPyGetOpt
45 from IPython.Struct import Struct
46 from IPython.OutputTrap import OutputTrap
47 from IPython.ConfigLoader import ConfigLoader
48 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
49 from IPython.usage import cmd_line_usage,interactive_usage
50 from IPython.Prompts import CachedOutput
51 from IPython.genutils import *
52
53 #-----------------------------------------------------------------------------
54 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
55 shell_class=InteractiveShell,embedded=False,**kw):
56 """This is a dump of IPython into a single function.
57
58 Later it will have to be broken up in a sensible manner.
59
60 Arguments:
61
62 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
63 script name, b/c DPyGetOpt strips the first argument only for the real
64 sys.argv.
65
66 - user_ns: a dict to be used as the user's namespace."""
67
68 #----------------------------------------------------------------------
69 # Defaults and initialization
70
71 # For developer debugging, deactivates crash handler and uses pdb.
72 DEVDEBUG = False
73
74 if argv is None:
75 argv = sys.argv
76
77 # __IP is the main global that lives throughout and represents the whole
78 # application. If the user redefines it, all bets are off as to what
79 # happens.
80
81 # __IP is the name of he global which the caller will have accessible as
82 # __IP.name. We set its name via the first parameter passed to
83 # InteractiveShell:
84
85 IP = shell_class('__IP',user_ns=user_ns,**kw)
86
87 # Put 'help' in the user namespace
88 try:
89 from site import _Helper
90 except ImportError:
91 # Use the _Helper class from Python 2.2 for older Python versions
92 class _Helper:
93 def __repr__(self):
94 return "Type help() for interactive help, " \
95 "or help(object) for help about object."
96 def __call__(self, *args, **kwds):
97 import pydoc
98 return pydoc.help(*args, **kwds)
99 else:
100 IP.user_ns['help'] = _Helper()
101
102 if DEVDEBUG:
103 # For developer debugging only (global flag)
104 from IPython import ultraTB
105 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
106 else:
107 # IPython itself shouldn't crash. This will produce a detailed
108 # post-mortem if it does
109 from IPython import CrashHandler
110 sys.excepthook = CrashHandler.CrashHandler(IP)
111
112 IP.BANNER_PARTS = ['Python %s\n'
113 'Type "copyright", "credits" or "license" '
114 'for more information.\n'
115 % (sys.version.split('\n')[0],),
116 "IPython %s -- An enhanced Interactive Python."
117 % (__version__,),
118 """? -> Introduction to IPython's features.
119 %magic -> Information about IPython's 'magic' % functions.
120 help -> Python's own help system.
121 object? -> Details about 'object'. ?object also works, ?? prints more.
122 """ ]
123
124 IP.usage = interactive_usage
125
126 # Platform-dependent suffix and directory names
127 if os.name == 'posix':
128 rc_suffix = ''
129 ipdir_def = '.ipython'
130 else:
131 rc_suffix = '.ini'
132 ipdir_def = '_ipython'
133
134 # default directory for configuration
135 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
136 os.path.join(IP.home_dir,ipdir_def)))
137
138 # we need the directory where IPython itself is installed
139 import IPython
140 IPython_dir = os.path.dirname(IPython.__file__)
141 del IPython
142
143 #-------------------------------------------------------------------------
144 # Command line handling
145
146 # Valid command line options (uses DPyGetOpt syntax, like Perl's
147 # GetOpt::Long)
148
149 # Any key not listed here gets deleted even if in the file (like session
150 # or profile). That's deliberate, to maintain the rc namespace clean.
151
152 # Each set of options appears twice: under _conv only the names are
153 # listed, indicating which type they must be converted to when reading the
154 # ipythonrc file. And under DPyGetOpt they are listed with the regular
155 # DPyGetOpt syntax (=s,=i,:f,etc).
156
157 # Make sure there's a space before each end of line (they get auto-joined!)
158 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
159 'c=s classic|cl color_info! colors=s confirm_exit! '
160 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
161 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
162 'quick screen_length|sl=i prompts_pad_left=i '
163 'logfile|lf=s logplay|lp=s profile|p=s '
164 'readline! readline_merge_completions! '
165 'readline_omit__names! '
166 'rcfile=s separate_in|si=s separate_out|so=s '
167 'separate_out2|so2=s xmode=s '
168 'magic_docstrings system_verbose! '
169 'multi_line_specials!')
170
171 # Options that can *only* appear at the cmd line (not in rcfiles).
172
173 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
174 # the 'C-c !' command in emacs automatically appends a -i option at the end.
175 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
176 'gthread! qthread! wthread! pylab! tk!')
177
178 # Build the actual name list to be used by DPyGetOpt
179 opts_names = qw(cmdline_opts) + qw(cmdline_only)
180
181 # Set sensible command line defaults.
182 # This should have everything from cmdline_opts and cmdline_only
183 opts_def = Struct(autocall = 1,
184 autoindent=0,
185 automagic = 1,
186 banner = 1,
187 cache_size = 1000,
188 c = '',
189 classic = 0,
190 colors = 'NoColor',
191 color_info = 0,
192 confirm_exit = 1,
193 debug = 0,
194 deep_reload = 0,
195 editor = '0',
196 help = 0,
197 ignore = 0,
198 ipythondir = ipythondir,
199 log = 0,
200 logfile = '',
201 logplay = '',
202 multi_line_specials = 1,
203 messages = 1,
204 nosep = 0,
205 pdb = 0,
206 pprint = 0,
207 profile = '',
208 prompt_in1 = 'In [\\#]:',
209 prompt_in2 = ' .\\D.:',
210 prompt_out = 'Out[\\#]:',
211 prompts_pad_left = 1,
212 quick = 0,
213 readline = 1,
214 readline_merge_completions = 1,
215 readline_omit__names = 0,
216 rcfile = 'ipythonrc' + rc_suffix,
217 screen_length = 0,
218 separate_in = '\n',
219 separate_out = '\n',
220 separate_out2 = '',
221 system_verbose = 0,
222 gthread = 0,
223 qthread = 0,
224 wthread = 0,
225 pylab = 0,
226 tk = 0,
227 upgrade = 0,
228 Version = 0,
229 xmode = 'Verbose',
230 magic_docstrings = 0, # undocumented, for doc generation
231 )
232
233 # Things that will *only* appear in rcfiles (not at the command line).
234 # Make sure there's a space before each end of line (they get auto-joined!)
235 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
236 qw_lol: 'import_some ',
237 # for things with embedded whitespace:
238 list_strings:'execute alias readline_parse_and_bind ',
239 # Regular strings need no conversion:
240 None:'readline_remove_delims ',
241 }
242 # Default values for these
243 rc_def = Struct(include = [],
244 import_mod = [],
245 import_all = [],
246 import_some = [[]],
247 execute = [],
248 execfile = [],
249 alias = [],
250 readline_parse_and_bind = [],
251 readline_remove_delims = '',
252 )
253
254 # Build the type conversion dictionary from the above tables:
255 typeconv = rcfile_opts.copy()
256 typeconv.update(optstr2types(cmdline_opts))
257
258 # FIXME: the None key appears in both, put that back together by hand. Ugly!
259 typeconv[None] += ' ' + rcfile_opts[None]
260
261 # Remove quotes at ends of all strings (used to protect spaces)
262 typeconv[unquote_ends] = typeconv[None]
263 del typeconv[None]
264
265 # Build the list we'll use to make all config decisions with defaults:
266 opts_all = opts_def.copy()
267 opts_all.update(rc_def)
268
269 # Build conflict resolver for recursive loading of config files:
270 # - preserve means the outermost file maintains the value, it is not
271 # overwritten if an included file has the same key.
272 # - add_flip applies + to the two values, so it better make sense to add
273 # those types of keys. But it flips them first so that things loaded
274 # deeper in the inclusion chain have lower precedence.
275 conflict = {'preserve': ' '.join([ typeconv[int],
276 typeconv[unquote_ends] ]),
277 'add_flip': ' '.join([ typeconv[qwflat],
278 typeconv[qw_lol],
279 typeconv[list_strings] ])
280 }
281
282 # Now actually process the command line
283 getopt = DPyGetOpt.DPyGetOpt()
284 getopt.setIgnoreCase(0)
285
286 getopt.parseConfiguration(opts_names)
287
288 try:
289 getopt.processArguments(argv)
290 except:
291 print cmd_line_usage
292 warn('\nError in Arguments: ' + `sys.exc_value`)
293 sys.exit()
294
295 # convert the options dict to a struct for much lighter syntax later
296 opts = Struct(getopt.optionValues)
297 args = getopt.freeValues
298
299 # this is the struct (which has default values at this point) with which
300 # we make all decisions:
301 opts_all.update(opts)
302
303 # Options that force an immediate exit
304 if opts_all.help:
305 page(cmd_line_usage)
306 sys.exit()
307
308 if opts_all.Version:
309 print __version__
310 sys.exit()
311
312 if opts_all.magic_docstrings:
313 IP.magic_magic('-latex')
314 sys.exit()
315
316 # Create user config directory if it doesn't exist. This must be done
317 # *after* getting the cmd line options.
318 if not os.path.isdir(opts_all.ipythondir):
319 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
320
321 # upgrade user config files while preserving a copy of the originals
322 if opts_all.upgrade:
323 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
324
325 # check mutually exclusive options in the *original* command line
326 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
327 qw('classic profile'),qw('classic rcfile')])
328
329 # default logfilename used when -log is called.
330 IP.LOGDEF = 'ipython.log'
331
332 #---------------------------------------------------------------------------
333 # Log replay
334
335 # if -logplay, we need to 'become' the other session. That basically means
336 # replacing the current command line environment with that of the old
337 # session and moving on.
338
339 # this is needed so that later we know we're in session reload mode, as
340 # opts_all will get overwritten:
341 load_logplay = 0
342
343 if opts_all.logplay:
344 load_logplay = opts_all.logplay
345 opts_debug_save = opts_all.debug
346 try:
347 logplay = open(opts_all.logplay)
348 except IOError:
349 if opts_all.debug: IP.InteractiveTB()
350 warn('Could not open logplay file '+`opts_all.logplay`)
351 # restore state as if nothing had happened and move on, but make
352 # sure that later we don't try to actually load the session file
353 logplay = None
354 load_logplay = 0
355 del opts_all.logplay
356 else:
357 try:
358 logplay.readline()
359 logplay.readline();
360 # this reloads that session's command line
361 cmd = logplay.readline()[6:]
362 exec cmd
363 # restore the true debug flag given so that the process of
364 # session loading itself can be monitored.
365 opts.debug = opts_debug_save
366 # save the logplay flag so later we don't overwrite the log
367 opts.logplay = load_logplay
368 # now we must update our own structure with defaults
369 opts_all.update(opts)
370 # now load args
371 cmd = logplay.readline()[6:]
372 exec cmd
373 logplay.close()
374 except:
375 logplay.close()
376 if opts_all.debug: IP.InteractiveTB()
377 warn("Logplay file lacking full configuration information.\n"
378 "I'll try to read it, but some things may not work.")
379
380 #-------------------------------------------------------------------------
381 # set up output traps: catch all output from files, being run, modules
382 # loaded, etc. Then give it to the user in a clean form at the end.
383
384 msg_out = 'Output messages. '
385 msg_err = 'Error messages. '
386 msg_sep = '\n'
387 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
388 msg_err,msg_sep,debug,
389 quiet_out=1),
390 user_exec = OutputTrap('User File Execution',msg_out,
391 msg_err,msg_sep,debug),
392 logplay = OutputTrap('Log Loader',msg_out,
393 msg_err,msg_sep,debug),
394 summary = ''
395 )
396
397 #-------------------------------------------------------------------------
398 # Process user ipythonrc-type configuration files
399
400 # turn on output trapping and log to msg.config
401 # remember that with debug on, trapping is actually disabled
402 msg.config.trap_all()
403
404 # look for rcfile in current or default directory
405 try:
406 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
407 except IOError:
408 if opts_all.debug: IP.InteractiveTB()
409 warn('Configuration file %s not found. Ignoring request.'
410 % (opts_all.rcfile) )
411
412 # 'profiles' are a shorthand notation for config filenames
413 if opts_all.profile:
414 try:
415 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
416 + rc_suffix,
417 opts_all.ipythondir)
418 except IOError:
419 if opts_all.debug: IP.InteractiveTB()
420 opts.profile = '' # remove profile from options if invalid
421 warn('Profile configuration file %s not found. Ignoring request.'
422 % (opts_all.profile) )
423
424 # load the config file
425 rcfiledata = None
426 if opts_all.quick:
427 print 'Launching IPython in quick mode. No config file read.'
428 elif opts_all.classic:
429 print 'Launching IPython in classic mode. No config file read.'
430 elif opts_all.rcfile:
431 try:
432 cfg_loader = ConfigLoader(conflict)
433 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
434 'include',opts_all.ipythondir,
435 purge = 1,
436 unique = conflict['preserve'])
437 except:
438 IP.InteractiveTB()
439 warn('Problems loading configuration file '+
440 `opts_all.rcfile`+
441 '\nStarting with default -bare bones- configuration.')
442 else:
443 warn('No valid configuration file found in either currrent directory\n'+
444 'or in the IPython config. directory: '+`opts_all.ipythondir`+
445 '\nProceeding with internal defaults.')
446
447 #------------------------------------------------------------------------
448 # Set exception handlers in mode requested by user.
449 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
450 IP.magic_xmode(opts_all.xmode)
451 otrap.release_out()
452
453 #------------------------------------------------------------------------
454 # Execute user config
455
456 # first, create a valid config structure with the right precedence order:
457 # defaults < rcfile < command line
458 IP.rc = rc_def.copy()
459 IP.rc.update(opts_def)
460 if rcfiledata:
461 # now we can update
462 IP.rc.update(rcfiledata)
463 IP.rc.update(opts)
464 IP.rc.update(rc_override)
465
466 # Store the original cmd line for reference:
467 IP.rc.opts = opts
468 IP.rc.args = args
469
470 # create a *runtime* Struct like rc for holding parameters which may be
471 # created and/or modified by runtime user extensions.
472 IP.runtime_rc = Struct()
473
474 # from this point on, all config should be handled through IP.rc,
475 # opts* shouldn't be used anymore.
476
477 # add personal .ipython dir to sys.path so that users can put things in
478 # there for customization
479 sys.path.append(IP.rc.ipythondir)
480 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
481
482 # update IP.rc with some special things that need manual
483 # tweaks. Basically options which affect other options. I guess this
484 # should just be written so that options are fully orthogonal and we
485 # wouldn't worry about this stuff!
486
487 if IP.rc.classic:
488 IP.rc.quick = 1
489 IP.rc.cache_size = 0
490 IP.rc.pprint = 0
491 IP.rc.prompt_in1 = '>>> '
492 IP.rc.prompt_in2 = '... '
493 IP.rc.prompt_out = ''
494 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
495 IP.rc.colors = 'NoColor'
496 IP.rc.xmode = 'Plain'
497
498 # configure readline
499 # Define the history file for saving commands in between sessions
500 if IP.rc.profile:
501 histfname = 'history-%s' % IP.rc.profile
502 else:
503 histfname = 'history'
504 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
505 # Load readline proper
506 if IP.rc.readline:
507 IP.init_readline()
508
509 # update exception handlers with rc file status
510 otrap.trap_out() # I don't want these messages ever.
511 IP.magic_xmode(IP.rc.xmode)
512 otrap.release_out()
513
514 # activate logging if requested and not reloading a log
515 if IP.rc.logplay:
516 IP.magic_logstart(IP.rc.logplay + ' append')
517 elif IP.rc.logfile:
518 IP.magic_logstart(IP.rc.logfile)
519 elif IP.rc.log:
520 IP.magic_logstart()
521
522 # find user editor so that it we don't have to look it up constantly
523 if IP.rc.editor.strip()=='0':
524 try:
525 ed = os.environ['EDITOR']
526 except KeyError:
527 if os.name == 'posix':
528 ed = 'vi' # the only one guaranteed to be there!
529 else:
530 ed = 'notepad' # same in Windows!
531 IP.rc.editor = ed
532
533 # Recursive reload
534 try:
535 from IPython import deep_reload
536 if IP.rc.deep_reload:
537 __builtin__.reload = deep_reload.reload
538 else:
539 __builtin__.dreload = deep_reload.reload
540 del deep_reload
541 except ImportError:
542 pass
543
544 # Save the current state of our namespace so that the interactive shell
545 # can later know which variables have been created by us from config files
546 # and loading. This way, loading a file (in any way) is treated just like
547 # defining things on the command line, and %who works as expected.
548
549 # DON'T do anything that affects the namespace beyond this point!
550 IP.internal_ns = __main__.__dict__.copy()
551
552 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
553
554 # Now run through the different sections of the users's config
555 if IP.rc.debug:
556 print 'Trying to execute the following configuration structure:'
557 print '(Things listed first are deeper in the inclusion tree and get'
558 print 'loaded first).\n'
559 pprint(IP.rc.__dict__)
560
561 for mod in IP.rc.import_mod:
562 try:
563 exec 'import '+mod in IP.user_ns
564 except :
565 IP.InteractiveTB()
566 import_fail_info(mod)
567
568 for mod_fn in IP.rc.import_some:
569 if mod_fn == []: break
570 mod,fn = mod_fn[0],','.join(mod_fn[1:])
571 try:
572 exec 'from '+mod+' import '+fn in IP.user_ns
573 except :
574 IP.InteractiveTB()
575 import_fail_info(mod,fn)
576
577 for mod in IP.rc.import_all:
578 try:
579 exec 'from '+mod+' import *' in IP.user_ns
580 except :
581 IP.InteractiveTB()
582 import_fail_info(mod)
583
584 for code in IP.rc.execute:
585 try:
586 exec code in IP.user_ns
587 except:
588 IP.InteractiveTB()
589 warn('Failure executing code: ' + `code`)
590
591 # Execute the files the user wants in ipythonrc
592 for file in IP.rc.execfile:
593 try:
594 file = filefind(file,sys.path+[IPython_dir])
595 except IOError:
596 warn(itpl('File $file not found. Skipping it.'))
597 else:
598 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
599
600 # Load user aliases
601 for alias in IP.rc.alias:
602 IP.magic_alias(alias)
603
604 # release stdout and stderr and save config log into a global summary
605 msg.config.release_all()
606 if IP.rc.messages:
607 msg.summary += msg.config.summary_all()
608
609 #------------------------------------------------------------------------
610 # Setup interactive session
611
612 # Now we should be fully configured. We can then execute files or load
613 # things only needed for interactive use. Then we'll open the shell.
614
615 # Take a snapshot of the user namespace before opening the shell. That way
616 # we'll be able to identify which things were interactively defined and
617 # which were defined through config files.
618 IP.user_config_ns = IP.user_ns.copy()
619
620 # Force reading a file as if it were a session log. Slower but safer.
621 if load_logplay:
622 print 'Replaying log...'
623 try:
624 if IP.rc.debug:
625 logplay_quiet = 0
626 else:
627 logplay_quiet = 1
628
629 msg.logplay.trap_all()
630 IP.safe_execfile(load_logplay,IP.user_ns,
631 islog = 1, quiet = logplay_quiet)
632 msg.logplay.release_all()
633 if IP.rc.messages:
634 msg.summary += msg.logplay.summary_all()
635 except:
636 warn('Problems replaying logfile %s.' % load_logplay)
637 IP.InteractiveTB()
638
639 # Load remaining files in command line
640 msg.user_exec.trap_all()
641
642 # Do NOT execute files named in the command line as scripts to be loaded
643 # by embedded instances. Doing so has the potential for an infinite
644 # recursion if there are exceptions thrown in the process.
645
646 # XXX FIXME: the execution of user files should be moved out to after
647 # ipython is fully initialized, just as if they were run via %run at the
648 # ipython prompt. This would also give them the benefit of ipython's
649 # nice tracebacks.
650
651 if not embedded and IP.rc.args:
652 name_save = IP.user_ns['__name__']
653 IP.user_ns['__name__'] = '__main__'
654 try:
655 # Set our own excepthook in case the user code tries to call it
656 # directly. This prevents triggering the IPython crash handler.
657 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
658 for run in args:
659 IP.safe_execfile(run,IP.user_ns)
660 finally:
661 # Reset our crash handler in place
662 sys.excepthook = old_excepthook
663
664 IP.user_ns['__name__'] = name_save
665
666 msg.user_exec.release_all()
667 if IP.rc.messages:
668 msg.summary += msg.user_exec.summary_all()
669
670 # since we can't specify a null string on the cmd line, 0 is the equivalent:
671 if IP.rc.nosep:
672 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
673 if IP.rc.separate_in == '0': IP.rc.separate_in = ''
674 if IP.rc.separate_out == '0': IP.rc.separate_out = ''
675 if IP.rc.separate_out2 == '0': IP.rc.separate_out2 = ''
676 IP.rc.separate_in = IP.rc.separate_in.replace('\\n','\n')
677 IP.rc.separate_out = IP.rc.separate_out.replace('\\n','\n')
678 IP.rc.separate_out2 = IP.rc.separate_out2.replace('\\n','\n')
679
680 # Determine how many lines at the bottom of the screen are needed for
681 # showing prompts, so we can know wheter long strings are to be printed or
682 # paged:
683 num_lines_bot = IP.rc.separate_in.count('\n')+1
684 IP.rc.screen_length = IP.rc.screen_length - num_lines_bot
685 # Initialize cache, set in/out prompts and printing system
686 IP.outputcache = CachedOutput(IP.rc.cache_size,
687 IP.rc.pprint,
688 input_sep = IP.rc.separate_in,
689 output_sep = IP.rc.separate_out,
690 output_sep2 = IP.rc.separate_out2,
691 ps1 = IP.rc.prompt_in1,
692 ps2 = IP.rc.prompt_in2,
693 ps_out = IP.rc.prompt_out,
694 user_ns = IP.user_ns,
695 input_hist = IP.input_hist,
696 pad_left = IP.rc.prompts_pad_left)
697
698 # Set user colors (don't do it in the constructor above so that it doesn't
699 # crash if colors option is invalid)
700 IP.magic_colors(IP.rc.colors)
701
702 # user may have over-ridden the default print hook:
703 try:
704 IP.outputcache.__class__.display = IP.hooks.display
705 except AttributeError:
706 pass
707
708 # Set calling of pdb on exceptions
709 IP.InteractiveTB.call_pdb = IP.rc.pdb
710
711 # I don't like assigning globally to sys, because it means when embedding
712 # instances, each embedded instance overrides the previous choice. But
713 # sys.displayhook seems to be called internally by exec, so I don't see a
714 # way around it.
715 sys.displayhook = IP.outputcache
716
717 # we need to know globally if we're caching i/o or not
718 IP.do_full_cache = IP.outputcache.do_full_cache
719
720 # configure startup banner
721 if IP.rc.c: # regular python doesn't print the banner with -c
722 IP.rc.banner = 0
723 if IP.rc.banner:
724 IP.BANNER = '\n'.join(IP.BANNER_PARTS)
725 else:
726 IP.BANNER = ''
727
728 if IP.rc.profile: IP.BANNER += '\nIPython profile: '+IP.rc.profile+'\n'
729
730 # add message log (possibly empty)
731 IP.BANNER += msg.summary
732
733 IP.post_config_initialization()
734
735 return IP
736 #************************ end of file <ipmaker.py> **************************
@@ -0,0 +1,305 b''
1 # -*- coding: utf-8 -*-
2 """
3 A set of convenient utilities for numerical work.
4
5 Most of this module requires Numerical Python or is meant to be used with it.
6 See http://www.pfdubois.com/numpy for details.
7
8 $Id: numutils.py 486 2005-01-27 19:34:21Z fperez $"""
9
10 #*****************************************************************************
11 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
12 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
16
17 from IPython import Release
18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __license__ = Release.license
20
21 __all__ = ['sum_flat','mean_flat','rms_flat','base_repr','binary_repr',
22 'amin','amax','amap','zeros_like','empty_like',
23 'frange','diagonal_matrix','identity',
24 'fromfunction_kw','log2','ispower2',
25 'norm','l1norm','l2norm','exp_safe',
26 'inf','infty','Infinity',
27 'Numeric']
28
29 #****************************************************************************
30 # required modules
31 import __main__
32 import sys,operator
33 import math
34 import Numeric
35 from Numeric import *
36
37 #*****************************************************************************
38 # Globals
39
40 # useful for testing infinities in results of array divisions (which don't
41 # raise an exception)
42 # Python, LaTeX and Mathematica names.
43 inf = infty = Infinity = (array([1])/0.0)[0]
44
45 #****************************************************************************
46 # function definitions
47 exp_safe_MIN = math.log(2.2250738585072014e-308)
48 exp_safe_MAX = 1.7976931348623157e+308
49
50 def exp_safe(x):
51 """Compute exponentials which safely underflow to zero.
52
53 Slow but convenient to use. Note that NumArray will introduce proper
54 floating point exception handling with access to the underlying
55 hardware."""
56
57 if type(x) is ArrayType:
58 return exp(clip(x,exp_safe_MIN,exp_safe_MAX))
59 else:
60 return math.exp(x)
61
62 def amap(fn,*args):
63 """amap(function, sequence[, sequence, ...]) -> array.
64
65 Works like map(), but it returns an array. This is just a convenient
66 shorthand for Numeric.array(map(...))"""
67 return array(map(fn,*args))
68
69 def amin(m,axis=0):
70 """amin(m,axis=0) returns the minimum of m along dimension axis.
71 """
72 return minimum.reduce(asarray(m),axis)
73
74 def amax(m,axis=0):
75 """amax(m,axis=0) returns the maximum of m along dimension axis.
76 """
77 return maximum.reduce(asarray(m),axis)
78
79 def zeros_like(a):
80 """Return an array of zeros of the shape and typecode of a.
81
82 If you don't explicitly need the array to be zeroed, you should instead
83 use empty_like(), which is faster as it only allocates memory."""
84
85 return zeros(a.shape,a.typecode())
86
87 def empty_like(a):
88 """Return an empty (uninitialized) array of the shape and typecode of a.
89
90 Note that this does NOT initialize the returned array. If you require
91 your array to be initialized, you should use zeros_like().
92
93 This requires Numeric.empty(), which appeared in Numeric 23.7."""
94
95 return empty(a.shape,a.typecode())
96
97 def sum_flat(a):
98 """Return the sum of all the elements of a, flattened out.
99
100 It uses a.flat, and if a is not contiguous, a call to ravel(a) is made."""
101
102 if a.iscontiguous():
103 return Numeric.sum(a.flat)
104 else:
105 return Numeric.sum(ravel(a))
106
107 def mean_flat(a):
108 """Return the mean of all the elements of a, flattened out."""
109
110 return sum_flat(a)/float(size(a))
111
112 def rms_flat(a):
113 """Return the root mean square of all the elements of a, flattened out."""
114
115 return math.sqrt(sum_flat(absolute(a)**2)/float(size(a)))
116
117 def l1norm(a):
118 """Return the l1 norm of a, flattened out.
119
120 Implemented as a separate function (not a call to norm() for speed).
121
122 Ref: http://mathworld.wolfram.com/L1-Norm.html"""
123
124 return sum_flat(absolute(a))
125
126 def l2norm(a):
127 """Return the l2 norm of a, flattened out.
128
129 Implemented as a separate function (not a call to norm() for speed).
130
131 Ref: http://mathworld.wolfram.com/L2-Norm.html"""
132
133 return math.sqrt(sum_flat(absolute(a)**2))
134
135 def norm(a,p=2):
136 """norm(a,p=2) -> l-p norm of a.flat
137
138 Return the l-p norm of a, considered as a flat array. This is NOT a true
139 matrix norm, since arrays of arbitrary rank are always flattened.
140
141 p can be a number or one of the strings ('inf','Infinity') to get the
142 L-infinity norm.
143
144 Ref: http://mathworld.wolfram.com/VectorNorm.html
145 http://mathworld.wolfram.com/L-Infinity-Norm.html"""
146
147 if p in ('inf','Infinity'):
148 return max(absolute(a).flat)
149 else:
150 return (sum_flat(absolute(a)**p))**(1.0/p)
151
152 def frange(xini,xfin=None,delta=None,**kw):
153 """frange([start,] stop[, step, keywords]) -> array of floats
154
155 Return a Numeric array() containing a progression of floats. Similar to
156 arange(), but defaults to a closed interval.
157
158 frange(x0, x1) returns [x0, x0+1, x0+2, ..., x1]; start defaults to 0, and
159 the endpoint *is included*. This behavior is different from that of
160 range() and arange(). This is deliberate, since frange will probably be
161 more useful for generating lists of points for function evaluation, and
162 endpoints are often desired in this use. The usual behavior of range() can
163 be obtained by setting the keyword 'closed=0', in this case frange()
164 basically becomes arange().
165
166 When step is given, it specifies the increment (or decrement). All
167 arguments can be floating point numbers.
168
169 frange(x0,x1,d) returns [x0,x0+d,x0+2d,...,xfin] where xfin<=x1.
170
171 frange can also be called with the keyword 'npts'. This sets the number of
172 points the list should contain (and overrides the value 'step' might have
173 been given). arange() doesn't offer this option.
174
175 Examples:
176 >>> frange(3)
177 array([ 0., 1., 2., 3.])
178 >>> frange(3,closed=0)
179 array([ 0., 1., 2.])
180 >>> frange(1,6,2)
181 array([1, 3, 5])
182 >>> frange(1,6.5,npts=5)
183 array([ 1. , 2.375, 3.75 , 5.125, 6.5 ])
184 """
185
186 #defaults
187 kw.setdefault('closed',1)
188 endpoint = kw['closed'] != 0
189
190 # funny logic to allow the *first* argument to be optional (like range())
191 # This was modified with a simpler version from a similar frange() found
192 # at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472
193 if xfin == None:
194 xfin = xini + 0.0
195 xini = 0.0
196
197 if delta == None:
198 delta = 1.0
199
200 # compute # of points, spacing and return final list
201 try:
202 npts=kw['npts']
203 delta=(xfin-xini)/float(npts-endpoint)
204 except KeyError:
205 # round() gets npts right even with the vagaries of floating point.
206 npts=int(round((xfin-xini)/delta+endpoint))
207
208 return arange(npts)*delta+xini
209
210 def diagonal_matrix(diag):
211 """Return square diagonal matrix whose non-zero elements are given by the
212 input array."""
213
214 return diag*identity(len(diag))
215
216 def identity(n,rank=2,typecode='l'):
217 """identity(n,r) returns the identity matrix of shape (n,n,...,n) (rank r).
218
219 For ranks higher than 2, this object is simply a multi-index Kronecker
220 delta:
221 / 1 if i0=i1=...=iR,
222 id[i0,i1,...,iR] = -|
223 \ 0 otherwise.
224
225 Optionally a typecode may be given (it defaults to 'l').
226
227 Since rank defaults to 2, this function behaves in the default case (when
228 only n is given) like the Numeric identity function."""
229
230 iden = zeros((n,)*rank,typecode=typecode)
231 for i in range(n):
232 idx = (i,)*rank
233 iden[idx] = 1
234 return iden
235
236 def base_repr (number, base = 2, padding = 0):
237 """Return the representation of a number in any given base."""
238 chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
239 if number < base: \
240 return (padding - 1) * chars [0] + chars [int (number)]
241 max_exponent = int (math.log (number)/math.log (base))
242 max_power = long (base) ** max_exponent
243 lead_digit = int (number/max_power)
244 return chars [lead_digit] + \
245 base_repr (number - max_power * lead_digit, base, \
246 max (padding - 1, max_exponent))
247
248 def binary_repr(number, max_length = 1025):
249 """Return the binary representation of the input number as a string.
250
251 This is more efficient than using base_repr with base 2.
252
253 Increase the value of max_length for very large numbers. Note that on
254 32-bit machines, 2**1023 is the largest integer power of 2 which can be
255 converted to a Python float."""
256
257 assert number < 2L << max_length
258 shifts = map (operator.rshift, max_length * [number], \
259 range (max_length - 1, -1, -1))
260 digits = map (operator.mod, shifts, max_length * [2])
261 if not digits.count (1): return 0
262 digits = digits [digits.index (1):]
263 return ''.join (map (repr, digits)).replace('L','')
264
265 def log2(x,ln2 = math.log(2.0)):
266 """Return the log(x) in base 2.
267
268 This is a _slow_ function but which is guaranteed to return the correct
269 integer value if the input is an ineger exact power of 2."""
270
271 try:
272 bin_n = binary_repr(x)[1:]
273 except (AssertionError,TypeError):
274 return math.log(x)/ln2
275 else:
276 if '1' in bin_n:
277 return math.log(x)/ln2
278 else:
279 return len(bin_n)
280
281 def ispower2(n):
282 """Returns the log base 2 of n if n is a power of 2, zero otherwise.
283
284 Note the potential ambiguity if n==1: 2**0==1, interpret accordingly."""
285
286 bin_n = binary_repr(n)[1:]
287 if '1' in bin_n:
288 return 0
289 else:
290 return len(bin_n)
291
292 def fromfunction_kw(function, dimensions, **kwargs):
293 """Drop-in replacement for fromfunction() from Numerical Python.
294
295 Allows passing keyword arguments to the desired function.
296
297 Call it as (keywords are optional):
298 fromfunction_kw(MyFunction, dimensions, keywords)
299
300 The function MyFunction() is responsible for handling the dictionary of
301 keywords it will recieve."""
302
303 return function(tuple(indices(dimensions)),**kwargs)
304
305 #**************************** end file <numutils.py> ************************
This diff has been collapsed as it changes many lines, (855 lines changed) Show them Hide them
@@ -0,0 +1,855 b''
1 # -*- coding: utf-8 -*-
2 """
3 ultraTB.py -- Spice up your tracebacks!
4
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 ColorTB class is a solution to that problem. It colors the different parts of a
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
10
11 Installation instructions for ColorTB:
12 import sys,ultraTB
13 sys.excepthook = ultraTB.ColorTB()
14
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 and intended it for CGI programmers, but why should they have all the fun? I
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 but kind of neat, and maybe useful for long-running programs that you believe
21 are bug-free. If a crash *does* occur in that type of program you want details.
22 Give it a shot--you'll love it or you'll hate it.
23
24 Note:
25
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
28 very slow, if you happen to have a huge data structure whose string
29 representation is complex to compute. Your computer may appear to freeze for
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 with Ctrl-C (maybe hitting it more than once).
32
33 If you encounter this kind of situation often, you may want to use the
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
36 Verbose).
37
38
39 Installation instructions for ColorTB:
40 import sys,ultraTB
41 sys.excepthook = ultraTB.VerboseTB()
42
43 Note: Much of the code in this module was lifted verbatim from the standard
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
49
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
58
59 You can implement other color schemes easily, the syntax is fairly
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
62
63 $Id: ultraTB.py 589 2005-05-30 06:26:28Z fperez $"""
64
65 #*****************************************************************************
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68 #
69 # Distributed under the terms of the BSD License. The full license is in
70 # the file COPYING, distributed as part of this software.
71 #*****************************************************************************
72
73 from IPython import Release
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 Release.authors['Fernando'])
76 __license__ = Release.license
77
78 # Required modules
79 import sys, os, traceback, types, string, time
80 import keyword, tokenize, linecache, inspect, pydoc
81 from UserDict import UserDict
82
83 # IPython's own modules
84 # Modified pdb which doesn't damage IPython's readline handling
85 from IPython import Debugger
86
87 from IPython.Struct import Struct
88 from IPython.ColorANSI import *
89 from IPython.genutils import Term,uniq_stable,error,info
90
91 #---------------------------------------------------------------------------
92 # Code begins
93
94 def inspect_error():
95 """Print a message about internal inspect errors.
96
97 These are unfortunately quite common."""
98
99 error('Internal Python error in the inspect module.\n'
100 'Below is the traceback from this internal error.\n')
101
102 class TBTools:
103 """Basic tools used by all traceback printer classes."""
104
105 def __init__(self,color_scheme = 'NoColor',call_pdb=0):
106 # Whether to call the interactive pdb debugger after printing
107 # tracebacks or not
108 self.call_pdb = call_pdb
109 if call_pdb:
110 self.pdb = Debugger.Pdb()
111 else:
112 self.pdb = None
113
114 # Create color table
115 self.ColorSchemeTable = ColorSchemeTable()
116
117 # Populate it with color schemes
118 C = TermColors # shorthand and local lookup
119 self.ColorSchemeTable.add_scheme(ColorScheme(
120 'NoColor',
121 # The color to be used for the top line
122 topline = C.NoColor,
123
124 # The colors to be used in the traceback
125 filename = C.NoColor,
126 lineno = C.NoColor,
127 name = C.NoColor,
128 vName = C.NoColor,
129 val = C.NoColor,
130 em = C.NoColor,
131
132 # Emphasized colors for the last frame of the traceback
133 normalEm = C.NoColor,
134 filenameEm = C.NoColor,
135 linenoEm = C.NoColor,
136 nameEm = C.NoColor,
137 valEm = C.NoColor,
138
139 # Colors for printing the exception
140 excName = C.NoColor,
141 line = C.NoColor,
142 caret = C.NoColor,
143 Normal = C.NoColor
144 ))
145
146 # make some schemes as instances so we can copy them for modification easily:
147 self.ColorSchemeTable.add_scheme(ColorScheme(
148 'Linux',
149 # The color to be used for the top line
150 topline = C.LightRed,
151
152 # The colors to be used in the traceback
153 filename = C.Green,
154 lineno = C.Green,
155 name = C.Purple,
156 vName = C.Cyan,
157 val = C.Green,
158 em = C.LightCyan,
159
160 # Emphasized colors for the last frame of the traceback
161 normalEm = C.LightCyan,
162 filenameEm = C.LightGreen,
163 linenoEm = C.LightGreen,
164 nameEm = C.LightPurple,
165 valEm = C.LightBlue,
166
167 # Colors for printing the exception
168 excName = C.LightRed,
169 line = C.Yellow,
170 caret = C.White,
171 Normal = C.Normal
172 ))
173
174 # For light backgrounds, swap dark/light colors
175 self.ColorSchemeTable.add_scheme(ColorScheme(
176 'LightBG',
177 # The color to be used for the top line
178 topline = C.Red,
179
180 # The colors to be used in the traceback
181 filename = C.LightGreen,
182 lineno = C.LightGreen,
183 name = C.LightPurple,
184 vName = C.Cyan,
185 val = C.LightGreen,
186 em = C.Cyan,
187
188 # Emphasized colors for the last frame of the traceback
189 normalEm = C.Cyan,
190 filenameEm = C.Green,
191 linenoEm = C.Green,
192 nameEm = C.Purple,
193 valEm = C.Blue,
194
195 # Colors for printing the exception
196 excName = C.Red,
197 #line = C.Brown, # brown often is displayed as yellow
198 line = C.Red,
199 caret = C.Normal,
200 Normal = C.Normal
201 ))
202
203 self.set_colors(color_scheme)
204 self.old_scheme = color_scheme # save initial value for toggles
205
206 def set_colors(self,*args,**kw):
207 """Shorthand access to the color table scheme selector method."""
208
209 self.ColorSchemeTable.set_active_scheme(*args,**kw)
210 # for convenience, set Colors to the active scheme
211 self.Colors = self.ColorSchemeTable.active_colors
212
213 def color_toggle(self):
214 """Toggle between the currently active color scheme and NoColor."""
215
216 if self.ColorSchemeTable.active_scheme_name == 'NoColor':
217 self.ColorSchemeTable.set_active_scheme(self.old_scheme)
218 self.Colors = self.ColorSchemeTable.active_colors
219 else:
220 self.old_scheme = self.ColorSchemeTable.active_scheme_name
221 self.ColorSchemeTable.set_active_scheme('NoColor')
222 self.Colors = self.ColorSchemeTable.active_colors
223
224 #---------------------------------------------------------------------------
225 class ListTB(TBTools):
226 """Print traceback information from a traceback list, with optional color.
227
228 Calling: requires 3 arguments:
229 (etype, evalue, elist)
230 as would be obtained by:
231 etype, evalue, tb = sys.exc_info()
232 if tb:
233 elist = traceback.extract_tb(tb)
234 else:
235 elist = None
236
237 It can thus be used by programs which need to process the traceback before
238 printing (such as console replacements based on the code module from the
239 standard library).
240
241 Because they are meant to be called without a full traceback (only a
242 list), instances of this class can't call the interactive pdb debugger."""
243
244 def __init__(self,color_scheme = 'NoColor'):
245 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
246
247 def __call__(self, etype, value, elist):
248 print >> Term.cerr, self.text(etype,value,elist)
249
250 def text(self,etype, value, elist,context=5):
251 """Return a color formatted string with the traceback info."""
252
253 Colors = self.Colors
254 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
255 if elist:
256 out_string.append('Traceback %s(most recent call last)%s:' % \
257 (Colors.normalEm, Colors.Normal) + '\n')
258 out_string.extend(self._format_list(elist))
259 lines = self._format_exception_only(etype, value)
260 for line in lines[:-1]:
261 out_string.append(" "+line)
262 out_string.append(lines[-1])
263 return ''.join(out_string)
264
265 def _format_list(self, extracted_list):
266 """Format a list of traceback entry tuples for printing.
267
268 Given a list of tuples as returned by extract_tb() or
269 extract_stack(), return a list of strings ready for printing.
270 Each string in the resulting list corresponds to the item with the
271 same index in the argument list. Each string ends in a newline;
272 the strings may contain internal newlines as well, for those items
273 whose source text line is not None.
274
275 Lifted almost verbatim from traceback.py
276 """
277
278 Colors = self.Colors
279 list = []
280 for filename, lineno, name, line in extracted_list[:-1]:
281 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
282 (Colors.filename, filename, Colors.Normal,
283 Colors.lineno, lineno, Colors.Normal,
284 Colors.name, name, Colors.Normal)
285 if line:
286 item = item + ' %s\n' % line.strip()
287 list.append(item)
288 # Emphasize the last entry
289 filename, lineno, name, line = extracted_list[-1]
290 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
291 (Colors.normalEm,
292 Colors.filenameEm, filename, Colors.normalEm,
293 Colors.linenoEm, lineno, Colors.normalEm,
294 Colors.nameEm, name, Colors.normalEm,
295 Colors.Normal)
296 if line:
297 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
298 Colors.Normal)
299 list.append(item)
300 return list
301
302 def _format_exception_only(self, etype, value):
303 """Format the exception part of a traceback.
304
305 The arguments are the exception type and value such as given by
306 sys.last_type and sys.last_value. The return value is a list of
307 strings, each ending in a newline. Normally, the list contains a
308 single string; however, for SyntaxError exceptions, it contains
309 several lines that (when printed) display detailed information
310 about where the syntax error occurred. The message indicating
311 which exception occurred is the always last string in the list.
312
313 Also lifted nearly verbatim from traceback.py
314 """
315
316 Colors = self.Colors
317 list = []
318 if type(etype) == types.ClassType:
319 stype = Colors.excName + etype.__name__ + Colors.Normal
320 else:
321 stype = etype # String exceptions don't get special coloring
322 if value is None:
323 list.append( str(stype) + '\n')
324 else:
325 if etype is SyntaxError:
326 try:
327 msg, (filename, lineno, offset, line) = value
328 except:
329 pass
330 else:
331 #print 'filename is',filename # dbg
332 if not filename: filename = "<string>"
333 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
334 (Colors.normalEm,
335 Colors.filenameEm, filename, Colors.normalEm,
336 Colors.linenoEm, lineno, Colors.Normal ))
337 if line is not None:
338 i = 0
339 while i < len(line) and line[i].isspace():
340 i = i+1
341 list.append('%s %s%s\n' % (Colors.line,
342 line.strip(),
343 Colors.Normal))
344 if offset is not None:
345 s = ' '
346 for c in line[i:offset-1]:
347 if c.isspace():
348 s = s + c
349 else:
350 s = s + ' '
351 list.append('%s%s^%s\n' % (Colors.caret, s,
352 Colors.Normal) )
353 value = msg
354 s = self._some_str(value)
355 if s:
356 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
357 Colors.Normal, s))
358 else:
359 list.append('%s\n' % str(stype))
360 return list
361
362 def _some_str(self, value):
363 # Lifted from traceback.py
364 try:
365 return str(value)
366 except:
367 return '<unprintable %s object>' % type(value).__name__
368
369 #----------------------------------------------------------------------------
370 class VerboseTB(TBTools):
371 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
372 of HTML. Requires inspect and pydoc. Crazy, man.
373
374 Modified version which optionally strips the topmost entries from the
375 traceback, to be used with alternate interpreters (because their own code
376 would appear in the traceback)."""
377
378 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
379 call_pdb = 0, include_vars=1):
380 """Specify traceback offset, headers and color scheme.
381
382 Define how many frames to drop from the tracebacks. Calling it with
383 tb_offset=1 allows use of this handler in interpreters which will have
384 their own code at the top of the traceback (VerboseTB will first
385 remove that frame before printing the traceback info)."""
386 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
387 self.tb_offset = tb_offset
388 self.long_header = long_header
389 self.include_vars = include_vars
390
391 def text(self, etype, evalue, etb, context=5):
392 """Return a nice text document describing the traceback."""
393
394 # some locals
395 Colors = self.Colors # just a shorthand + quicker name lookup
396 ColorsNormal = Colors.Normal # used a lot
397 indent_size = 8 # we need some space to put line numbers before
398 indent = ' '*indent_size
399 numbers_width = indent_size - 1 # leave space between numbers & code
400 text_repr = pydoc.text.repr
401 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
402 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
403 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
404
405 # some internal-use functions
406 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
407 def nullrepr(value, repr=text_repr): return ''
408
409 # meat of the code begins
410 if type(etype) is types.ClassType:
411 etype = etype.__name__
412
413 if self.long_header:
414 # Header with the exception type, python version, and date
415 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
416 date = time.ctime(time.time())
417
418 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
419 exc, ' '*(75-len(str(etype))-len(pyver)),
420 pyver, string.rjust(date, 75) )
421 head += "\nA problem occured executing Python code. Here is the sequence of function"\
422 "\ncalls leading up to the error, with the most recent (innermost) call last."
423 else:
424 # Simplified header
425 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
426 string.rjust('Traceback (most recent call last)',
427 75 - len(str(etype)) ) )
428 frames = []
429 # Flush cache before calling inspect. This helps alleviate some of the
430 # problems with python 2.3's inspect.py.
431 linecache.checkcache()
432 # Drop topmost frames if requested
433 try:
434 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
435 except:
436
437 # FIXME: I've been getting many crash reports from python 2.3
438 # users, traceable to inspect.py. If I can find a small test-case
439 # to reproduce this, I should either write a better workaround or
440 # file a bug report against inspect (if that's the real problem).
441 # So far, I haven't been able to find an isolated example to
442 # reproduce the problem.
443 inspect_error()
444 traceback.print_exc(file=Term.cerr)
445 info('\nUnfortunately, your original traceback can not be constructed.\n')
446 return ''
447
448 # build some color string templates outside these nested loops
449 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
450 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
451 ColorsNormal)
452 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
453 (Colors.vName, Colors.valEm, ColorsNormal)
454 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
455 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
456 Colors.vName, ColorsNormal)
457 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
458 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
459 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
460 ColorsNormal)
461
462 # now, loop over all records printing context and info
463 abspath = os.path.abspath
464 for frame, file, lnum, func, lines, index in records:
465 #print '*** record:',file,lnum,func,lines,index # dbg
466 try:
467 file = file and abspath(file) or '?'
468 except OSError:
469 # if file is '<console>' or something not in the filesystem,
470 # the abspath call will throw an OSError. Just ignore it and
471 # keep the original file string.
472 pass
473 link = tpl_link % file
474 try:
475 args, varargs, varkw, locals = inspect.getargvalues(frame)
476 except:
477 # This can happen due to a bug in python2.3. We should be
478 # able to remove this try/except when 2.4 becomes a
479 # requirement. Bug details at http://python.org/sf/1005466
480 inspect_error()
481 traceback.print_exc(file=Term.cerr)
482 info("\nIPython's exception reporting continues...\n")
483
484 if func == '?':
485 call = ''
486 else:
487 # Decide whether to include variable details or not
488 var_repr = self.include_vars and eqrepr or nullrepr
489 try:
490 call = tpl_call % (func,inspect.formatargvalues(args,
491 varargs, varkw,
492 locals,formatvalue=var_repr))
493 except KeyError:
494 # Very odd crash from inspect.formatargvalues(). The
495 # scenario under which it appeared was a call to
496 # view(array,scale) in NumTut.view.view(), where scale had
497 # been defined as a scalar (it should be a tuple). Somehow
498 # inspect messes up resolving the argument list of view()
499 # and barfs out. At some point I should dig into this one
500 # and file a bug report about it.
501 inspect_error()
502 traceback.print_exc(file=Term.cerr)
503 info("\nIPython's exception reporting continues...\n")
504 call = tpl_call_fail % func
505
506 # Initialize a list of names on the current line, which the
507 # tokenizer below will populate.
508 names = []
509
510 def tokeneater(token_type, token, start, end, line):
511 """Stateful tokeneater which builds dotted names.
512
513 The list of names it appends to (from the enclosing scope) can
514 contain repeated composite names. This is unavoidable, since
515 there is no way to disambguate partial dotted structures until
516 the full list is known. The caller is responsible for pruning
517 the final list of duplicates before using it."""
518
519 # build composite names
520 if token == '.':
521 try:
522 names[-1] += '.'
523 # store state so the next token is added for x.y.z names
524 tokeneater.name_cont = True
525 return
526 except IndexError:
527 pass
528 if token_type == tokenize.NAME and token not in keyword.kwlist:
529 if tokeneater.name_cont:
530 # Dotted names
531 names[-1] += token
532 tokeneater.name_cont = False
533 else:
534 # Regular new names. We append everything, the caller
535 # will be responsible for pruning the list later. It's
536 # very tricky to try to prune as we go, b/c composite
537 # names can fool us. The pruning at the end is easy
538 # to do (or the caller can print a list with repeated
539 # names if so desired.
540 names.append(token)
541 elif token_type == tokenize.NEWLINE:
542 raise IndexError
543 # we need to store a bit of state in the tokenizer to build
544 # dotted names
545 tokeneater.name_cont = False
546
547 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
548 line = getline(file, lnum[0])
549 lnum[0] += 1
550 return line
551
552 # Build the list of names on this line of code where the exception
553 # occurred.
554 try:
555 # This builds the names list in-place by capturing it from the
556 # enclosing scope.
557 tokenize.tokenize(linereader, tokeneater)
558 except IndexError:
559 # signals exit of tokenizer
560 pass
561 except tokenize.TokenError,msg:
562 _m = ("An unexpected error occurred while tokenizing input\n"
563 "The following traceback may be corrupted or invalid\n"
564 "The error message is: %s\n" % msg)
565 error(_m)
566
567 # prune names list of duplicates, but keep the right order
568 unique_names = uniq_stable(names)
569
570 # Start loop over vars
571 lvals = []
572 if self.include_vars:
573 for name_full in unique_names:
574 name_base = name_full.split('.',1)[0]
575 if name_base in frame.f_code.co_varnames:
576 if locals.has_key(name_base):
577 try:
578 value = repr(eval(name_full,locals))
579 except:
580 value = undefined
581 else:
582 value = undefined
583 name = tpl_local_var % name_full
584 else:
585 if frame.f_globals.has_key(name_base):
586 try:
587 value = repr(eval(name_full,frame.f_globals))
588 except:
589 value = undefined
590 else:
591 value = undefined
592 name = tpl_global_var % name_full
593 lvals.append(tpl_name_val % (name,value))
594 if lvals:
595 lvals = '%s%s' % (indent,em_normal.join(lvals))
596 else:
597 lvals = ''
598
599 level = '%s %s\n' % (link,call)
600 excerpt = []
601 if index is not None:
602 i = lnum - index
603 for line in lines:
604 if i == lnum:
605 # This is the line with the error
606 pad = numbers_width - len(str(i))
607 if pad >= 3:
608 marker = '-'*(pad-3) + '-> '
609 elif pad == 2:
610 marker = '> '
611 elif pad == 1:
612 marker = '>'
613 else:
614 marker = ''
615 num = '%s%s' % (marker,i)
616 line = tpl_line_em % (num,line)
617 else:
618 num = '%*s' % (numbers_width,i)
619 line = tpl_line % (num,line)
620
621 excerpt.append(line)
622 if self.include_vars and i == lnum:
623 excerpt.append('%s\n' % lvals)
624 i += 1
625 frames.append('%s%s' % (level,''.join(excerpt)) )
626
627 # Get (safely) a string form of the exception info
628 try:
629 etype_str,evalue_str = map(str,(etype,evalue))
630 except:
631 # User exception is improperly defined.
632 etype,evalue = str,sys.exc_info()[:2]
633 etype_str,evalue_str = map(str,(etype,evalue))
634 # ... and format it
635 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
636 ColorsNormal, evalue_str)]
637 if type(evalue) is types.InstanceType:
638 for name in dir(evalue):
639 value = text_repr(getattr(evalue, name))
640 exception.append('\n%s%s = %s' % (indent, name, value))
641 # return all our info assembled as a single string
642 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
643
644 def debugger(self):
645 """Call up the pdb debugger if desired, always clean up the tb reference.
646
647 If the call_pdb flag is set, the pdb interactive debugger is
648 invoked. In all cases, the self.tb reference to the current traceback
649 is deleted to prevent lingering references which hamper memory
650 management.
651
652 Note that each call to pdb() does an 'import readline', so if your app
653 requires a special setup for the readline completers, you'll have to
654 fix that by hand after invoking the exception handler."""
655
656 if self.call_pdb:
657 if self.pdb is None:
658 self.pdb = Debugger.Pdb()
659 # the system displayhook may have changed, restore the original for pdb
660 dhook = sys.displayhook
661 sys.displayhook = sys.__displayhook__
662 self.pdb.reset()
663 while self.tb.tb_next is not None:
664 self.tb = self.tb.tb_next
665 try:
666 self.pdb.interaction(self.tb.tb_frame, self.tb)
667 except:
668 print '*** ERROR ***'
669 print 'This version of pdb has a bug and crashed.'
670 print 'Returning to IPython...'
671 sys.displayhook = dhook
672 del self.tb
673
674 def handler(self, info=None):
675 (etype, evalue, etb) = info or sys.exc_info()
676 self.tb = etb
677 print >> Term.cerr, self.text(etype, evalue, etb)
678
679 # Changed so an instance can just be called as VerboseTB_inst() and print
680 # out the right info on its own.
681 def __call__(self, etype=None, evalue=None, etb=None):
682 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
683 if etb is not None:
684 self.handler((etype, evalue, etb))
685 else:
686 self.handler()
687 self.debugger()
688
689 #----------------------------------------------------------------------------
690 class FormattedTB(VerboseTB,ListTB):
691 """Subclass ListTB but allow calling with a traceback.
692
693 It can thus be used as a sys.excepthook for Python > 2.1.
694
695 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
696
697 Allows a tb_offset to be specified. This is useful for situations where
698 one needs to remove a number of topmost frames from the traceback (such as
699 occurs with python programs that themselves execute other python code,
700 like Python shells). """
701
702 def __init__(self, mode = 'Plain', color_scheme='Linux',
703 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
704
705 # NEVER change the order of this list. Put new modes at the end:
706 self.valid_modes = ['Plain','Context','Verbose']
707 self.verbose_modes = self.valid_modes[1:3]
708
709 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
710 call_pdb=call_pdb,include_vars=include_vars)
711 self.set_mode(mode)
712
713 def _extract_tb(self,tb):
714 if tb:
715 return traceback.extract_tb(tb)
716 else:
717 return None
718
719 def text(self, etype, value, tb,context=5,mode=None):
720 """Return formatted traceback.
721
722 If the optional mode parameter is given, it overrides the current
723 mode."""
724
725 if mode is None:
726 mode = self.mode
727 if mode in self.verbose_modes:
728 # verbose modes need a full traceback
729 return VerboseTB.text(self,etype, value, tb,context=5)
730 else:
731 # We must check the source cache because otherwise we can print
732 # out-of-date source code.
733 linecache.checkcache()
734 # Now we can extract and format the exception
735 elist = self._extract_tb(tb)
736 if len(elist) > self.tb_offset:
737 del elist[:self.tb_offset]
738 return ListTB.text(self,etype,value,elist)
739
740 def set_mode(self,mode=None):
741 """Switch to the desired mode.
742
743 If mode is not specified, cycles through the available modes."""
744
745 if not mode:
746 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
747 len(self.valid_modes)
748 self.mode = self.valid_modes[new_idx]
749 elif mode not in self.valid_modes:
750 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
751 'Valid modes: '+str(self.valid_modes)
752 else:
753 self.mode = mode
754 # include variable details only in 'Verbose' mode
755 self.include_vars = (self.mode == self.valid_modes[2])
756
757 # some convenient shorcuts
758 def plain(self):
759 self.set_mode(self.valid_modes[0])
760
761 def context(self):
762 self.set_mode(self.valid_modes[1])
763
764 def verbose(self):
765 self.set_mode(self.valid_modes[2])
766
767 #----------------------------------------------------------------------------
768 class AutoFormattedTB(FormattedTB):
769 """A traceback printer which can be called on the fly.
770
771 It will find out about exceptions by itself.
772
773 A brief example:
774
775 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
776 try:
777 ...
778 except:
779 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
780 """
781 def __call__(self,etype=None,evalue=None,etb=None,
782 out=None,tb_offset=None):
783 """Print out a formatted exception traceback.
784
785 Optional arguments:
786 - out: an open file-like object to direct output to.
787
788 - tb_offset: the number of frames to skip over in the stack, on a
789 per-call basis (this overrides temporarily the instance's tb_offset
790 given at initialization time. """
791
792 if out is None:
793 out = Term.cerr
794 if tb_offset is not None:
795 tb_offset, self.tb_offset = self.tb_offset, tb_offset
796 print >> out, self.text(etype, evalue, etb)
797 self.tb_offset = tb_offset
798 else:
799 print >> out, self.text()
800 self.debugger()
801
802 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
803 if etype is None:
804 etype,value,tb = sys.exc_info()
805 self.tb = tb
806 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
807
808 #---------------------------------------------------------------------------
809 # A simple class to preserve Nathan's original functionality.
810 class ColorTB(FormattedTB):
811 """Shorthand to initialize a FormattedTB in Linux colors mode."""
812 def __init__(self,color_scheme='Linux',call_pdb=0):
813 FormattedTB.__init__(self,color_scheme=color_scheme,
814 call_pdb=call_pdb)
815
816 #----------------------------------------------------------------------------
817 # module testing (minimal)
818 if __name__ == "__main__":
819 def spam(c, (d, e)):
820 x = c + d
821 y = c * d
822 foo(x, y)
823
824 def foo(a, b, bar=1):
825 eggs(a, b + bar)
826
827 def eggs(f, g, z=globals()):
828 h = f + g
829 i = f - g
830 return h / i
831
832 print ''
833 print '*** Before ***'
834 try:
835 print spam(1, (2, 3))
836 except:
837 traceback.print_exc()
838 print ''
839
840 handler = ColorTB()
841 print '*** ColorTB ***'
842 try:
843 print spam(1, (2, 3))
844 except:
845 apply(handler, sys.exc_info() )
846 print ''
847
848 handler = VerboseTB()
849 print '*** VerboseTB ***'
850 try:
851 print spam(1, (2, 3))
852 except:
853 apply(handler, sys.exc_info() )
854 print ''
855
This diff has been collapsed as it changes many lines, (586 lines changed) Show them Hide them
@@ -0,0 +1,586 b''
1 # -*- coding: utf-8 -*-
2 #*****************************************************************************
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 #
5 # Distributed under the terms of the BSD License. The full license is in
6 # the file COPYING, distributed as part of this software.
7 #*****************************************************************************
8
9 # $Id: usage.py 578 2005-05-13 21:16:51Z fperez $
10
11 from IPython import Release
12 __author__ = '%s <%s>' % Release.authors['Fernando']
13 __license__ = Release.license
14 __version__ = Release.version
15
16 __doc__ = """
17 IPython -- An enhanced Interactive Python
18 =========================================
19
20 A Python shell with automatic history (input and output), dynamic object
21 introspection, easier configuration, command completion, access to the system
22 shell and more.
23
24 IPython can also be embedded in running programs. See EMBEDDING below.
25
26
27 USAGE
28 ipython [options] files
29
30 If invoked with no options, it executes all the files listed in
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
33 different from standard Python, which when called as python -i will
34 only execute one file and will ignore your configuration setup.
35
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
38 your ipythonrc configuration file for details on those. This file
39 typically installed in the $HOME/.ipython directory.
40
41 For Windows users, $HOME resolves to C:\\Documents and
42 Settings\\YourUserName in most instances, and _ipython is used instead
43 of .ipython, since some Win32 programs have problems with dotted names
44 in directories.
45
46 In the rest of this text, we will refer to this directory as
47 IPYTHONDIR.
48
49
50 SPECIAL THREADING OPTIONS
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-
53 ization of ipython itself, before the normal option-handling mechanism
54 is active.
55
56 -gthread, -qthread, -wthread, -pylab
57
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
60 other position). They provide threading support for the GTK, QT
61 and WXWidgets toolkits, and for the matplotlib library.
62
63 With any of the first three options, IPython starts running a
64 separate thread for the graphical toolkit's operation, so that
65 you can open and control graphical elements from within an
66 IPython command line, without blocking. All three provide
67 essentially the same functionality, respectively for GTK, QT and
68 WXWidgets (via their Python interfaces).
69
70 If -pylab is given, IPython loads special support for the mat-
71 plotlib library (http://matplotlib.sourceforge.net), allowing
72 interactive usage of any of its backends as defined in the
73 user's .matplotlibrc file. It automatically activates GTK, QT
74 or WX threading for IPyhton if the choice of matplotlib backend
75 requires it. It also modifies the %run command to correctly
76 execute (without blocking) any matplotlib-based script which
77 calls show() at the end.
78
79 -tk The -g/q/wthread options, and -pylab (if matplotlib is
80 configured to use GTK, QT or WX), will normally block Tk
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
83 a dead window, and possibly cause the Python interpreter to
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
86 above (-gthread, -qthread, -wthread or -pylab).
87
88 If -tk is given, IPython will try to coordinate Tk threading
89 with GTK, QT or WX. This is however potentially unreliable, and
90 you will have to test on your platform and Python configuration
91 to determine whether it works for you. Debian users have
92 reported success, apparently due to the fact that Debian builds
93 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
94 other Linux environments (such as Fedora Core 2/3), this option
95 has caused random crashes and lockups of the Python interpreter.
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
98 available.
99
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
102 do some experiments before relying on it for regular work.
103
104 A WARNING ABOUT SIGNALS AND THREADS
105
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
108 interrupt long-running Python code via Ctrl-C. IPython can not pass
109 the KeyboardInterrupt exception (or the underlying SIGINT) across
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)
112 mechanism.
113
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
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
118 the IPython sources, look at the Shell.py module, and in particular at
119 the runcode() method.
120
121 REGULAR OPTIONS
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
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 |.
126
127 Most options can also be set from your ipythonrc configuration file.
128 See the provided examples for assistance. Options given on the comman-
129 dline override the values set in the ipythonrc file.
130
131 All options with a no| prepended can be specified in ’no’ form (-noop-
132 tion instead of -option) to turn the feature off.
133
134 -h, --help
135 Show summary of options.
136
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-
139 port for the matplotlib library (http://matplotlib.source-
140 forge.net), allowing interactive usage of any of its backends as
141 defined in the user’s .matplotlibrc file. It automatically
142 activates GTK or WX threading for IPyhton if the choice of mat-
143 plotlib backend requires it. It also modifies the @run command
144 to correctly execute (without blocking) any matplotlib-based
145 script which calls show() at the end.
146
147 -no|autocall
148 Make IPython automatically call any callable object even if you
149 didn’t type explicit parentheses. For example, ’str 43’ becomes
150 ’str(43)’ automatically.
151
152 -no|autoindent
153 Turn automatic indentation on/off.
154
155 -no|automagic
156 Make magic commands automatic (without needing their first char-
157 acter to be @). Type @magic at the IPython prompt for more
158 information.
159
160 -no|autoparens
161 Make IPython automatically call any callable object even if you
162 didn’t type explicit parentheses. For example, ’str 43’ becomes
163 ’str(43)’ automatically.
164
165 -no|banner
166 Print the intial information banner (default on).
167
168 -c <command>
169 Execute the given command string, and set sys.argv to [’c’].
170 This is similar to the -c option in the normal Python inter-
171 preter.
172
173 -cache_size|cs <n>
174 Size of the output cache (maximum number of entries to hold in
175 memory). The default is 1000, you can change it permanently in
176 your config file. Setting it to 0 completely disables the
177 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
179 issued). This limit is defined because otherwise you’ll spend
180 more time re-flushing a too small cache than working.
181
182 -classic|cl
183 Gives IPython a similar feel to the classic Python prompt.
184
185 -colors <scheme>
186 Color scheme for prompts and exception reporting. Currently
187 implemented: NoColor, Linux, and LightBG.
188
189 -no|color_info
190 IPython can display information about objects via a set of func-
191 tions, and optionally can use colors for this, syntax highlight-
192 ing source code and various other elements. However, because
193 this information is passed through a pager (like ’less’) and
194 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
196 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
198 7.2 doesn’t.
199
200 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-
202 actively for testing.
203
204 -no|confirm_exit
205 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
207 magic functions @Exit or @Quit you can force a direct exit,
208 bypassing any confirmation.
209
210 -no|debug
211 Show information about the loading process. Very useful to pin
212 down problems with your configuration files or to get details
213 about session restores.
214
215 -no|deep_reload
216 IPython can use the deep_reload module which reloads changes in
217 modules recursively (it replaces the reload() function, so you
218 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
220 default reload() function does not.
221
222 When deep_reload is off, IPython will use the normal reload(),
223 but deep_reload will still be available as dreload(). This fea-
224 ture is off by default [which means that you have both normal
225 reload() and dreload()].
226
227 -editor <name>
228 Which editor to use with the @edit command. By default, IPython
229 will honor your EDITOR environment variable (if not set, vi is
230 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
232 code snippets, you may want to use a small, lightweight editor
233 here (in case your default EDITOR is something like Emacs).
234
235 -ipythondir <name>
236 The name of your IPython configuration directory IPYTHONDIR.
237 This can also be specified through the environment variable
238 IPYTHONDIR.
239
240 -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
242 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
244 executed with option -logplay (see below).
245
246 -logfile|lf
247 Specifu the name of your logfile.
248
249 -logplay|lp
250 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
252 run the logfile). With -logplay, IPython will try to reconstruct
253 the previous working environment in full, not just execute the
254 commands in the logfile.
255 When a session is restored, logging is automatically turned on
256 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
258 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
260 from the beginning every time.
261
262 Caveats: there are limitations in this option. The history vari-
263 ables _i*,_* and _dh don’t get restored properly. In the future
264 we will try to implement full session saving by writing and
265 retrieving a failed because of inherent limitations of Python’s
266 Pickle module, so this may have to wait.
267
268 -no|messages
269 Print messages which IPython collects about its startup process
270 (default on).
271
272 -no|pdb
273 Automatically call the pdb debugger after every uncaught excep-
274 tion. If you are used to debugging using pdb, this puts you
275 automatically inside of it after any call (either in IPython or
276 in code called by it) which triggers an exception which goes
277 uncaught.
278
279 -no|pprint
280 IPython can optionally use the pprint (pretty printer) module
281 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-
283 manently in your config file (default off).
284
285 -profile|p <name>
286 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
288 and load multiple config files for different tasks, especially
289 if you use the include option of config files. You can keep a
290 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
291 which include this one and load extra things for particular
292 tasks. For example:
293
294 1) $HOME/.ipython/ipythonrc : load basic things you always want.
295 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
296 related modules.
297 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
298 plotting modules.
299
300 Since it is possible to create an endless loop by having circu-
301 lar file inclusions, IPython will stop if it reaches 15 recur-
302 sive inclusions.
303
304 -prompt_in1|pi1 <string>
305 Specify the string used for input prompts. Note that if you are
306 using numbered prompts, the number is represented with a ’\#’ in
307 the string. Don’t forget to quote strings with spaces embedded
308 in them. Default: ’In [\#]:’.
309
310 Most bash-like escapes can be used to customize IPython’s
311 prompts, as well as a few additional ones which are IPython-spe-
312 cific. All valid prompt escapes are described in detail in the
313 Customization section of the IPython HTML/PDF manual.
314
315 -prompt_in2|pi2 <string>
316 Similar to the previous option, but used for the continuation
317 prompts. The special sequence ’\D’ is similar to ’\#’, but with
318 all digits replaced dots (so you can have your continuation
319 prompt aligned with your input prompt). Default: ’ .\D.:’
320 (note three spaces at the start for alignment with ’In [\#]’).
321
322 -prompt_out|po <string>
323 String used for output prompts, also uses numbers like
324 prompt_in1. Default: ’Out[\#]:’.
325
326 -quick Start in bare bones mode (no config file loaded).
327
328 -rcfile <name>
329 Name of your IPython resource configuration file. normally
330 IPython loads ipythonrc (from current directory) or
331 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
332 IPython starts with a bare bones configuration (no modules
333 loaded at all).
334
335 -no|readline
336 Use the readline library, which is needed to support name com-
337 pletion and command history, among other things. It is enabled
338 by default, but may cause problems for users of X/Emacs in
339 Python comint or shell buffers.
340
341 Note that emacs ’eterm’ buffers (opened with M-x term) support
342 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
343 shell and C-c !) buffers do not.
344
345 -screen_length|sl <n>
346 Number of lines of your screen. This is used to control print-
347 ing of very long strings. Strings longer than this number of
348 lines will be sent through a pager instead of directly printed.
349
350 The default value for this is 0, which means IPython will auto-
351 detect your screen size every time it needs to print certain
352 potentially long strings (this doesn’t change the behavior of
353 the ’print’ keyword, it’s only triggered internally). If for
354 some reason this isn’t working well (it needs curses support),
355 specify it yourself. Otherwise don’t change the default.
356
357 -separate_in|si <string>
358 Separator before input prompts. Default ’0.
359
360 -separate_out|so <string>
361 Separator before output prompts. Default: 0 (nothing).
362
363 -separate_out2|so2 <string>
364 Separator after output prompts. Default: 0 (nothing).
365
366 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
367 Simply removes all input/output separators.
368
369 -upgrade
370 Allows you to upgrade your IPYTHONDIR configuration when you
371 install a new version of IPython. Since new versions may
372 include new command lines options or example files, this copies
373 updated ipythonrc-type files. However, it backs up (with a .old
374 extension) all files which it overwrites so that you can merge
375 back any custimizations you might have in your personal files.
376
377 -Version
378 Print version information and exit.
379
380 -xmode <modename>
381 Mode for exception reporting. The valid modes are Plain, Con-
382 text, and Verbose.
383
384 - Plain: similar to python’s normal traceback printing.
385
386 - Context: prints 5 lines of context source code around each
387 line in the traceback.
388
389 - Verbose: similar to Context, but additionally prints the vari-
390 ables currently visible where the exception happened (shortening
391 their strings if too long). This can potentially be very slow,
392 if you happen to have a huge data structure whose string repre-
393 sentation is complex to compute. Your computer may appear to
394 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
396 once).
397
398
399 EMBEDDING
400 It is possible to start an IPython instance inside your own Python pro-
401 grams. In the documentation example files there are some illustrations
402 on how to do this.
403
404 This feature allows you to evalutate dynamically the state of your
405 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
407 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.
409 """
410
411 cmd_line_usage = __doc__
412
413 #---------------------------------------------------------------------------
414 interactive_usage = """
415 IPython -- An enhanced Interactive Python
416 =========================================
417
418 IPython offers a combination of convenient shell features, special commands
419 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
421 replacement for the standard Python interpreter, while offering vastly
422 improved functionality and flexibility.
423
424 At your system command line, type 'ipython -help' to see the command line
425 options available. This document only describes interactive features.
426
427 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
429 will quickly occur.
430
431 MAIN FEATURES
432
433 * 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
435 type 'help' (no quotes) to access it.
436
437 * Magic commands: type %magic for information on the magic subsystem.
438
439 * System command aliases, via the %alias command or the ipythonrc config file.
440
441 * Dynamic object information:
442
443 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
445 snipped in the center for brevity.
446
447 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
449 pager if longer than the screen, printed otherwise.
450
451 The ?/?? system gives access to the full source code for any object (if
452 available), shows function prototypes and other useful information.
453
454 If you just want to see an object's docstring, type '%pdoc object' (without
455 quotes, and without % if you have automagic on).
456
457 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,
459 type os.path.abspath??. The magic functions %pdef, %source and %file operate
460 similarly.
461
462 * Completion in the local namespace, by typing TAB at the prompt.
463
464 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
466 no unambiguous one. It will also complete filenames in the current directory.
467
468 This feature requires the readline and rlcomplete modules, so it won't work
469 if your Python lacks readline support (such as under Windows).
470
471 * Search previous command history in two ways (also requires readline):
472
473 - 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
475 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
476 normal arrow keys.
477
478 - 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
480 much as it can.
481
482 * Persistent command history across sessions (readline required).
483
484 * Logging of input with the ability to save and restore a working session.
485
486 * System escape with !. Typing !ls will run 'ls' in the current directory.
487
488 * 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.
490
491 * Verbose and colored exception traceback printouts. See the magic xmode and
492 xcolor functions for details (just type %magic).
493
494 * Input caching system:
495
496 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
498 key recall).
499
500 The following GLOBAL variables always exist (so don't overwrite them!):
501 _i: stores previous input.
502 _ii: next previous.
503 _iii: next-next previous.
504 _ih : a list of all input _ih[n] is the input from line n.
505
506 Additionally, global variables named _i<n> are dynamically created (<n>
507 being the prompt counter), such that _i<n> == _ih[<n>]
508
509 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
510
511 You can create macros which contain multiple input lines from this history,
512 for later re-execution, with the %macro function.
513
514 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
516 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.
518
519 * Output caching system:
520
521 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
523 (NOT assignments, for example) are cached. If you are familiar with
524 Mathematica, IPython's _ variables behave exactly like Mathematica's %
525 variables.
526
527 The following GLOBAL variables always exist (so don't overwrite them!):
528 _ (one underscore): previous output.
529 __ (two underscores): next previous.
530 ___ (three underscores): next-next previous.
531
532 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>.
534
535 Finally, a global dictionary named _oh exists with entries for all lines
536 which generated output.
537
538 * Directory history:
539
540 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.
542
543 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
544
545 1. Auto-parentheses
546 Callable objects (i.e. functions, methods, etc) can be invoked like
547 this (notice the commas between the arguments):
548 >>> callable_ob arg1, arg2, arg3
549 and the input will be translated to this:
550 --> callable_ob(arg1, arg2, arg3)
551 You can force auto-parentheses by using '/' as the first character
552 of a line. For example:
553 >>> /globals # becomes 'globals()'
554 Note that the '/' MUST be the first character on the line! This
555 won't work:
556 >>> print /globals # syntax error
557
558 In most cases the automatic algorithm should work, so you should
559 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
561 parenthesis will confuse IPython):
562 In [1]: zip (1,2,3),(4,5,6) # won't work
563 but this will work:
564 In [2]: /zip (1,2,3),(4,5,6)
565 ------> zip ((1,2,3),(4,5,6))
566 Out[2]= [(1, 4), (2, 5), (3, 6)]
567
568 IPython tells you that it has altered your command line by
569 displaying the new command line preceded by -->. e.g.:
570 In [18]: callable list
571 -------> callable (list)
572
573 2. Auto-Quoting
574 You can force auto-quoting of a function's arguments by using ',' as
575 the first character of a line. For example:
576 >>> ,my_function /home/me # becomes my_function("/home/me")
577
578 If you use ';' instead, the whole argument is quoted as a single
579 string (while ',' splits on whitespace):
580 >>> ,my_function a b c # becomes my_function("a","b","c")
581 >>> ;my_function a b c # becomes my_function("a b c")
582
583 Note that the ',' MUST be the first character on the line! This
584 won't work:
585 >>> x = ,my_function /home/me # syntax error
586 """
@@ -0,0 +1,29 b''
1 include README_Windows.txt
2 include win32_manual_post_install.py
3
4 graft scripts
5
6 graft setupext
7
8 graft IPython/UserConfig
9
10 graft doc
11 exclude doc/*.1
12 exclude doc/*.lyx
13 exclude doc/ChangeLog.*
14 exclude doc/#*
15 exclude doc/magic.tex
16 exclude doc/update_magic.sh
17 exclude doc/update_version.sh
18 exclude doc/manual_base*
19 exclude doc/manual/WARNINGS
20 exclude doc/manual/*.aux
21 exclude doc/manual/*.log
22 exclude doc/manual/*.out
23 exclude doc/manual/*.pl
24 exclude doc/manual/*.tex
25
26 global-exclude *~
27 global-exclude *.flc
28 global-exclude *.pyc
29 global-exclude .dircopy.log
@@ -0,0 +1,12 b''
1 Please see the doc/ directory for full manuals and other documents. The manual is
2 prepared using the LyX system (www.lyx.org), but in the doc/manual directory
3 you'll find HTML and PDF versions.
4
5 These manuals normally get installed to $PREFIX/share/doc/ipython-VERSION, unless you
6 redirect the installer via a --prefix/--home option. Normally, $PREFIX is
7 /usr, but your Python may be installed elsewhere. You can see its value by
8 running:
9
10 python -c "import sys;print sys.prefix"
11
12 # testing notes...
@@ -0,0 +1,42 b''
1 Notes for Windows Users
2 =======================
3
4 These are just minimal notes. The manual contains more detailed
5 information.
6
7 Requirements
8 ------------
9
10 IPython runs under (as far as the Windows family is concerned):
11
12 - Windows XP (I think WinNT/2000 are ok): works well. It needs:
13
14 * PyWin32, the win32 Python extensions from
15 http://starship.python.net/crew/mhammond.
16
17 * Gary Bishop's readline from
18 http://sourceforge.net/projects/uncpythontools.
19
20 * This in turn requires Tomas Heller's ctypes from
21 http://starship.python.net/crew/theller/ctypes.
22
23 - Windows 95/98/ME: I have no idea. It should work, but I can't test.
24
25 - CygWin environments should work, they are basically Posix.
26
27 It needs Python 2.2 or newer.
28
29
30 Installation
31 ------------
32
33 Double-click the supplied .exe installer file. If all goes well, that's all
34 you need to do. You should now have an IPython entry in your Start Menu.
35
36 In case the automatic installer does not work for some reason, you can
37 download the ipython-XXX.tar.gz file, which contains the full IPython source
38 distribution (the popular WinZip can read .tar.gz files). After uncompressing
39 the archive, you can install it at a command terminal just like any other
40 Python module, by using python setup.py install'. After this completes, you
41 can run the supplied win32_manual_post_install.py script which will add
42 the relevant shortcuts to your startup menu.
@@ -0,0 +1,70 b''
1 ipython (0.6.4-1) unstable; urgency=low
2
3 * Fix dpatch dependency (Closes: #280505)
4
5 -- Fernando Perez <fperez@colorado.edu> Wed Nov 17 22:54:23 MST 2004
6
7 ipython (0.6.3-1) unstable; urgency=low
8
9 * New upstream release (Closes: #262244, #252525)
10
11 -- Jack Moffitt <jack@xiph.org> Wed, 22 Sep 2004 21:39:38 -0600
12
13 ipython (0.6.0-1) unstable; urgency=low
14
15 * New upstream release
16
17 -- Jack Moffitt <jack@xiph.org> Sun, 9 May 2004 17:38:00 +0200
18
19 ipython (0.4.0-1.1) unstable; urgency=low
20
21 * Non maintainer upload with maintainer consensus.
22 * Updated buil-dep to depend on python-2.3 (Closes: #206653)
23 * Included encoding comment string in modules under IPython to
24 avoid python2.3 Warnigs (upstream noticed).
25
26 -- Marco Presi (Zufus) <zufus@debian.org> Mon, 25 Aug 2003 19:02:20 +0200
27
28 ipython (0.4.0-1) unstable; urgency=low
29
30 * New upstream release (Closes #195215)
31 * Updated Build-Depends (Closes #200021)
32
33 -- Jack Moffitt <jack@xiph.org> Fri, 25 Jul 2003 10:16:12 -0600
34
35 ipython (0.2.15pre3-4) unstable; urgency=low
36
37 * Add python-dev Build-Depends (Closes: #189901)
38
39 -- Jack Moffitt <jack@babyjesus.cantcode.com> Mon, 12 May 2003 23:33:43 -0600
40
41 ipython (0.2.15pre3-3) unstable; urgency=low
42
43 * Fix for accidently converting home directory files' line ends
44 instead of just the appropriate ipython configuration files
45 (Closes: #189042)
46
47 -- Jack Moffitt <jack@xiph.org> Mon, 14 Apr 2003 21:18:18 -0600
48
49 ipython (0.2.15pre3-2) unstable; urgency=low
50
51 * Added text of the PSF license to debian/copyright.
52
53 -- Jack Moffitt <jack@xiph.org> Sat, 5 Apr 2003 11:41:31 -0700
54
55 ipython (0.2.15pre3-1) unstable; urgency=low
56
57 * Updated documentation to point to the new homepage -
58 http://ipython.scipy.org
59 * Removed doc/COPYING and doc/GNU-LGPL to fix lintian warnings
60 * Public release ready (Closes: #185789)
61
62 -- Jack Moffitt <jack@xiph.org> Tue, 1 Apr 2003 20:53:31 -0700
63
64 ipython (0.2.15pre3-0a) unstable; urgency=low
65
66 * Initial Release.
67 * This is my first Debian package
68
69 -- Jack Moffitt <jack@xiph.org> Wed, 12 Mar 2003 21:04:22 -0700
70
@@ -0,0 +1,1 b''
1 4
@@ -0,0 +1,21 b''
1 Source: ipython
2 Section: devel
3 Priority: optional
4 Maintainer: Jack Moffitt <jack@xiph.org>
5 Build-Depends-Indep: debhelper (>> 4.1.65), dpatch, python-dev
6 Standards-Version: 3.6.1
7
8 Package: ipython
9 Architecture: all
10 Depends: ${python:Depends}
11 Recommends: python-numeric, python-numeric-ext
12 Description: An enhanced interactive Python shell
13 IPython is an enhanced interactive Python shell. It can be used as a
14 replacement for the standard Python shell, or it can be used as a
15 complete working environment for scientific computing (like Matlab or
16 Mathematica) when paired with the standard Python scientific and
17 numerical tools. It supports dynamic object introspections, numbered
18 input/output prompts, a macro system, session logging, session
19 restoring, complete system shell access, verbose and colored
20 traceback reports, auto-parentheses, auto-quoting, and is
21 embeddedable in other Python programs.
@@ -0,0 +1,204 b''
1 This package was debianized by Jack Moffitt <jack@xiph.org> on
2 Wed, 12 Mar 2003 20:38:14 -0700.
3
4 It was downloaded from http://ipython.scipy.org/
5
6 Upstream Author: Fernando Perez <fperez@colorado.edu>,
7 Janko Hauser <jhauser@zscout.de>,
8 Nathaniel Gray <n8gray@caltech.edu>
9
10 Copyright:
11
12 Most IPython code is copyright (C) 2001-2004 by Fernando Perez, Janko Hauser,
13 and Nathaniel Gray. All code is licensed under a BSD-type License except as
14 explicitly mentioned below. The full IPython license is:
15
16 IPython is released under a BSD-type license.
17
18 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
19
20 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
21 <n8gray@caltech.edu>.
22
23 All rights reserved.
24
25 Redistribution and use in source and binary forms, with or without
26 modification, are permitted provided that the following conditions are met:
27
28 a. Redistributions of source code must retain the above copyright notice,
29 this list of conditions and the following disclaimer.
30
31 b. Redistributions in binary form must reproduce the above copyright
32 notice, this list of conditions and the following disclaimer in the
33 documentation and/or other materials provided with the distribution.
34
35 c. Neither the name of the copyright holders nor the names of any
36 contributors to this software may be used to endorse or promote products
37 derived from this software without specific prior written permission.
38
39
40 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
41 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
44 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
46 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
47 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
50 DAMAGE.
51
52
53 DPyGetOpt.py is copyright (C) 2001 by Bill Bumgarner <bbum@friday.com>
54 and is licensed under the MIT license, reproduced below:
55
56 Permission is hereby granted, free of charge, to any person obtaining a copy
57 of this software and associated documentation files (the "Software"), to
58 deal in the Software without restriction, including without limitation the
59 rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
60 sell copies of the Software, and to permit persons to whom the Software is
61 furnished to do so, subject to the following conditions:
62
63 The above copyright notice and this permission notice shall be included in
64 all copies or substantial portions of the Software.
65
66 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
67 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
68 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
69 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
70 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
71 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
72 IN THE SOFTWARE.
73
74 FlexCompleter.py is copyright (C) 2001 by the Python Software
75 Foundation and licensed under the terms of the Python Software
76 Foundation License, reproduced below:
77
78 A. HISTORY OF THE SOFTWARE
79 ==========================
80
81 Python was created in the early 1990s by Guido van Rossum at Stichting
82 Mathematisch Centrum (CWI) in the Netherlands as a successor of a
83 language called ABC. Guido is Python's principal author, although it
84 includes many contributions from others. The last version released
85 from CWI was Python 1.2. In 1995, Guido continued his work on Python
86 at the Corporation for National Research Initiatives (CNRI) in Reston,
87 Virginia where he released several versions of the software. Python
88 1.6 was the last of the versions released by CNRI. In 2000, Guido and
89 the Python core development team moved to BeOpen.com to form the
90 BeOpen PythonLabs team. Python 2.0 was the first and only release
91 from BeOpen.com.
92
93 Following the release of Python 1.6, and after Guido van Rossum left
94 CNRI to work with commercial software developers, it became clear that
95 the ability to use Python with software available under the GNU Public
96 License (GPL) was very desirable. CNRI and the Free Software
97 Foundation (FSF) interacted to develop enabling wording changes to the
98 Python license. Python 1.6.1 is essentially the same as Python 1.6,
99 with a few minor bug fixes, and with a different license that enables
100 later versions to be GPL-compatible. Python 2.1 is a derivative work
101 of Python 1.6.1, as well as of Python 2.0.
102
103 After Python 2.0 was released by BeOpen.com, Guido van Rossum and the
104 other PythonLabs developers joined Digital Creations. All
105 intellectual property added from this point on, starting with Python
106 2.1 and its alpha and beta releases, is owned by the Python Software
107 Foundation (PSF), a non-profit modeled after the Apache Software
108 Foundation. See http://www.python.org/psf/ for more information about
109 the PSF.
110
111 Thanks to the many outside volunteers who have worked under Guido's
112 direction to make these releases possible.
113
114
115 B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
116 ===============================================================
117
118 PSF LICENSE AGREEMENT
119 ---------------------
120
121 1. This LICENSE AGREEMENT is between the Python Software Foundation
122 ("PSF"), and the Individual or Organization ("Licensee") accessing and
123 otherwise using Python 2.1 software in source or binary form and its
124 associated documentation.
125
126 2. Subject to the terms and conditions of this License Agreement, PSF
127 hereby grants Licensee a nonexclusive, royalty-free, world-wide
128 license to reproduce, analyze, test, perform and/or display publicly,
129 prepare derivative works, distribute, and otherwise use Python 2.1
130 alone or in any derivative version, provided, however, that PSF's
131 License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
132 2001 Python Software Foundation; All Rights Reserved" are retained in
133 Python 2.1 alone or in any derivative version prepared by Licensee.
134
135 3. In the event Licensee prepares a derivative work that is based on
136 or incorporates Python 2.1 or any part thereof, and wants to make
137 the derivative work available to others as provided herein, then
138 Licensee hereby agrees to include in any such work a brief summary of
139 the changes made to Python 2.1.
140
141 4. PSF is making Python 2.1 available to Licensee on an "AS IS"
142 basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
143 IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
144 DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
145 FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.1 WILL NOT
146 INFRINGE ANY THIRD PARTY RIGHTS.
147
148 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
149 2.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A
150 RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.1, OR
151 ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
152
153 6. This License Agreement will automatically terminate upon a material
154 breach of its terms and conditions.
155
156 7. This License Agreement shall be governed by the federal
157 intellectual property law of the United States, including without
158 limitation the federal copyright law, and, to the extent such
159 U.S. federal law does not apply, by the law of the Commonwealth of
160 Virginia, excluding Virginia's conflict of law provisions.
161 Notwithstanding the foregoing, with regard to derivative works based
162 on Python 1.6.1 that incorporate non-separable material that was
163 previously distributed under the GNU General Public License (GPL), the
164 law of the Commonwealth of Virginia shall govern this License
165 Agreement only as to issues arising under or with respect to
166 Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
167 License Agreement shall be deemed to create any relationship of
168 agency, partnership, or joint venture between CNRI and Licensee. This
169 License Agreement does not grant permission to use CNRI trademarks or
170 trade name in a trademark sense to endorse or promote products or
171 services of Licensee, or any third party.
172
173 8. By clicking on the "ACCEPT" button where indicated, or by copying,
174 installing or otherwise using Python 1.6.1, Licensee agrees to be
175 bound by the terms and conditions of this License Agreement.
176
177 ACCEPT
178
179
180 CWI PERMISSIONS STATEMENT AND DISCLAIMER
181 ----------------------------------------
182
183 Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
184 The Netherlands. All rights reserved.
185
186 Permission to use, copy, modify, and distribute this software and its
187 documentation for any purpose and without fee is hereby granted,
188 provided that the above copyright notice appear in all copies and that
189 both that copyright notice and this permission notice appear in
190 supporting documentation, and that the name of Stichting Mathematisch
191 Centrum or CWI not be used in advertising or publicity pertaining to
192 distribution of the software without specific, written prior
193 permission.
194
195 STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
196 THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
197 FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
198 FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
199 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
200 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
201 OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
202
203 Itpl.py is copyright (C) 2001 Ka-Ping Yee <ping@lfw.org> and licensed
204 under the MIT license reproduced above.
@@ -0,0 +1,14 b''
1 Document: ipython
2 Title: IPython Manual
3 Author: Fernando Perez <fperez@colorado.edu>
4 Abstract: Full documentation on all features of IPython.
5 Section: devel
6
7 Format: pdf
8 Files: /usr/share/doc/ipython/ipython.pdf
9
10 Format: HTML
11 Index: /usr/share/doc/ipython/manual/index.html
12 Files: /usr/share/doc/ipython/manual/*.html
13
14
@@ -0,0 +1,13 b''
1 #!/bin/sh
2 set -e
3
4 OLD_MODDIR=/usr/lib/python2.2/site-packages/IPython
5
6 if [ $1 = "configure" ]; then
7 if [ -d $OLD_MODDIR ];then
8 echo "Removing old python2.2 modules"
9 rm -fr $OLD_MODDIR >&2
10 fi
11 fi
12
13 #DEBHELPER#
@@ -0,0 +1,98 b''
1 #!/usr/bin/make -f
2 # Sample debian/rules that uses debhelper.
3 # GNU copyright 1997 to 1999 by Joey Hess.
4
5 # Uncomment this to turn on verbose mode.
6 #export DH_VERBOSE=1
7
8
9
10
11 CFLAGS = -Wall -g
12
13 ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
14 CFLAGS += -O0
15 else
16 CFLAGS += -O2
17 endif
18 ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS)))
19 INSTALL_PROGRAM += -s
20 endif
21
22 configure: configure-stamp
23 configure-stamp:
24 dh_testdir
25
26 python setup.py config
27
28 touch configure-stamp
29
30
31 build: build-stamp
32
33 build-stamp: configure-stamp
34 dh_testdir
35
36 python setup.py build
37
38 touch build-stamp
39
40 clean:
41 dh_testdir
42 dh_testroot
43 rm -f build-stamp configure-stamp
44
45 -python setup.py clean --all
46 rm -f setupext/*.pyc
47
48 dh_clean
49
50 install: build
51 dh_testdir
52 dh_testroot
53 dh_clean -k
54 dh_installdirs
55
56 python setup.py install --prefix $(CURDIR)/debian/ipython/usr
57
58 # remove extra license docs that get installed
59 rm -f $(CURDIR)/debian/ipython/usr/share/doc/ipython/COPYING
60 #rm -f $(CURDIR)/debian/ipython/usr/share/doc/ipython/GNU-LGPL
61
62 # change permission on scripts
63 chmod 755 $(CURDIR)/debian/ipython/usr/share/doc/ipython/examples/example-embed.py
64 chmod 755 $(CURDIR)/debian/ipython/usr/share/doc/ipython/examples/example-gnuplot.py
65
66 binary-indep: build install
67 dh_testdir
68 dh_testroot
69 dh_installchangelogs doc/ChangeLog
70 dh_installdocs
71 # dh_installexamples
72 dh_install
73 # dh_installmenu
74 # dh_installdebconf
75 # dh_installlogrotate
76 # dh_installemacsen
77 # dh_installpam
78 # dh_installmime
79 # dh_installinit
80 # dh_installcron
81 # dh_installinfo
82 dh_installman doc/ipython.1.gz doc/pycolor.1.gz
83 dh_compress
84 dh_fixperms
85 dh_python
86 # dh_makeshlibs
87 dh_installdeb
88 # dh_shlibdeps
89 dh_gencontrol
90 dh_md5sums
91 dh_builddeb
92
93 # Build architecture-dependent files here.
94 binary-arch: build install
95 # We have nothing to do by default.
96
97 binary: binary-indep binary-arch
98 .PHONY: build clean binary-indep binary-arch binary install configure
@@ -0,0 +1,52 b''
1 IPython copyright and licensing notes
2 =====================================
3
4 Unless indicated otherwise, files in this project are covered by a BSD-type
5 license, included below.
6
7 Individual authors are the holders of the copyright for their code and are
8 listed in each file.
9
10 Some files (DPyGetOpt.py, for example) may be licensed under different
11 conditions. Ultimately each file indicates clearly the conditions under which
12 its author/authors have decided to publish the code.
13
14
15 IPython license
16 ---------------
17
18 IPython is released under a BSD-type license.
19
20 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
21
22 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
23 <n8gray@caltech.edu>.
24
25 All rights reserved.
26
27 Redistribution and use in source and binary forms, with or without
28 modification, are permitted provided that the following conditions are met:
29
30 a. Redistributions of source code must retain the above copyright notice,
31 this list of conditions and the following disclaimer.
32
33 b. Redistributions in binary form must reproduce the above copyright
34 notice, this list of conditions and the following disclaimer in the
35 documentation and/or other materials provided with the distribution.
36
37 c. Neither the name of the copyright holders nor the names of any
38 contributors to this software may be used to endorse or promote products
39 derived from this software without specific prior written permission.
40
41
42 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
43 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
46 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
48 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
49 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
52 DAMAGE.
This diff has been collapsed as it changes many lines, (4243 lines changed) Show them Hide them
@@ -0,0 +1,4243 b''
1 2005-06-08 Fernando Perez <fperez@colorado.edu>
2
3 * IPython/iplib.py (write/write_err): Add methods to abstract all
4 I/O a bit more.
5
6 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
7 warning, reported by Aric Hagberg, fix by JD Hunter.
8
9 2005-06-02 *** Released version 0.6.15
10
11 2005-06-01 Fernando Perez <fperez@colorado.edu>
12
13 * IPython/iplib.py (MagicCompleter.file_matches): Fix
14 tab-completion of filenames within open-quoted strings. Note that
15 this requires that in ~/.ipython/ipythonrc, users change the
16 readline delimiters configuration to read:
17
18 readline_remove_delims -/~
19
20
21 2005-05-31 *** Released version 0.6.14
22
23 2005-05-29 Fernando Perez <fperez@colorado.edu>
24
25 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
26 with files not on the filesystem. Reported by Eliyahu Sandler
27 <eli@gondolin.net>
28
29 2005-05-22 Fernando Perez <fperez@colorado.edu>
30
31 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
32 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
33
34 2005-05-19 Fernando Perez <fperez@colorado.edu>
35
36 * IPython/iplib.py (safe_execfile): close a file which could be
37 left open (causing problems in win32, which locks open files).
38 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
39
40 2005-05-18 Fernando Perez <fperez@colorado.edu>
41
42 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
43 keyword arguments correctly to safe_execfile().
44
45 2005-05-13 Fernando Perez <fperez@colorado.edu>
46
47 * ipython.1: Added info about Qt to manpage, and threads warning
48 to usage page (invoked with --help).
49
50 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
51 new matcher (it goes at the end of the priority list) to do
52 tab-completion on named function arguments. Submitted by George
53 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
54 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
55 for more details.
56
57 * IPython/Magic.py (magic_run): Added new -e flag to ignore
58 SystemExit exceptions in the script being run. Thanks to a report
59 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
60 producing very annoying behavior when running unit tests.
61
62 2005-05-12 Fernando Perez <fperez@colorado.edu>
63
64 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
65 which I'd broken (again) due to a changed regexp. In the process,
66 added ';' as an escape to auto-quote the whole line without
67 splitting its arguments. Thanks to a report by Jerry McRae
68 <qrs0xyc02-AT-sneakemail.com>.
69
70 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
71 possible crashes caused by a TokenError. Reported by Ed Schofield
72 <schofield-AT-ftw.at>.
73
74 2005-05-06 Fernando Perez <fperez@colorado.edu>
75
76 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
77
78 2005-04-29 Fernando Perez <fperez@colorado.edu>
79
80 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
81 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
82 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
83 which provides support for Qt interactive usage (similar to the
84 existing one for WX and GTK). This had been often requested.
85
86 2005-04-14 *** Released version 0.6.13
87
88 2005-04-08 Fernando Perez <fperez@colorado.edu>
89
90 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
91 from _ofind, which gets called on almost every input line. Now,
92 we only try to get docstrings if they are actually going to be
93 used (the overhead of fetching unnecessary docstrings can be
94 noticeable for certain objects, such as Pyro proxies).
95
96 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
97 for completers. For some reason I had been passing them the state
98 variable, which completers never actually need, and was in
99 conflict with the rlcompleter API. Custom completers ONLY need to
100 take the text parameter.
101
102 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
103 work correctly in pysh. I've also moved all the logic which used
104 to be in pysh.py here, which will prevent problems with future
105 upgrades. However, this time I must warn users to update their
106 pysh profile to include the line
107
108 import_all IPython.Extensions.InterpreterExec
109
110 because otherwise things won't work for them. They MUST also
111 delete pysh.py and the line
112
113 execfile pysh.py
114
115 from their ipythonrc-pysh.
116
117 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
118 robust in the face of objects whose dir() returns non-strings
119 (which it shouldn't, but some broken libs like ITK do). Thanks to
120 a patch by John Hunter (implemented differently, though). Also
121 minor improvements by using .extend instead of + on lists.
122
123 * pysh.py:
124
125 2005-04-06 Fernando Perez <fperez@colorado.edu>
126
127 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
128 by default, so that all users benefit from it. Those who don't
129 want it can still turn it off.
130
131 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
132 config file, I'd forgotten about this, so users were getting it
133 off by default.
134
135 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
136 consistency. Now magics can be called in multiline statements,
137 and python variables can be expanded in magic calls via $var.
138 This makes the magic system behave just like aliases or !system
139 calls.
140
141 2005-03-28 Fernando Perez <fperez@colorado.edu>
142
143 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
144 expensive string additions for building command. Add support for
145 trailing ';' when autocall is used.
146
147 2005-03-26 Fernando Perez <fperez@colorado.edu>
148
149 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
150 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
151 ipython.el robust against prompts with any number of spaces
152 (including 0) after the ':' character.
153
154 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
155 continuation prompt, which misled users to think the line was
156 already indented. Closes debian Bug#300847, reported to me by
157 Norbert Tretkowski <tretkowski-AT-inittab.de>.
158
159 2005-03-23 Fernando Perez <fperez@colorado.edu>
160
161 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
162 properly aligned if they have embedded newlines.
163
164 * IPython/iplib.py (runlines): Add a public method to expose
165 IPython's code execution machinery, so that users can run strings
166 as if they had been typed at the prompt interactively.
167 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
168 methods which can call the system shell, but with python variable
169 expansion. The three such methods are: __IPYTHON__.system,
170 .getoutput and .getoutputerror. These need to be documented in a
171 'public API' section (to be written) of the manual.
172
173 2005-03-20 Fernando Perez <fperez@colorado.edu>
174
175 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
176 for custom exception handling. This is quite powerful, and it
177 allows for user-installable exception handlers which can trap
178 custom exceptions at runtime and treat them separately from
179 IPython's default mechanisms. At the request of Frédéric
180 Mantegazza <mantegazza-AT-ill.fr>.
181 (InteractiveShell.set_custom_completer): public API function to
182 add new completers at runtime.
183
184 2005-03-19 Fernando Perez <fperez@colorado.edu>
185
186 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
187 allow objects which provide their docstrings via non-standard
188 mechanisms (like Pyro proxies) to still be inspected by ipython's
189 ? system.
190
191 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
192 automatic capture system. I tried quite hard to make it work
193 reliably, and simply failed. I tried many combinations with the
194 subprocess module, but eventually nothing worked in all needed
195 cases (not blocking stdin for the child, duplicating stdout
196 without blocking, etc). The new %sc/%sx still do capture to these
197 magical list/string objects which make shell use much more
198 conveninent, so not all is lost.
199
200 XXX - FIX MANUAL for the change above!
201
202 (runsource): I copied code.py's runsource() into ipython to modify
203 it a bit. Now the code object and source to be executed are
204 stored in ipython. This makes this info accessible to third-party
205 tools, like custom exception handlers. After a request by Frédéric
206 Mantegazza <mantegazza-AT-ill.fr>.
207
208 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
209 history-search via readline (like C-p/C-n). I'd wanted this for a
210 long time, but only recently found out how to do it. For users
211 who already have their ipythonrc files made and want this, just
212 add:
213
214 readline_parse_and_bind "\e[A": history-search-backward
215 readline_parse_and_bind "\e[B": history-search-forward
216
217 2005-03-18 Fernando Perez <fperez@colorado.edu>
218
219 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
220 LSString and SList classes which allow transparent conversions
221 between list mode and whitespace-separated string.
222 (magic_r): Fix recursion problem in %r.
223
224 * IPython/genutils.py (LSString): New class to be used for
225 automatic storage of the results of all alias/system calls in _o
226 and _e (stdout/err). These provide a .l/.list attribute which
227 does automatic splitting on newlines. This means that for most
228 uses, you'll never need to do capturing of output with %sc/%sx
229 anymore, since ipython keeps this always done for you. Note that
230 only the LAST results are stored, the _o/e variables are
231 overwritten on each call. If you need to save their contents
232 further, simply bind them to any other name.
233
234 2005-03-17 Fernando Perez <fperez@colorado.edu>
235
236 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
237 prompt namespace handling.
238
239 2005-03-16 Fernando Perez <fperez@colorado.edu>
240
241 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
242 classic prompts to be '>>> ' (final space was missing, and it
243 trips the emacs python mode).
244 (BasePrompt.__str__): Added safe support for dynamic prompt
245 strings. Now you can set your prompt string to be '$x', and the
246 value of x will be printed from your interactive namespace. The
247 interpolation syntax includes the full Itpl support, so
248 ${foo()+x+bar()} is a valid prompt string now, and the function
249 calls will be made at runtime.
250
251 2005-03-15 Fernando Perez <fperez@colorado.edu>
252
253 * IPython/Magic.py (magic_history): renamed %hist to %history, to
254 avoid name clashes in pylab. %hist still works, it just forwards
255 the call to %history.
256
257 2005-03-02 *** Released version 0.6.12
258
259 2005-03-02 Fernando Perez <fperez@colorado.edu>
260
261 * IPython/iplib.py (handle_magic): log magic calls properly as
262 ipmagic() function calls.
263
264 * IPython/Magic.py (magic_time): Improved %time to support
265 statements and provide wall-clock as well as CPU time.
266
267 2005-02-27 Fernando Perez <fperez@colorado.edu>
268
269 * IPython/hooks.py: New hooks module, to expose user-modifiable
270 IPython functionality in a clean manner. For now only the editor
271 hook is actually written, and other thigns which I intend to turn
272 into proper hooks aren't yet there. The display and prefilter
273 stuff, for example, should be hooks. But at least now the
274 framework is in place, and the rest can be moved here with more
275 time later. IPython had had a .hooks variable for a long time for
276 this purpose, but I'd never actually used it for anything.
277
278 2005-02-26 Fernando Perez <fperez@colorado.edu>
279
280 * IPython/ipmaker.py (make_IPython): make the default ipython
281 directory be called _ipython under win32, to follow more the
282 naming peculiarities of that platform (where buggy software like
283 Visual Sourcesafe breaks with .named directories). Reported by
284 Ville Vainio.
285
286 2005-02-23 Fernando Perez <fperez@colorado.edu>
287
288 * IPython/iplib.py (InteractiveShell.__init__): removed a few
289 auto_aliases for win32 which were causing problems. Users can
290 define the ones they personally like.
291
292 2005-02-21 Fernando Perez <fperez@colorado.edu>
293
294 * IPython/Magic.py (magic_time): new magic to time execution of
295 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
296
297 2005-02-19 Fernando Perez <fperez@colorado.edu>
298
299 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
300 into keys (for prompts, for example).
301
302 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
303 prompts in case users want them. This introduces a small behavior
304 change: ipython does not automatically add a space to all prompts
305 anymore. To get the old prompts with a space, users should add it
306 manually to their ipythonrc file, so for example prompt_in1 should
307 now read 'In [\#]: ' instead of 'In [\#]:'.
308 (BasePrompt.__init__): New option prompts_pad_left (only in rc
309 file) to control left-padding of secondary prompts.
310
311 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
312 the profiler can't be imported. Fix for Debian, which removed
313 profile.py because of License issues. I applied a slightly
314 modified version of the original Debian patch at
315 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
316
317 2005-02-17 Fernando Perez <fperez@colorado.edu>
318
319 * IPython/genutils.py (native_line_ends): Fix bug which would
320 cause improper line-ends under win32 b/c I was not opening files
321 in binary mode. Bug report and fix thanks to Ville.
322
323 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
324 trying to catch spurious foo[1] autocalls. My fix actually broke
325 ',/' autoquote/call with explicit escape (bad regexp).
326
327 2005-02-15 *** Released version 0.6.11
328
329 2005-02-14 Fernando Perez <fperez@colorado.edu>
330
331 * IPython/background_jobs.py: New background job management
332 subsystem. This is implemented via a new set of classes, and
333 IPython now provides a builtin 'jobs' object for background job
334 execution. A convenience %bg magic serves as a lightweight
335 frontend for starting the more common type of calls. This was
336 inspired by discussions with B. Granger and the BackgroundCommand
337 class described in the book Python Scripting for Computational
338 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
339 (although ultimately no code from this text was used, as IPython's
340 system is a separate implementation).
341
342 * IPython/iplib.py (MagicCompleter.python_matches): add new option
343 to control the completion of single/double underscore names
344 separately. As documented in the example ipytonrc file, the
345 readline_omit__names variable can now be set to 2, to omit even
346 single underscore names. Thanks to a patch by Brian Wong
347 <BrianWong-AT-AirgoNetworks.Com>.
348 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
349 be autocalled as foo([1]) if foo were callable. A problem for
350 things which are both callable and implement __getitem__.
351 (init_readline): Fix autoindentation for win32. Thanks to a patch
352 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
353
354 2005-02-12 Fernando Perez <fperez@colorado.edu>
355
356 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
357 which I had written long ago to sort out user error messages which
358 may occur during startup. This seemed like a good idea initially,
359 but it has proven a disaster in retrospect. I don't want to
360 change much code for now, so my fix is to set the internal 'debug'
361 flag to true everywhere, whose only job was precisely to control
362 this subsystem. This closes issue 28 (as well as avoiding all
363 sorts of strange hangups which occur from time to time).
364
365 2005-02-07 Fernando Perez <fperez@colorado.edu>
366
367 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
368 previous call produced a syntax error.
369
370 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
371 classes without constructor.
372
373 2005-02-06 Fernando Perez <fperez@colorado.edu>
374
375 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
376 completions with the results of each matcher, so we return results
377 to the user from all namespaces. This breaks with ipython
378 tradition, but I think it's a nicer behavior. Now you get all
379 possible completions listed, from all possible namespaces (python,
380 filesystem, magics...) After a request by John Hunter
381 <jdhunter-AT-nitace.bsd.uchicago.edu>.
382
383 2005-02-05 Fernando Perez <fperez@colorado.edu>
384
385 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
386 the call had quote characters in it (the quotes were stripped).
387
388 2005-01-31 Fernando Perez <fperez@colorado.edu>
389
390 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
391 Itpl.itpl() to make the code more robust against psyco
392 optimizations.
393
394 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
395 of causing an exception. Quicker, cleaner.
396
397 2005-01-28 Fernando Perez <fperez@colorado.edu>
398
399 * scripts/ipython_win_post_install.py (install): hardcode
400 sys.prefix+'python.exe' as the executable path. It turns out that
401 during the post-installation run, sys.executable resolves to the
402 name of the binary installer! I should report this as a distutils
403 bug, I think. I updated the .10 release with this tiny fix, to
404 avoid annoying the lists further.
405
406 2005-01-27 *** Released version 0.6.10
407
408 2005-01-27 Fernando Perez <fperez@colorado.edu>
409
410 * IPython/numutils.py (norm): Added 'inf' as optional name for
411 L-infinity norm, included references to mathworld.com for vector
412 norm definitions.
413 (amin/amax): added amin/amax for array min/max. Similar to what
414 pylab ships with after the recent reorganization of names.
415 (spike/spike_odd): removed deprecated spike/spike_odd functions.
416
417 * ipython.el: committed Alex's recent fixes and improvements.
418 Tested with python-mode from CVS, and it looks excellent. Since
419 python-mode hasn't released anything in a while, I'm temporarily
420 putting a copy of today's CVS (v 4.70) of python-mode in:
421 http://ipython.scipy.org/tmp/python-mode.el
422
423 * scripts/ipython_win_post_install.py (install): Win32 fix to use
424 sys.executable for the executable name, instead of assuming it's
425 called 'python.exe' (the post-installer would have produced broken
426 setups on systems with a differently named python binary).
427
428 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
429 references to os.linesep, to make the code more
430 platform-independent. This is also part of the win32 coloring
431 fixes.
432
433 * IPython/genutils.py (page_dumb): Remove attempts to chop long
434 lines, which actually cause coloring bugs because the length of
435 the line is very difficult to correctly compute with embedded
436 escapes. This was the source of all the coloring problems under
437 Win32. I think that _finally_, Win32 users have a properly
438 working ipython in all respects. This would never have happened
439 if not for Gary Bishop and Viktor Ransmayr's great help and work.
440
441 2005-01-26 *** Released version 0.6.9
442
443 2005-01-25 Fernando Perez <fperez@colorado.edu>
444
445 * setup.py: finally, we have a true Windows installer, thanks to
446 the excellent work of Viktor Ransmayr
447 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
448 Windows users. The setup routine is quite a bit cleaner thanks to
449 this, and the post-install script uses the proper functions to
450 allow a clean de-installation using the standard Windows Control
451 Panel.
452
453 * IPython/genutils.py (get_home_dir): changed to use the $HOME
454 environment variable under all OSes (including win32) if
455 available. This will give consistency to win32 users who have set
456 this variable for any reason. If os.environ['HOME'] fails, the
457 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
458
459 2005-01-24 Fernando Perez <fperez@colorado.edu>
460
461 * IPython/numutils.py (empty_like): add empty_like(), similar to
462 zeros_like() but taking advantage of the new empty() Numeric routine.
463
464 2005-01-23 *** Released version 0.6.8
465
466 2005-01-22 Fernando Perez <fperez@colorado.edu>
467
468 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
469 automatic show() calls. After discussing things with JDH, it
470 turns out there are too many corner cases where this can go wrong.
471 It's best not to try to be 'too smart', and simply have ipython
472 reproduce as much as possible the default behavior of a normal
473 python shell.
474
475 * IPython/iplib.py (InteractiveShell.__init__): Modified the
476 line-splitting regexp and _prefilter() to avoid calling getattr()
477 on assignments. This closes
478 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
479 readline uses getattr(), so a simple <TAB> keypress is still
480 enough to trigger getattr() calls on an object.
481
482 2005-01-21 Fernando Perez <fperez@colorado.edu>
483
484 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
485 docstring under pylab so it doesn't mask the original.
486
487 2005-01-21 *** Released version 0.6.7
488
489 2005-01-21 Fernando Perez <fperez@colorado.edu>
490
491 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
492 signal handling for win32 users in multithreaded mode.
493
494 2005-01-17 Fernando Perez <fperez@colorado.edu>
495
496 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
497 instances with no __init__. After a crash report by Norbert Nemec
498 <Norbert-AT-nemec-online.de>.
499
500 2005-01-14 Fernando Perez <fperez@colorado.edu>
501
502 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
503 names for verbose exceptions, when multiple dotted names and the
504 'parent' object were present on the same line.
505
506 2005-01-11 Fernando Perez <fperez@colorado.edu>
507
508 * IPython/genutils.py (flag_calls): new utility to trap and flag
509 calls in functions. I need it to clean up matplotlib support.
510 Also removed some deprecated code in genutils.
511
512 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
513 that matplotlib scripts called with %run, which don't call show()
514 themselves, still have their plotting windows open.
515
516 2005-01-05 Fernando Perez <fperez@colorado.edu>
517
518 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
519 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
520
521 2004-12-19 Fernando Perez <fperez@colorado.edu>
522
523 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
524 parent_runcode, which was an eyesore. The same result can be
525 obtained with Python's regular superclass mechanisms.
526
527 2004-12-17 Fernando Perez <fperez@colorado.edu>
528
529 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
530 reported by Prabhu.
531 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
532 sys.stderr) instead of explicitly calling sys.stderr. This helps
533 maintain our I/O abstractions clean, for future GUI embeddings.
534
535 * IPython/genutils.py (info): added new utility for sys.stderr
536 unified info message handling (thin wrapper around warn()).
537
538 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
539 composite (dotted) names on verbose exceptions.
540 (VerboseTB.nullrepr): harden against another kind of errors which
541 Python's inspect module can trigger, and which were crashing
542 IPython. Thanks to a report by Marco Lombardi
543 <mlombard-AT-ma010192.hq.eso.org>.
544
545 2004-12-13 *** Released version 0.6.6
546
547 2004-12-12 Fernando Perez <fperez@colorado.edu>
548
549 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
550 generated by pygtk upon initialization if it was built without
551 threads (for matplotlib users). After a crash reported by
552 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
553
554 * IPython/ipmaker.py (make_IPython): fix small bug in the
555 import_some parameter for multiple imports.
556
557 * IPython/iplib.py (ipmagic): simplified the interface of
558 ipmagic() to take a single string argument, just as it would be
559 typed at the IPython cmd line.
560 (ipalias): Added new ipalias() with an interface identical to
561 ipmagic(). This completes exposing a pure python interface to the
562 alias and magic system, which can be used in loops or more complex
563 code where IPython's automatic line mangling is not active.
564
565 * IPython/genutils.py (timing): changed interface of timing to
566 simply run code once, which is the most common case. timings()
567 remains unchanged, for the cases where you want multiple runs.
568
569 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
570 bug where Python2.2 crashes with exec'ing code which does not end
571 in a single newline. Python 2.3 is OK, so I hadn't noticed this
572 before.
573
574 2004-12-10 Fernando Perez <fperez@colorado.edu>
575
576 * IPython/Magic.py (Magic.magic_prun): changed name of option from
577 -t to -T, to accomodate the new -t flag in %run (the %run and
578 %prun options are kind of intermixed, and it's not easy to change
579 this with the limitations of python's getopt).
580
581 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
582 the execution of scripts. It's not as fine-tuned as timeit.py,
583 but it works from inside ipython (and under 2.2, which lacks
584 timeit.py). Optionally a number of runs > 1 can be given for
585 timing very short-running code.
586
587 * IPython/genutils.py (uniq_stable): new routine which returns a
588 list of unique elements in any iterable, but in stable order of
589 appearance. I needed this for the ultraTB fixes, and it's a handy
590 utility.
591
592 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
593 dotted names in Verbose exceptions. This had been broken since
594 the very start, now x.y will properly be printed in a Verbose
595 traceback, instead of x being shown and y appearing always as an
596 'undefined global'. Getting this to work was a bit tricky,
597 because by default python tokenizers are stateless. Saved by
598 python's ability to easily add a bit of state to an arbitrary
599 function (without needing to build a full-blown callable object).
600
601 Also big cleanup of this code, which had horrendous runtime
602 lookups of zillions of attributes for colorization. Moved all
603 this code into a few templates, which make it cleaner and quicker.
604
605 Printout quality was also improved for Verbose exceptions: one
606 variable per line, and memory addresses are printed (this can be
607 quite handy in nasty debugging situations, which is what Verbose
608 is for).
609
610 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
611 the command line as scripts to be loaded by embedded instances.
612 Doing so has the potential for an infinite recursion if there are
613 exceptions thrown in the process. This fixes a strange crash
614 reported by Philippe MULLER <muller-AT-irit.fr>.
615
616 2004-12-09 Fernando Perez <fperez@colorado.edu>
617
618 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
619 to reflect new names in matplotlib, which now expose the
620 matlab-compatible interface via a pylab module instead of the
621 'matlab' name. The new code is backwards compatible, so users of
622 all matplotlib versions are OK. Patch by J. Hunter.
623
624 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
625 of __init__ docstrings for instances (class docstrings are already
626 automatically printed). Instances with customized docstrings
627 (indep. of the class) are also recognized and all 3 separate
628 docstrings are printed (instance, class, constructor). After some
629 comments/suggestions by J. Hunter.
630
631 2004-12-05 Fernando Perez <fperez@colorado.edu>
632
633 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
634 warnings when tab-completion fails and triggers an exception.
635
636 2004-12-03 Fernando Perez <fperez@colorado.edu>
637
638 * IPython/Magic.py (magic_prun): Fix bug where an exception would
639 be triggered when using 'run -p'. An incorrect option flag was
640 being set ('d' instead of 'D').
641 (manpage): fix missing escaped \- sign.
642
643 2004-11-30 *** Released version 0.6.5
644
645 2004-11-30 Fernando Perez <fperez@colorado.edu>
646
647 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
648 setting with -d option.
649
650 * setup.py (docfiles): Fix problem where the doc glob I was using
651 was COMPLETELY BROKEN. It was giving the right files by pure
652 accident, but failed once I tried to include ipython.el. Note:
653 glob() does NOT allow you to do exclusion on multiple endings!
654
655 2004-11-29 Fernando Perez <fperez@colorado.edu>
656
657 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
658 the manpage as the source. Better formatting & consistency.
659
660 * IPython/Magic.py (magic_run): Added new -d option, to run
661 scripts under the control of the python pdb debugger. Note that
662 this required changing the %prun option -d to -D, to avoid a clash
663 (since %run must pass options to %prun, and getopt is too dumb to
664 handle options with string values with embedded spaces). Thanks
665 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
666 (magic_who_ls): added type matching to %who and %whos, so that one
667 can filter their output to only include variables of certain
668 types. Another suggestion by Matthew.
669 (magic_whos): Added memory summaries in kb and Mb for arrays.
670 (magic_who): Improve formatting (break lines every 9 vars).
671
672 2004-11-28 Fernando Perez <fperez@colorado.edu>
673
674 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
675 cache when empty lines were present.
676
677 2004-11-24 Fernando Perez <fperez@colorado.edu>
678
679 * IPython/usage.py (__doc__): document the re-activated threading
680 options for WX and GTK.
681
682 2004-11-23 Fernando Perez <fperez@colorado.edu>
683
684 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
685 the -wthread and -gthread options, along with a new -tk one to try
686 and coordinate Tk threading with wx/gtk. The tk support is very
687 platform dependent, since it seems to require Tcl and Tk to be
688 built with threads (Fedora1/2 appears NOT to have it, but in
689 Prabhu's Debian boxes it works OK). But even with some Tk
690 limitations, this is a great improvement.
691
692 * IPython/Prompts.py (prompt_specials_color): Added \t for time
693 info in user prompts. Patch by Prabhu.
694
695 2004-11-18 Fernando Perez <fperez@colorado.edu>
696
697 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
698 EOFErrors and bail, to avoid infinite loops if a non-terminating
699 file is fed into ipython. Patch submitted in issue 19 by user,
700 many thanks.
701
702 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
703 autoquote/parens in continuation prompts, which can cause lots of
704 problems. Closes roundup issue 20.
705
706 2004-11-17 Fernando Perez <fperez@colorado.edu>
707
708 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
709 reported as debian bug #280505. I'm not sure my local changelog
710 entry has the proper debian format (Jack?).
711
712 2004-11-08 *** Released version 0.6.4
713
714 2004-11-08 Fernando Perez <fperez@colorado.edu>
715
716 * IPython/iplib.py (init_readline): Fix exit message for Windows
717 when readline is active. Thanks to a report by Eric Jones
718 <eric-AT-enthought.com>.
719
720 2004-11-07 Fernando Perez <fperez@colorado.edu>
721
722 * IPython/genutils.py (page): Add a trap for OSError exceptions,
723 sometimes seen by win2k/cygwin users.
724
725 2004-11-06 Fernando Perez <fperez@colorado.edu>
726
727 * IPython/iplib.py (interact): Change the handling of %Exit from
728 trying to propagate a SystemExit to an internal ipython flag.
729 This is less elegant than using Python's exception mechanism, but
730 I can't get that to work reliably with threads, so under -pylab
731 %Exit was hanging IPython. Cross-thread exception handling is
732 really a bitch. Thaks to a bug report by Stephen Walton
733 <stephen.walton-AT-csun.edu>.
734
735 2004-11-04 Fernando Perez <fperez@colorado.edu>
736
737 * IPython/iplib.py (raw_input_original): store a pointer to the
738 true raw_input to harden against code which can modify it
739 (wx.py.PyShell does this and would otherwise crash ipython).
740 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
741
742 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
743 Ctrl-C problem, which does not mess up the input line.
744
745 2004-11-03 Fernando Perez <fperez@colorado.edu>
746
747 * IPython/Release.py: Changed licensing to BSD, in all files.
748 (name): lowercase name for tarball/RPM release.
749
750 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
751 use throughout ipython.
752
753 * IPython/Magic.py (Magic._ofind): Switch to using the new
754 OInspect.getdoc() function.
755
756 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
757 of the line currently being canceled via Ctrl-C. It's extremely
758 ugly, but I don't know how to do it better (the problem is one of
759 handling cross-thread exceptions).
760
761 2004-10-28 Fernando Perez <fperez@colorado.edu>
762
763 * IPython/Shell.py (signal_handler): add signal handlers to trap
764 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
765 report by Francesc Alted.
766
767 2004-10-21 Fernando Perez <fperez@colorado.edu>
768
769 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
770 to % for pysh syntax extensions.
771
772 2004-10-09 Fernando Perez <fperez@colorado.edu>
773
774 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
775 arrays to print a more useful summary, without calling str(arr).
776 This avoids the problem of extremely lengthy computations which
777 occur if arr is large, and appear to the user as a system lockup
778 with 100% cpu activity. After a suggestion by Kristian Sandberg
779 <Kristian.Sandberg@colorado.edu>.
780 (Magic.__init__): fix bug in global magic escapes not being
781 correctly set.
782
783 2004-10-08 Fernando Perez <fperez@colorado.edu>
784
785 * IPython/Magic.py (__license__): change to absolute imports of
786 ipython's own internal packages, to start adapting to the absolute
787 import requirement of PEP-328.
788
789 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
790 files, and standardize author/license marks through the Release
791 module instead of having per/file stuff (except for files with
792 particular licenses, like the MIT/PSF-licensed codes).
793
794 * IPython/Debugger.py: remove dead code for python 2.1
795
796 2004-10-04 Fernando Perez <fperez@colorado.edu>
797
798 * IPython/iplib.py (ipmagic): New function for accessing magics
799 via a normal python function call.
800
801 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
802 from '@' to '%', to accomodate the new @decorator syntax of python
803 2.4.
804
805 2004-09-29 Fernando Perez <fperez@colorado.edu>
806
807 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
808 matplotlib.use to prevent running scripts which try to switch
809 interactive backends from within ipython. This will just crash
810 the python interpreter, so we can't allow it (but a detailed error
811 is given to the user).
812
813 2004-09-28 Fernando Perez <fperez@colorado.edu>
814
815 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
816 matplotlib-related fixes so that using @run with non-matplotlib
817 scripts doesn't pop up spurious plot windows. This requires
818 matplotlib >= 0.63, where I had to make some changes as well.
819
820 * IPython/ipmaker.py (make_IPython): update version requirement to
821 python 2.2.
822
823 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
824 banner arg for embedded customization.
825
826 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
827 explicit uses of __IP as the IPython's instance name. Now things
828 are properly handled via the shell.name value. The actual code
829 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
830 is much better than before. I'll clean things completely when the
831 magic stuff gets a real overhaul.
832
833 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
834 minor changes to debian dir.
835
836 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
837 pointer to the shell itself in the interactive namespace even when
838 a user-supplied dict is provided. This is needed for embedding
839 purposes (found by tests with Michel Sanner).
840
841 2004-09-27 Fernando Perez <fperez@colorado.edu>
842
843 * IPython/UserConfig/ipythonrc: remove []{} from
844 readline_remove_delims, so that things like [modname.<TAB> do
845 proper completion. This disables [].TAB, but that's a less common
846 case than module names in list comprehensions, for example.
847 Thanks to a report by Andrea Riciputi.
848
849 2004-09-09 Fernando Perez <fperez@colorado.edu>
850
851 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
852 blocking problems in win32 and osx. Fix by John.
853
854 2004-09-08 Fernando Perez <fperez@colorado.edu>
855
856 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
857 for Win32 and OSX. Fix by John Hunter.
858
859 2004-08-30 *** Released version 0.6.3
860
861 2004-08-30 Fernando Perez <fperez@colorado.edu>
862
863 * setup.py (isfile): Add manpages to list of dependent files to be
864 updated.
865
866 2004-08-27 Fernando Perez <fperez@colorado.edu>
867
868 * IPython/Shell.py (start): I've disabled -wthread and -gthread
869 for now. They don't really work with standalone WX/GTK code
870 (though matplotlib IS working fine with both of those backends).
871 This will neeed much more testing. I disabled most things with
872 comments, so turning it back on later should be pretty easy.
873
874 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
875 autocalling of expressions like r'foo', by modifying the line
876 split regexp. Closes
877 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
878 Riley <ipythonbugs-AT-sabi.net>.
879 (InteractiveShell.mainloop): honor --nobanner with banner
880 extensions.
881
882 * IPython/Shell.py: Significant refactoring of all classes, so
883 that we can really support ALL matplotlib backends and threading
884 models (John spotted a bug with Tk which required this). Now we
885 should support single-threaded, WX-threads and GTK-threads, both
886 for generic code and for matplotlib.
887
888 * IPython/ipmaker.py (__call__): Changed -mpthread option to
889 -pylab, to simplify things for users. Will also remove the pylab
890 profile, since now all of matplotlib configuration is directly
891 handled here. This also reduces startup time.
892
893 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
894 shell wasn't being correctly called. Also in IPShellWX.
895
896 * IPython/iplib.py (InteractiveShell.__init__): Added option to
897 fine-tune banner.
898
899 * IPython/numutils.py (spike): Deprecate these spike functions,
900 delete (long deprecated) gnuplot_exec handler.
901
902 2004-08-26 Fernando Perez <fperez@colorado.edu>
903
904 * ipython.1: Update for threading options, plus some others which
905 were missing.
906
907 * IPython/ipmaker.py (__call__): Added -wthread option for
908 wxpython thread handling. Make sure threading options are only
909 valid at the command line.
910
911 * scripts/ipython: moved shell selection into a factory function
912 in Shell.py, to keep the starter script to a minimum.
913
914 2004-08-25 Fernando Perez <fperez@colorado.edu>
915
916 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
917 John. Along with some recent changes he made to matplotlib, the
918 next versions of both systems should work very well together.
919
920 2004-08-24 Fernando Perez <fperez@colorado.edu>
921
922 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
923 tried to switch the profiling to using hotshot, but I'm getting
924 strange errors from prof.runctx() there. I may be misreading the
925 docs, but it looks weird. For now the profiling code will
926 continue to use the standard profiler.
927
928 2004-08-23 Fernando Perez <fperez@colorado.edu>
929
930 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
931 threaded shell, by John Hunter. It's not quite ready yet, but
932 close.
933
934 2004-08-22 Fernando Perez <fperez@colorado.edu>
935
936 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
937 in Magic and ultraTB.
938
939 * ipython.1: document threading options in manpage.
940
941 * scripts/ipython: Changed name of -thread option to -gthread,
942 since this is GTK specific. I want to leave the door open for a
943 -wthread option for WX, which will most likely be necessary. This
944 change affects usage and ipmaker as well.
945
946 * IPython/Shell.py (matplotlib_shell): Add a factory function to
947 handle the matplotlib shell issues. Code by John Hunter
948 <jdhunter-AT-nitace.bsd.uchicago.edu>.
949 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
950 broken (and disabled for end users) for now, but it puts the
951 infrastructure in place.
952
953 2004-08-21 Fernando Perez <fperez@colorado.edu>
954
955 * ipythonrc-pylab: Add matplotlib support.
956
957 * matplotlib_config.py: new files for matplotlib support, part of
958 the pylab profile.
959
960 * IPython/usage.py (__doc__): documented the threading options.
961
962 2004-08-20 Fernando Perez <fperez@colorado.edu>
963
964 * ipython: Modified the main calling routine to handle the -thread
965 and -mpthread options. This needs to be done as a top-level hack,
966 because it determines which class to instantiate for IPython
967 itself.
968
969 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
970 classes to support multithreaded GTK operation without blocking,
971 and matplotlib with all backends. This is a lot of still very
972 experimental code, and threads are tricky. So it may still have a
973 few rough edges... This code owes a lot to
974 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
975 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
976 to John Hunter for all the matplotlib work.
977
978 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
979 options for gtk thread and matplotlib support.
980
981 2004-08-16 Fernando Perez <fperez@colorado.edu>
982
983 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
984 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
985 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
986
987 2004-08-11 Fernando Perez <fperez@colorado.edu>
988
989 * setup.py (isfile): Fix build so documentation gets updated for
990 rpms (it was only done for .tgz builds).
991
992 2004-08-10 Fernando Perez <fperez@colorado.edu>
993
994 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
995
996 * iplib.py : Silence syntax error exceptions in tab-completion.
997
998 2004-08-05 Fernando Perez <fperez@colorado.edu>
999
1000 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1001 'color off' mark for continuation prompts. This was causing long
1002 continuation lines to mis-wrap.
1003
1004 2004-08-01 Fernando Perez <fperez@colorado.edu>
1005
1006 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1007 for building ipython to be a parameter. All this is necessary
1008 right now to have a multithreaded version, but this insane
1009 non-design will be cleaned up soon. For now, it's a hack that
1010 works.
1011
1012 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1013 args in various places. No bugs so far, but it's a dangerous
1014 practice.
1015
1016 2004-07-31 Fernando Perez <fperez@colorado.edu>
1017
1018 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1019 fix completion of files with dots in their names under most
1020 profiles (pysh was OK because the completion order is different).
1021
1022 2004-07-27 Fernando Perez <fperez@colorado.edu>
1023
1024 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1025 keywords manually, b/c the one in keyword.py was removed in python
1026 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1027 This is NOT a bug under python 2.3 and earlier.
1028
1029 2004-07-26 Fernando Perez <fperez@colorado.edu>
1030
1031 * IPython/ultraTB.py (VerboseTB.text): Add another
1032 linecache.checkcache() call to try to prevent inspect.py from
1033 crashing under python 2.3. I think this fixes
1034 http://www.scipy.net/roundup/ipython/issue17.
1035
1036 2004-07-26 *** Released version 0.6.2
1037
1038 2004-07-26 Fernando Perez <fperez@colorado.edu>
1039
1040 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1041 fail for any number.
1042 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1043 empty bookmarks.
1044
1045 2004-07-26 *** Released version 0.6.1
1046
1047 2004-07-26 Fernando Perez <fperez@colorado.edu>
1048
1049 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1050
1051 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1052 escaping '()[]{}' in filenames.
1053
1054 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1055 Python 2.2 users who lack a proper shlex.split.
1056
1057 2004-07-19 Fernando Perez <fperez@colorado.edu>
1058
1059 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1060 for reading readline's init file. I follow the normal chain:
1061 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1062 report by Mike Heeter. This closes
1063 http://www.scipy.net/roundup/ipython/issue16.
1064
1065 2004-07-18 Fernando Perez <fperez@colorado.edu>
1066
1067 * IPython/iplib.py (__init__): Add better handling of '\' under
1068 Win32 for filenames. After a patch by Ville.
1069
1070 2004-07-17 Fernando Perez <fperez@colorado.edu>
1071
1072 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1073 autocalling would be triggered for 'foo is bar' if foo is
1074 callable. I also cleaned up the autocall detection code to use a
1075 regexp, which is faster. Bug reported by Alexander Schmolck.
1076
1077 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1078 '?' in them would confuse the help system. Reported by Alex
1079 Schmolck.
1080
1081 2004-07-16 Fernando Perez <fperez@colorado.edu>
1082
1083 * IPython/GnuplotInteractive.py (__all__): added plot2.
1084
1085 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1086 plotting dictionaries, lists or tuples of 1d arrays.
1087
1088 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1089 optimizations.
1090
1091 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1092 the information which was there from Janko's original IPP code:
1093
1094 03.05.99 20:53 porto.ifm.uni-kiel.de
1095 --Started changelog.
1096 --make clear do what it say it does
1097 --added pretty output of lines from inputcache
1098 --Made Logger a mixin class, simplifies handling of switches
1099 --Added own completer class. .string<TAB> expands to last history
1100 line which starts with string. The new expansion is also present
1101 with Ctrl-r from the readline library. But this shows, who this
1102 can be done for other cases.
1103 --Added convention that all shell functions should accept a
1104 parameter_string This opens the door for different behaviour for
1105 each function. @cd is a good example of this.
1106
1107 04.05.99 12:12 porto.ifm.uni-kiel.de
1108 --added logfile rotation
1109 --added new mainloop method which freezes first the namespace
1110
1111 07.05.99 21:24 porto.ifm.uni-kiel.de
1112 --added the docreader classes. Now there is a help system.
1113 -This is only a first try. Currently it's not easy to put new
1114 stuff in the indices. But this is the way to go. Info would be
1115 better, but HTML is every where and not everybody has an info
1116 system installed and it's not so easy to change html-docs to info.
1117 --added global logfile option
1118 --there is now a hook for object inspection method pinfo needs to
1119 be provided for this. Can be reached by two '??'.
1120
1121 08.05.99 20:51 porto.ifm.uni-kiel.de
1122 --added a README
1123 --bug in rc file. Something has changed so functions in the rc
1124 file need to reference the shell and not self. Not clear if it's a
1125 bug or feature.
1126 --changed rc file for new behavior
1127
1128 2004-07-15 Fernando Perez <fperez@colorado.edu>
1129
1130 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1131 cache was falling out of sync in bizarre manners when multi-line
1132 input was present. Minor optimizations and cleanup.
1133
1134 (Logger): Remove old Changelog info for cleanup. This is the
1135 information which was there from Janko's original code:
1136
1137 Changes to Logger: - made the default log filename a parameter
1138
1139 - put a check for lines beginning with !@? in log(). Needed
1140 (even if the handlers properly log their lines) for mid-session
1141 logging activation to work properly. Without this, lines logged
1142 in mid session, which get read from the cache, would end up
1143 'bare' (with !@? in the open) in the log. Now they are caught
1144 and prepended with a #.
1145
1146 * IPython/iplib.py (InteractiveShell.init_readline): added check
1147 in case MagicCompleter fails to be defined, so we don't crash.
1148
1149 2004-07-13 Fernando Perez <fperez@colorado.edu>
1150
1151 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1152 of EPS if the requested filename ends in '.eps'.
1153
1154 2004-07-04 Fernando Perez <fperez@colorado.edu>
1155
1156 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1157 escaping of quotes when calling the shell.
1158
1159 2004-07-02 Fernando Perez <fperez@colorado.edu>
1160
1161 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1162 gettext not working because we were clobbering '_'. Fixes
1163 http://www.scipy.net/roundup/ipython/issue6.
1164
1165 2004-07-01 Fernando Perez <fperez@colorado.edu>
1166
1167 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1168 into @cd. Patch by Ville.
1169
1170 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1171 new function to store things after ipmaker runs. Patch by Ville.
1172 Eventually this will go away once ipmaker is removed and the class
1173 gets cleaned up, but for now it's ok. Key functionality here is
1174 the addition of the persistent storage mechanism, a dict for
1175 keeping data across sessions (for now just bookmarks, but more can
1176 be implemented later).
1177
1178 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1179 persistent across sections. Patch by Ville, I modified it
1180 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1181 added a '-l' option to list all bookmarks.
1182
1183 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1184 center for cleanup. Registered with atexit.register(). I moved
1185 here the old exit_cleanup(). After a patch by Ville.
1186
1187 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1188 characters in the hacked shlex_split for python 2.2.
1189
1190 * IPython/iplib.py (file_matches): more fixes to filenames with
1191 whitespace in them. It's not perfect, but limitations in python's
1192 readline make it impossible to go further.
1193
1194 2004-06-29 Fernando Perez <fperez@colorado.edu>
1195
1196 * IPython/iplib.py (file_matches): escape whitespace correctly in
1197 filename completions. Bug reported by Ville.
1198
1199 2004-06-28 Fernando Perez <fperez@colorado.edu>
1200
1201 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1202 the history file will be called 'history-PROFNAME' (or just
1203 'history' if no profile is loaded). I was getting annoyed at
1204 getting my Numerical work history clobbered by pysh sessions.
1205
1206 * IPython/iplib.py (InteractiveShell.__init__): Internal
1207 getoutputerror() function so that we can honor the system_verbose
1208 flag for _all_ system calls. I also added escaping of #
1209 characters here to avoid confusing Itpl.
1210
1211 * IPython/Magic.py (shlex_split): removed call to shell in
1212 parse_options and replaced it with shlex.split(). The annoying
1213 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1214 to backport it from 2.3, with several frail hacks (the shlex
1215 module is rather limited in 2.2). Thanks to a suggestion by Ville
1216 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1217 problem.
1218
1219 (Magic.magic_system_verbose): new toggle to print the actual
1220 system calls made by ipython. Mainly for debugging purposes.
1221
1222 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1223 doesn't support persistence. Reported (and fix suggested) by
1224 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1225
1226 2004-06-26 Fernando Perez <fperez@colorado.edu>
1227
1228 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1229 continue prompts.
1230
1231 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1232 function (basically a big docstring) and a few more things here to
1233 speedup startup. pysh.py is now very lightweight. We want because
1234 it gets execfile'd, while InterpreterExec gets imported, so
1235 byte-compilation saves time.
1236
1237 2004-06-25 Fernando Perez <fperez@colorado.edu>
1238
1239 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1240 -NUM', which was recently broken.
1241
1242 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1243 in multi-line input (but not !!, which doesn't make sense there).
1244
1245 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1246 It's just too useful, and people can turn it off in the less
1247 common cases where it's a problem.
1248
1249 2004-06-24 Fernando Perez <fperez@colorado.edu>
1250
1251 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1252 special syntaxes (like alias calling) is now allied in multi-line
1253 input. This is still _very_ experimental, but it's necessary for
1254 efficient shell usage combining python looping syntax with system
1255 calls. For now it's restricted to aliases, I don't think it
1256 really even makes sense to have this for magics.
1257
1258 2004-06-23 Fernando Perez <fperez@colorado.edu>
1259
1260 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1261 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1262
1263 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1264 extensions under Windows (after code sent by Gary Bishop). The
1265 extensions considered 'executable' are stored in IPython's rc
1266 structure as win_exec_ext.
1267
1268 * IPython/genutils.py (shell): new function, like system() but
1269 without return value. Very useful for interactive shell work.
1270
1271 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1272 delete aliases.
1273
1274 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1275 sure that the alias table doesn't contain python keywords.
1276
1277 2004-06-21 Fernando Perez <fperez@colorado.edu>
1278
1279 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1280 non-existent items are found in $PATH. Reported by Thorsten.
1281
1282 2004-06-20 Fernando Perez <fperez@colorado.edu>
1283
1284 * IPython/iplib.py (complete): modified the completer so that the
1285 order of priorities can be easily changed at runtime.
1286
1287 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1288 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1289
1290 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1291 expand Python variables prepended with $ in all system calls. The
1292 same was done to InteractiveShell.handle_shell_escape. Now all
1293 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1294 expansion of python variables and expressions according to the
1295 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1296
1297 Though PEP-215 has been rejected, a similar (but simpler) one
1298 seems like it will go into Python 2.4, PEP-292 -
1299 http://www.python.org/peps/pep-0292.html.
1300
1301 I'll keep the full syntax of PEP-215, since IPython has since the
1302 start used Ka-Ping Yee's reference implementation discussed there
1303 (Itpl), and I actually like the powerful semantics it offers.
1304
1305 In order to access normal shell variables, the $ has to be escaped
1306 via an extra $. For example:
1307
1308 In [7]: PATH='a python variable'
1309
1310 In [8]: !echo $PATH
1311 a python variable
1312
1313 In [9]: !echo $$PATH
1314 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1315
1316 (Magic.parse_options): escape $ so the shell doesn't evaluate
1317 things prematurely.
1318
1319 * IPython/iplib.py (InteractiveShell.call_alias): added the
1320 ability for aliases to expand python variables via $.
1321
1322 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1323 system, now there's a @rehash/@rehashx pair of magics. These work
1324 like the csh rehash command, and can be invoked at any time. They
1325 build a table of aliases to everything in the user's $PATH
1326 (@rehash uses everything, @rehashx is slower but only adds
1327 executable files). With this, the pysh.py-based shell profile can
1328 now simply call rehash upon startup, and full access to all
1329 programs in the user's path is obtained.
1330
1331 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1332 functionality is now fully in place. I removed the old dynamic
1333 code generation based approach, in favor of a much lighter one
1334 based on a simple dict. The advantage is that this allows me to
1335 now have thousands of aliases with negligible cost (unthinkable
1336 with the old system).
1337
1338 2004-06-19 Fernando Perez <fperez@colorado.edu>
1339
1340 * IPython/iplib.py (__init__): extended MagicCompleter class to
1341 also complete (last in priority) on user aliases.
1342
1343 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1344 call to eval.
1345 (ItplNS.__init__): Added a new class which functions like Itpl,
1346 but allows configuring the namespace for the evaluation to occur
1347 in.
1348
1349 2004-06-18 Fernando Perez <fperez@colorado.edu>
1350
1351 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1352 better message when 'exit' or 'quit' are typed (a common newbie
1353 confusion).
1354
1355 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1356 check for Windows users.
1357
1358 * IPython/iplib.py (InteractiveShell.user_setup): removed
1359 disabling of colors for Windows. I'll test at runtime and issue a
1360 warning if Gary's readline isn't found, as to nudge users to
1361 download it.
1362
1363 2004-06-16 Fernando Perez <fperez@colorado.edu>
1364
1365 * IPython/genutils.py (Stream.__init__): changed to print errors
1366 to sys.stderr. I had a circular dependency here. Now it's
1367 possible to run ipython as IDLE's shell (consider this pre-alpha,
1368 since true stdout things end up in the starting terminal instead
1369 of IDLE's out).
1370
1371 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1372 users who haven't # updated their prompt_in2 definitions. Remove
1373 eventually.
1374 (multiple_replace): added credit to original ASPN recipe.
1375
1376 2004-06-15 Fernando Perez <fperez@colorado.edu>
1377
1378 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1379 list of auto-defined aliases.
1380
1381 2004-06-13 Fernando Perez <fperez@colorado.edu>
1382
1383 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1384 install was really requested (so setup.py can be used for other
1385 things under Windows).
1386
1387 2004-06-10 Fernando Perez <fperez@colorado.edu>
1388
1389 * IPython/Logger.py (Logger.create_log): Manually remove any old
1390 backup, since os.remove may fail under Windows. Fixes bug
1391 reported by Thorsten.
1392
1393 2004-06-09 Fernando Perez <fperez@colorado.edu>
1394
1395 * examples/example-embed.py: fixed all references to %n (replaced
1396 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1397 for all examples and the manual as well.
1398
1399 2004-06-08 Fernando Perez <fperez@colorado.edu>
1400
1401 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1402 alignment and color management. All 3 prompt subsystems now
1403 inherit from BasePrompt.
1404
1405 * tools/release: updates for windows installer build and tag rpms
1406 with python version (since paths are fixed).
1407
1408 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1409 which will become eventually obsolete. Also fixed the default
1410 prompt_in2 to use \D, so at least new users start with the correct
1411 defaults.
1412 WARNING: Users with existing ipythonrc files will need to apply
1413 this fix manually!
1414
1415 * setup.py: make windows installer (.exe). This is finally the
1416 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1417 which I hadn't included because it required Python 2.3 (or recent
1418 distutils).
1419
1420 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1421 usage of new '\D' escape.
1422
1423 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1424 lacks os.getuid())
1425 (CachedOutput.set_colors): Added the ability to turn coloring
1426 on/off with @colors even for manually defined prompt colors. It
1427 uses a nasty global, but it works safely and via the generic color
1428 handling mechanism.
1429 (Prompt2.__init__): Introduced new escape '\D' for continuation
1430 prompts. It represents the counter ('\#') as dots.
1431 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1432 need to update their ipythonrc files and replace '%n' with '\D' in
1433 their prompt_in2 settings everywhere. Sorry, but there's
1434 otherwise no clean way to get all prompts to properly align. The
1435 ipythonrc shipped with IPython has been updated.
1436
1437 2004-06-07 Fernando Perez <fperez@colorado.edu>
1438
1439 * setup.py (isfile): Pass local_icons option to latex2html, so the
1440 resulting HTML file is self-contained. Thanks to
1441 dryice-AT-liu.com.cn for the tip.
1442
1443 * pysh.py: I created a new profile 'shell', which implements a
1444 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1445 system shell, nor will it become one anytime soon. It's mainly
1446 meant to illustrate the use of the new flexible bash-like prompts.
1447 I guess it could be used by hardy souls for true shell management,
1448 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1449 profile. This uses the InterpreterExec extension provided by
1450 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1451
1452 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1453 auto-align itself with the length of the previous input prompt
1454 (taking into account the invisible color escapes).
1455 (CachedOutput.__init__): Large restructuring of this class. Now
1456 all three prompts (primary1, primary2, output) are proper objects,
1457 managed by the 'parent' CachedOutput class. The code is still a
1458 bit hackish (all prompts share state via a pointer to the cache),
1459 but it's overall far cleaner than before.
1460
1461 * IPython/genutils.py (getoutputerror): modified to add verbose,
1462 debug and header options. This makes the interface of all getout*
1463 functions uniform.
1464 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1465
1466 * IPython/Magic.py (Magic.default_option): added a function to
1467 allow registering default options for any magic command. This
1468 makes it easy to have profiles which customize the magics globally
1469 for a certain use. The values set through this function are
1470 picked up by the parse_options() method, which all magics should
1471 use to parse their options.
1472
1473 * IPython/genutils.py (warn): modified the warnings framework to
1474 use the Term I/O class. I'm trying to slowly unify all of
1475 IPython's I/O operations to pass through Term.
1476
1477 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1478 the secondary prompt to correctly match the length of the primary
1479 one for any prompt. Now multi-line code will properly line up
1480 even for path dependent prompts, such as the new ones available
1481 via the prompt_specials.
1482
1483 2004-06-06 Fernando Perez <fperez@colorado.edu>
1484
1485 * IPython/Prompts.py (prompt_specials): Added the ability to have
1486 bash-like special sequences in the prompts, which get
1487 automatically expanded. Things like hostname, current working
1488 directory and username are implemented already, but it's easy to
1489 add more in the future. Thanks to a patch by W.J. van der Laan
1490 <gnufnork-AT-hetdigitalegat.nl>
1491 (prompt_specials): Added color support for prompt strings, so
1492 users can define arbitrary color setups for their prompts.
1493
1494 2004-06-05 Fernando Perez <fperez@colorado.edu>
1495
1496 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1497 code to load Gary Bishop's readline and configure it
1498 automatically. Thanks to Gary for help on this.
1499
1500 2004-06-01 Fernando Perez <fperez@colorado.edu>
1501
1502 * IPython/Logger.py (Logger.create_log): fix bug for logging
1503 with no filename (previous fix was incomplete).
1504
1505 2004-05-25 Fernando Perez <fperez@colorado.edu>
1506
1507 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1508 parens would get passed to the shell.
1509
1510 2004-05-20 Fernando Perez <fperez@colorado.edu>
1511
1512 * IPython/Magic.py (Magic.magic_prun): changed default profile
1513 sort order to 'time' (the more common profiling need).
1514
1515 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1516 so that source code shown is guaranteed in sync with the file on
1517 disk (also changed in psource). Similar fix to the one for
1518 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1519 <yann.ledu-AT-noos.fr>.
1520
1521 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1522 with a single option would not be correctly parsed. Closes
1523 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1524 introduced in 0.6.0 (on 2004-05-06).
1525
1526 2004-05-13 *** Released version 0.6.0
1527
1528 2004-05-13 Fernando Perez <fperez@colorado.edu>
1529
1530 * debian/: Added debian/ directory to CVS, so that debian support
1531 is publicly accessible. The debian package is maintained by Jack
1532 Moffit <jack-AT-xiph.org>.
1533
1534 * Documentation: included the notes about an ipython-based system
1535 shell (the hypothetical 'pysh') into the new_design.pdf document,
1536 so that these ideas get distributed to users along with the
1537 official documentation.
1538
1539 2004-05-10 Fernando Perez <fperez@colorado.edu>
1540
1541 * IPython/Logger.py (Logger.create_log): fix recently introduced
1542 bug (misindented line) where logstart would fail when not given an
1543 explicit filename.
1544
1545 2004-05-09 Fernando Perez <fperez@colorado.edu>
1546
1547 * IPython/Magic.py (Magic.parse_options): skip system call when
1548 there are no options to look for. Faster, cleaner for the common
1549 case.
1550
1551 * Documentation: many updates to the manual: describing Windows
1552 support better, Gnuplot updates, credits, misc small stuff. Also
1553 updated the new_design doc a bit.
1554
1555 2004-05-06 *** Released version 0.6.0.rc1
1556
1557 2004-05-06 Fernando Perez <fperez@colorado.edu>
1558
1559 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1560 operations to use the vastly more efficient list/''.join() method.
1561 (FormattedTB.text): Fix
1562 http://www.scipy.net/roundup/ipython/issue12 - exception source
1563 extract not updated after reload. Thanks to Mike Salib
1564 <msalib-AT-mit.edu> for pinning the source of the problem.
1565 Fortunately, the solution works inside ipython and doesn't require
1566 any changes to python proper.
1567
1568 * IPython/Magic.py (Magic.parse_options): Improved to process the
1569 argument list as a true shell would (by actually using the
1570 underlying system shell). This way, all @magics automatically get
1571 shell expansion for variables. Thanks to a comment by Alex
1572 Schmolck.
1573
1574 2004-04-04 Fernando Perez <fperez@colorado.edu>
1575
1576 * IPython/iplib.py (InteractiveShell.interact): Added a special
1577 trap for a debugger quit exception, which is basically impossible
1578 to handle by normal mechanisms, given what pdb does to the stack.
1579 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1580
1581 2004-04-03 Fernando Perez <fperez@colorado.edu>
1582
1583 * IPython/genutils.py (Term): Standardized the names of the Term
1584 class streams to cin/cout/cerr, following C++ naming conventions
1585 (I can't use in/out/err because 'in' is not a valid attribute
1586 name).
1587
1588 * IPython/iplib.py (InteractiveShell.interact): don't increment
1589 the prompt if there's no user input. By Daniel 'Dang' Griffith
1590 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1591 Francois Pinard.
1592
1593 2004-04-02 Fernando Perez <fperez@colorado.edu>
1594
1595 * IPython/genutils.py (Stream.__init__): Modified to survive at
1596 least importing in contexts where stdin/out/err aren't true file
1597 objects, such as PyCrust (they lack fileno() and mode). However,
1598 the recovery facilities which rely on these things existing will
1599 not work.
1600
1601 2004-04-01 Fernando Perez <fperez@colorado.edu>
1602
1603 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
1604 use the new getoutputerror() function, so it properly
1605 distinguishes stdout/err.
1606
1607 * IPython/genutils.py (getoutputerror): added a function to
1608 capture separately the standard output and error of a command.
1609 After a comment from dang on the mailing lists. This code is
1610 basically a modified version of commands.getstatusoutput(), from
1611 the standard library.
1612
1613 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
1614 '!!' as a special syntax (shorthand) to access @sx.
1615
1616 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
1617 command and return its output as a list split on '\n'.
1618
1619 2004-03-31 Fernando Perez <fperez@colorado.edu>
1620
1621 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
1622 method to dictionaries used as FakeModule instances if they lack
1623 it. At least pydoc in python2.3 breaks for runtime-defined
1624 functions without this hack. At some point I need to _really_
1625 understand what FakeModule is doing, because it's a gross hack.
1626 But it solves Arnd's problem for now...
1627
1628 2004-02-27 Fernando Perez <fperez@colorado.edu>
1629
1630 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
1631 mode would behave erratically. Also increased the number of
1632 possible logs in rotate mod to 999. Thanks to Rod Holland
1633 <rhh@StructureLABS.com> for the report and fixes.
1634
1635 2004-02-26 Fernando Perez <fperez@colorado.edu>
1636
1637 * IPython/genutils.py (page): Check that the curses module really
1638 has the initscr attribute before trying to use it. For some
1639 reason, the Solaris curses module is missing this. I think this
1640 should be considered a Solaris python bug, but I'm not sure.
1641
1642 2004-01-17 Fernando Perez <fperez@colorado.edu>
1643
1644 * IPython/genutils.py (Stream.__init__): Changes to try to make
1645 ipython robust against stdin/out/err being closed by the user.
1646 This is 'user error' (and blocks a normal python session, at least
1647 the stdout case). However, Ipython should be able to survive such
1648 instances of abuse as gracefully as possible. To simplify the
1649 coding and maintain compatibility with Gary Bishop's Term
1650 contributions, I've made use of classmethods for this. I think
1651 this introduces a dependency on python 2.2.
1652
1653 2004-01-13 Fernando Perez <fperez@colorado.edu>
1654
1655 * IPython/numutils.py (exp_safe): simplified the code a bit and
1656 removed the need for importing the kinds module altogether.
1657
1658 2004-01-06 Fernando Perez <fperez@colorado.edu>
1659
1660 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
1661 a magic function instead, after some community feedback. No
1662 special syntax will exist for it, but its name is deliberately
1663 very short.
1664
1665 2003-12-20 Fernando Perez <fperez@colorado.edu>
1666
1667 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
1668 new functionality, to automagically assign the result of a shell
1669 command to a variable. I'll solicit some community feedback on
1670 this before making it permanent.
1671
1672 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
1673 requested about callables for which inspect couldn't obtain a
1674 proper argspec. Thanks to a crash report sent by Etienne
1675 Posthumus <etienne-AT-apple01.cs.vu.nl>.
1676
1677 2003-12-09 Fernando Perez <fperez@colorado.edu>
1678
1679 * IPython/genutils.py (page): patch for the pager to work across
1680 various versions of Windows. By Gary Bishop.
1681
1682 2003-12-04 Fernando Perez <fperez@colorado.edu>
1683
1684 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
1685 Gnuplot.py version 1.7, whose internal names changed quite a bit.
1686 While I tested this and it looks ok, there may still be corner
1687 cases I've missed.
1688
1689 2003-12-01 Fernando Perez <fperez@colorado.edu>
1690
1691 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
1692 where a line like 'p,q=1,2' would fail because the automagic
1693 system would be triggered for @p.
1694
1695 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
1696 cleanups, code unmodified.
1697
1698 * IPython/genutils.py (Term): added a class for IPython to handle
1699 output. In most cases it will just be a proxy for stdout/err, but
1700 having this allows modifications to be made for some platforms,
1701 such as handling color escapes under Windows. All of this code
1702 was contributed by Gary Bishop, with minor modifications by me.
1703 The actual changes affect many files.
1704
1705 2003-11-30 Fernando Perez <fperez@colorado.edu>
1706
1707 * IPython/iplib.py (file_matches): new completion code, courtesy
1708 of Jeff Collins. This enables filename completion again under
1709 python 2.3, which disabled it at the C level.
1710
1711 2003-11-11 Fernando Perez <fperez@colorado.edu>
1712
1713 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
1714 for Numeric.array(map(...)), but often convenient.
1715
1716 2003-11-05 Fernando Perez <fperez@colorado.edu>
1717
1718 * IPython/numutils.py (frange): Changed a call from int() to
1719 int(round()) to prevent a problem reported with arange() in the
1720 numpy list.
1721
1722 2003-10-06 Fernando Perez <fperez@colorado.edu>
1723
1724 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
1725 prevent crashes if sys lacks an argv attribute (it happens with
1726 embedded interpreters which build a bare-bones sys module).
1727 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
1728
1729 2003-09-24 Fernando Perez <fperez@colorado.edu>
1730
1731 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
1732 to protect against poorly written user objects where __getattr__
1733 raises exceptions other than AttributeError. Thanks to a bug
1734 report by Oliver Sander <osander-AT-gmx.de>.
1735
1736 * IPython/FakeModule.py (FakeModule.__repr__): this method was
1737 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
1738
1739 2003-09-09 Fernando Perez <fperez@colorado.edu>
1740
1741 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1742 unpacking a list whith a callable as first element would
1743 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
1744 Collins.
1745
1746 2003-08-25 *** Released version 0.5.0
1747
1748 2003-08-22 Fernando Perez <fperez@colorado.edu>
1749
1750 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
1751 improperly defined user exceptions. Thanks to feedback from Mark
1752 Russell <mrussell-AT-verio.net>.
1753
1754 2003-08-20 Fernando Perez <fperez@colorado.edu>
1755
1756 * IPython/OInspect.py (Inspector.pinfo): changed String Form
1757 printing so that it would print multi-line string forms starting
1758 with a new line. This way the formatting is better respected for
1759 objects which work hard to make nice string forms.
1760
1761 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
1762 autocall would overtake data access for objects with both
1763 __getitem__ and __call__.
1764
1765 2003-08-19 *** Released version 0.5.0-rc1
1766
1767 2003-08-19 Fernando Perez <fperez@colorado.edu>
1768
1769 * IPython/deep_reload.py (load_tail): single tiny change here
1770 seems to fix the long-standing bug of dreload() failing to work
1771 for dotted names. But this module is pretty tricky, so I may have
1772 missed some subtlety. Needs more testing!.
1773
1774 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
1775 exceptions which have badly implemented __str__ methods.
1776 (VerboseTB.text): harden against inspect.getinnerframes crashing,
1777 which I've been getting reports about from Python 2.3 users. I
1778 wish I had a simple test case to reproduce the problem, so I could
1779 either write a cleaner workaround or file a bug report if
1780 necessary.
1781
1782 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
1783 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
1784 a bug report by Tjabo Kloppenburg.
1785
1786 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
1787 crashes. Wrapped the pdb call in a blanket try/except, since pdb
1788 seems rather unstable. Thanks to a bug report by Tjabo
1789 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
1790
1791 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
1792 this out soon because of the critical fixes in the inner loop for
1793 generators.
1794
1795 * IPython/Magic.py (Magic.getargspec): removed. This (and
1796 _get_def) have been obsoleted by OInspect for a long time, I
1797 hadn't noticed that they were dead code.
1798 (Magic._ofind): restored _ofind functionality for a few literals
1799 (those in ["''",'""','[]','{}','()']). But it won't work anymore
1800 for things like "hello".capitalize?, since that would require a
1801 potentially dangerous eval() again.
1802
1803 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
1804 logic a bit more to clean up the escapes handling and minimize the
1805 use of _ofind to only necessary cases. The interactive 'feel' of
1806 IPython should have improved quite a bit with the changes in
1807 _prefilter and _ofind (besides being far safer than before).
1808
1809 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
1810 obscure, never reported). Edit would fail to find the object to
1811 edit under some circumstances.
1812 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
1813 which were causing double-calling of generators. Those eval calls
1814 were _very_ dangerous, since code with side effects could be
1815 triggered. As they say, 'eval is evil'... These were the
1816 nastiest evals in IPython. Besides, _ofind is now far simpler,
1817 and it should also be quite a bit faster. Its use of inspect is
1818 also safer, so perhaps some of the inspect-related crashes I've
1819 seen lately with Python 2.3 might be taken care of. That will
1820 need more testing.
1821
1822 2003-08-17 Fernando Perez <fperez@colorado.edu>
1823
1824 * IPython/iplib.py (InteractiveShell._prefilter): significant
1825 simplifications to the logic for handling user escapes. Faster
1826 and simpler code.
1827
1828 2003-08-14 Fernando Perez <fperez@colorado.edu>
1829
1830 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
1831 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
1832 but it should be quite a bit faster. And the recursive version
1833 generated O(log N) intermediate storage for all rank>1 arrays,
1834 even if they were contiguous.
1835 (l1norm): Added this function.
1836 (norm): Added this function for arbitrary norms (including
1837 l-infinity). l1 and l2 are still special cases for convenience
1838 and speed.
1839
1840 2003-08-03 Fernando Perez <fperez@colorado.edu>
1841
1842 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
1843 exceptions, which now raise PendingDeprecationWarnings in Python
1844 2.3. There were some in Magic and some in Gnuplot2.
1845
1846 2003-06-30 Fernando Perez <fperez@colorado.edu>
1847
1848 * IPython/genutils.py (page): modified to call curses only for
1849 terminals where TERM=='xterm'. After problems under many other
1850 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
1851
1852 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
1853 would be triggered when readline was absent. This was just an old
1854 debugging statement I'd forgotten to take out.
1855
1856 2003-06-20 Fernando Perez <fperez@colorado.edu>
1857
1858 * IPython/genutils.py (clock): modified to return only user time
1859 (not counting system time), after a discussion on scipy. While
1860 system time may be a useful quantity occasionally, it may much
1861 more easily be skewed by occasional swapping or other similar
1862 activity.
1863
1864 2003-06-05 Fernando Perez <fperez@colorado.edu>
1865
1866 * IPython/numutils.py (identity): new function, for building
1867 arbitrary rank Kronecker deltas (mostly backwards compatible with
1868 Numeric.identity)
1869
1870 2003-06-03 Fernando Perez <fperez@colorado.edu>
1871
1872 * IPython/iplib.py (InteractiveShell.handle_magic): protect
1873 arguments passed to magics with spaces, to allow trailing '\' to
1874 work normally (mainly for Windows users).
1875
1876 2003-05-29 Fernando Perez <fperez@colorado.edu>
1877
1878 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
1879 instead of pydoc.help. This fixes a bizarre behavior where
1880 printing '%s' % locals() would trigger the help system. Now
1881 ipython behaves like normal python does.
1882
1883 Note that if one does 'from pydoc import help', the bizarre
1884 behavior returns, but this will also happen in normal python, so
1885 it's not an ipython bug anymore (it has to do with how pydoc.help
1886 is implemented).
1887
1888 2003-05-22 Fernando Perez <fperez@colorado.edu>
1889
1890 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
1891 return [] instead of None when nothing matches, also match to end
1892 of line. Patch by Gary Bishop.
1893
1894 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
1895 protection as before, for files passed on the command line. This
1896 prevents the CrashHandler from kicking in if user files call into
1897 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
1898 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
1899
1900 2003-05-20 *** Released version 0.4.0
1901
1902 2003-05-20 Fernando Perez <fperez@colorado.edu>
1903
1904 * setup.py: added support for manpages. It's a bit hackish b/c of
1905 a bug in the way the bdist_rpm distutils target handles gzipped
1906 manpages, but it works. After a patch by Jack.
1907
1908 2003-05-19 Fernando Perez <fperez@colorado.edu>
1909
1910 * IPython/numutils.py: added a mockup of the kinds module, since
1911 it was recently removed from Numeric. This way, numutils will
1912 work for all users even if they are missing kinds.
1913
1914 * IPython/Magic.py (Magic._ofind): Harden against an inspect
1915 failure, which can occur with SWIG-wrapped extensions. After a
1916 crash report from Prabhu.
1917
1918 2003-05-16 Fernando Perez <fperez@colorado.edu>
1919
1920 * IPython/iplib.py (InteractiveShell.excepthook): New method to
1921 protect ipython from user code which may call directly
1922 sys.excepthook (this looks like an ipython crash to the user, even
1923 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
1924 This is especially important to help users of WxWindows, but may
1925 also be useful in other cases.
1926
1927 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
1928 an optional tb_offset to be specified, and to preserve exception
1929 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
1930
1931 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
1932
1933 2003-05-15 Fernando Perez <fperez@colorado.edu>
1934
1935 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
1936 installing for a new user under Windows.
1937
1938 2003-05-12 Fernando Perez <fperez@colorado.edu>
1939
1940 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
1941 handler for Emacs comint-based lines. Currently it doesn't do
1942 much (but importantly, it doesn't update the history cache). In
1943 the future it may be expanded if Alex needs more functionality
1944 there.
1945
1946 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
1947 info to crash reports.
1948
1949 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
1950 just like Python's -c. Also fixed crash with invalid -color
1951 option value at startup. Thanks to Will French
1952 <wfrench-AT-bestweb.net> for the bug report.
1953
1954 2003-05-09 Fernando Perez <fperez@colorado.edu>
1955
1956 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
1957 to EvalDict (it's a mapping, after all) and simplified its code
1958 quite a bit, after a nice discussion on c.l.py where Gustavo
1959 Córdova <gcordova-AT-sismex.com> suggested the new version.
1960
1961 2003-04-30 Fernando Perez <fperez@colorado.edu>
1962
1963 * IPython/genutils.py (timings_out): modified it to reduce its
1964 overhead in the common reps==1 case.
1965
1966 2003-04-29 Fernando Perez <fperez@colorado.edu>
1967
1968 * IPython/genutils.py (timings_out): Modified to use the resource
1969 module, which avoids the wraparound problems of time.clock().
1970
1971 2003-04-17 *** Released version 0.2.15pre4
1972
1973 2003-04-17 Fernando Perez <fperez@colorado.edu>
1974
1975 * setup.py (scriptfiles): Split windows-specific stuff over to a
1976 separate file, in an attempt to have a Windows GUI installer.
1977 That didn't work, but part of the groundwork is done.
1978
1979 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
1980 indent/unindent with 4 spaces. Particularly useful in combination
1981 with the new auto-indent option.
1982
1983 2003-04-16 Fernando Perez <fperez@colorado.edu>
1984
1985 * IPython/Magic.py: various replacements of self.rc for
1986 self.shell.rc. A lot more remains to be done to fully disentangle
1987 this class from the main Shell class.
1988
1989 * IPython/GnuplotRuntime.py: added checks for mouse support so
1990 that we don't try to enable it if the current gnuplot doesn't
1991 really support it. Also added checks so that we don't try to
1992 enable persist under Windows (where Gnuplot doesn't recognize the
1993 option).
1994
1995 * IPython/iplib.py (InteractiveShell.interact): Added optional
1996 auto-indenting code, after a patch by King C. Shu
1997 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
1998 get along well with pasting indented code. If I ever figure out
1999 how to make that part go well, it will become on by default.
2000
2001 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2002 crash ipython if there was an unmatched '%' in the user's prompt
2003 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2004
2005 * IPython/iplib.py (InteractiveShell.interact): removed the
2006 ability to ask the user whether he wants to crash or not at the
2007 'last line' exception handler. Calling functions at that point
2008 changes the stack, and the error reports would have incorrect
2009 tracebacks.
2010
2011 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2012 pass through a peger a pretty-printed form of any object. After a
2013 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2014
2015 2003-04-14 Fernando Perez <fperez@colorado.edu>
2016
2017 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2018 all files in ~ would be modified at first install (instead of
2019 ~/.ipython). This could be potentially disastrous, as the
2020 modification (make line-endings native) could damage binary files.
2021
2022 2003-04-10 Fernando Perez <fperez@colorado.edu>
2023
2024 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2025 handle only lines which are invalid python. This now means that
2026 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2027 for the bug report.
2028
2029 2003-04-01 Fernando Perez <fperez@colorado.edu>
2030
2031 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2032 where failing to set sys.last_traceback would crash pdb.pm().
2033 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2034 report.
2035
2036 2003-03-25 Fernando Perez <fperez@colorado.edu>
2037
2038 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2039 before printing it (it had a lot of spurious blank lines at the
2040 end).
2041
2042 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2043 output would be sent 21 times! Obviously people don't use this
2044 too often, or I would have heard about it.
2045
2046 2003-03-24 Fernando Perez <fperez@colorado.edu>
2047
2048 * setup.py (scriptfiles): renamed the data_files parameter from
2049 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2050 for the patch.
2051
2052 2003-03-20 Fernando Perez <fperez@colorado.edu>
2053
2054 * IPython/genutils.py (error): added error() and fatal()
2055 functions.
2056
2057 2003-03-18 *** Released version 0.2.15pre3
2058
2059 2003-03-18 Fernando Perez <fperez@colorado.edu>
2060
2061 * setupext/install_data_ext.py
2062 (install_data_ext.initialize_options): Class contributed by Jack
2063 Moffit for fixing the old distutils hack. He is sending this to
2064 the distutils folks so in the future we may not need it as a
2065 private fix.
2066
2067 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2068 changes for Debian packaging. See his patch for full details.
2069 The old distutils hack of making the ipythonrc* files carry a
2070 bogus .py extension is gone, at last. Examples were moved to a
2071 separate subdir under doc/, and the separate executable scripts
2072 now live in their own directory. Overall a great cleanup. The
2073 manual was updated to use the new files, and setup.py has been
2074 fixed for this setup.
2075
2076 * IPython/PyColorize.py (Parser.usage): made non-executable and
2077 created a pycolor wrapper around it to be included as a script.
2078
2079 2003-03-12 *** Released version 0.2.15pre2
2080
2081 2003-03-12 Fernando Perez <fperez@colorado.edu>
2082
2083 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2084 long-standing problem with garbage characters in some terminals.
2085 The issue was really that the \001 and \002 escapes must _only_ be
2086 passed to input prompts (which call readline), but _never_ to
2087 normal text to be printed on screen. I changed ColorANSI to have
2088 two classes: TermColors and InputTermColors, each with the
2089 appropriate escapes for input prompts or normal text. The code in
2090 Prompts.py got slightly more complicated, but this very old and
2091 annoying bug is finally fixed.
2092
2093 All the credit for nailing down the real origin of this problem
2094 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2095 *Many* thanks to him for spending quite a bit of effort on this.
2096
2097 2003-03-05 *** Released version 0.2.15pre1
2098
2099 2003-03-03 Fernando Perez <fperez@colorado.edu>
2100
2101 * IPython/FakeModule.py: Moved the former _FakeModule to a
2102 separate file, because it's also needed by Magic (to fix a similar
2103 pickle-related issue in @run).
2104
2105 2003-03-02 Fernando Perez <fperez@colorado.edu>
2106
2107 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2108 the autocall option at runtime.
2109 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2110 across Magic.py to start separating Magic from InteractiveShell.
2111 (Magic._ofind): Fixed to return proper namespace for dotted
2112 names. Before, a dotted name would always return 'not currently
2113 defined', because it would find the 'parent'. s.x would be found,
2114 but since 'x' isn't defined by itself, it would get confused.
2115 (Magic.magic_run): Fixed pickling problems reported by Ralf
2116 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2117 that I'd used when Mike Heeter reported similar issues at the
2118 top-level, but now for @run. It boils down to injecting the
2119 namespace where code is being executed with something that looks
2120 enough like a module to fool pickle.dump(). Since a pickle stores
2121 a named reference to the importing module, we need this for
2122 pickles to save something sensible.
2123
2124 * IPython/ipmaker.py (make_IPython): added an autocall option.
2125
2126 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2127 the auto-eval code. Now autocalling is an option, and the code is
2128 also vastly safer. There is no more eval() involved at all.
2129
2130 2003-03-01 Fernando Perez <fperez@colorado.edu>
2131
2132 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2133 dict with named keys instead of a tuple.
2134
2135 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2136
2137 * setup.py (make_shortcut): Fixed message about directories
2138 created during Windows installation (the directories were ok, just
2139 the printed message was misleading). Thanks to Chris Liechti
2140 <cliechti-AT-gmx.net> for the heads up.
2141
2142 2003-02-21 Fernando Perez <fperez@colorado.edu>
2143
2144 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2145 of ValueError exception when checking for auto-execution. This
2146 one is raised by things like Numeric arrays arr.flat when the
2147 array is non-contiguous.
2148
2149 2003-01-31 Fernando Perez <fperez@colorado.edu>
2150
2151 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2152 not return any value at all (even though the command would get
2153 executed).
2154 (xsys): Flush stdout right after printing the command to ensure
2155 proper ordering of commands and command output in the total
2156 output.
2157 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2158 system/getoutput as defaults. The old ones are kept for
2159 compatibility reasons, so no code which uses this library needs
2160 changing.
2161
2162 2003-01-27 *** Released version 0.2.14
2163
2164 2003-01-25 Fernando Perez <fperez@colorado.edu>
2165
2166 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2167 functions defined in previous edit sessions could not be re-edited
2168 (because the temp files were immediately removed). Now temp files
2169 are removed only at IPython's exit.
2170 (Magic.magic_run): Improved @run to perform shell-like expansions
2171 on its arguments (~users and $VARS). With this, @run becomes more
2172 like a normal command-line.
2173
2174 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2175 bugs related to embedding and cleaned up that code. A fairly
2176 important one was the impossibility to access the global namespace
2177 through the embedded IPython (only local variables were visible).
2178
2179 2003-01-14 Fernando Perez <fperez@colorado.edu>
2180
2181 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2182 auto-calling to be a bit more conservative. Now it doesn't get
2183 triggered if any of '!=()<>' are in the rest of the input line, to
2184 allow comparing callables. Thanks to Alex for the heads up.
2185
2186 2003-01-07 Fernando Perez <fperez@colorado.edu>
2187
2188 * IPython/genutils.py (page): fixed estimation of the number of
2189 lines in a string to be paged to simply count newlines. This
2190 prevents over-guessing due to embedded escape sequences. A better
2191 long-term solution would involve stripping out the control chars
2192 for the count, but it's potentially so expensive I just don't
2193 think it's worth doing.
2194
2195 2002-12-19 *** Released version 0.2.14pre50
2196
2197 2002-12-19 Fernando Perez <fperez@colorado.edu>
2198
2199 * tools/release (version): Changed release scripts to inform
2200 Andrea and build a NEWS file with a list of recent changes.
2201
2202 * IPython/ColorANSI.py (__all__): changed terminal detection
2203 code. Seems to work better for xterms without breaking
2204 konsole. Will need more testing to determine if WinXP and Mac OSX
2205 also work ok.
2206
2207 2002-12-18 *** Released version 0.2.14pre49
2208
2209 2002-12-18 Fernando Perez <fperez@colorado.edu>
2210
2211 * Docs: added new info about Mac OSX, from Andrea.
2212
2213 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2214 allow direct plotting of python strings whose format is the same
2215 of gnuplot data files.
2216
2217 2002-12-16 Fernando Perez <fperez@colorado.edu>
2218
2219 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2220 value of exit question to be acknowledged.
2221
2222 2002-12-03 Fernando Perez <fperez@colorado.edu>
2223
2224 * IPython/ipmaker.py: removed generators, which had been added
2225 by mistake in an earlier debugging run. This was causing trouble
2226 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2227 for pointing this out.
2228
2229 2002-11-17 Fernando Perez <fperez@colorado.edu>
2230
2231 * Manual: updated the Gnuplot section.
2232
2233 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2234 a much better split of what goes in Runtime and what goes in
2235 Interactive.
2236
2237 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2238 being imported from iplib.
2239
2240 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2241 for command-passing. Now the global Gnuplot instance is called
2242 'gp' instead of 'g', which was really a far too fragile and
2243 common name.
2244
2245 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2246 bounding boxes generated by Gnuplot for square plots.
2247
2248 * IPython/genutils.py (popkey): new function added. I should
2249 suggest this on c.l.py as a dict method, it seems useful.
2250
2251 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2252 to transparently handle PostScript generation. MUCH better than
2253 the previous plot_eps/replot_eps (which I removed now). The code
2254 is also fairly clean and well documented now (including
2255 docstrings).
2256
2257 2002-11-13 Fernando Perez <fperez@colorado.edu>
2258
2259 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2260 (inconsistent with options).
2261
2262 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2263 manually disabled, I don't know why. Fixed it.
2264 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2265 eps output.
2266
2267 2002-11-12 Fernando Perez <fperez@colorado.edu>
2268
2269 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2270 don't propagate up to caller. Fixes crash reported by François
2271 Pinard.
2272
2273 2002-11-09 Fernando Perez <fperez@colorado.edu>
2274
2275 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2276 history file for new users.
2277 (make_IPython): fixed bug where initial install would leave the
2278 user running in the .ipython dir.
2279 (make_IPython): fixed bug where config dir .ipython would be
2280 created regardless of the given -ipythondir option. Thanks to Cory
2281 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2282
2283 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2284 type confirmations. Will need to use it in all of IPython's code
2285 consistently.
2286
2287 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2288 context to print 31 lines instead of the default 5. This will make
2289 the crash reports extremely detailed in case the problem is in
2290 libraries I don't have access to.
2291
2292 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2293 line of defense' code to still crash, but giving users fair
2294 warning. I don't want internal errors to go unreported: if there's
2295 an internal problem, IPython should crash and generate a full
2296 report.
2297
2298 2002-11-08 Fernando Perez <fperez@colorado.edu>
2299
2300 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2301 otherwise uncaught exceptions which can appear if people set
2302 sys.stdout to something badly broken. Thanks to a crash report
2303 from henni-AT-mail.brainbot.com.
2304
2305 2002-11-04 Fernando Perez <fperez@colorado.edu>
2306
2307 * IPython/iplib.py (InteractiveShell.interact): added
2308 __IPYTHON__active to the builtins. It's a flag which goes on when
2309 the interaction starts and goes off again when it stops. This
2310 allows embedding code to detect being inside IPython. Before this
2311 was done via __IPYTHON__, but that only shows that an IPython
2312 instance has been created.
2313
2314 * IPython/Magic.py (Magic.magic_env): I realized that in a
2315 UserDict, instance.data holds the data as a normal dict. So I
2316 modified @env to return os.environ.data instead of rebuilding a
2317 dict by hand.
2318
2319 2002-11-02 Fernando Perez <fperez@colorado.edu>
2320
2321 * IPython/genutils.py (warn): changed so that level 1 prints no
2322 header. Level 2 is now the default (with 'WARNING' header, as
2323 before). I think I tracked all places where changes were needed in
2324 IPython, but outside code using the old level numbering may have
2325 broken.
2326
2327 * IPython/iplib.py (InteractiveShell.runcode): added this to
2328 handle the tracebacks in SystemExit traps correctly. The previous
2329 code (through interact) was printing more of the stack than
2330 necessary, showing IPython internal code to the user.
2331
2332 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2333 default. Now that the default at the confirmation prompt is yes,
2334 it's not so intrusive. François' argument that ipython sessions
2335 tend to be complex enough not to lose them from an accidental C-d,
2336 is a valid one.
2337
2338 * IPython/iplib.py (InteractiveShell.interact): added a
2339 showtraceback() call to the SystemExit trap, and modified the exit
2340 confirmation to have yes as the default.
2341
2342 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2343 this file. It's been gone from the code for a long time, this was
2344 simply leftover junk.
2345
2346 2002-11-01 Fernando Perez <fperez@colorado.edu>
2347
2348 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2349 added. If set, IPython now traps EOF and asks for
2350 confirmation. After a request by François Pinard.
2351
2352 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2353 of @abort, and with a new (better) mechanism for handling the
2354 exceptions.
2355
2356 2002-10-27 Fernando Perez <fperez@colorado.edu>
2357
2358 * IPython/usage.py (__doc__): updated the --help information and
2359 the ipythonrc file to indicate that -log generates
2360 ./ipython.log. Also fixed the corresponding info in @logstart.
2361 This and several other fixes in the manuals thanks to reports by
2362 François Pinard <pinard-AT-iro.umontreal.ca>.
2363
2364 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2365 refer to @logstart (instead of @log, which doesn't exist).
2366
2367 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2368 AttributeError crash. Thanks to Christopher Armstrong
2369 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2370 introduced recently (in 0.2.14pre37) with the fix to the eval
2371 problem mentioned below.
2372
2373 2002-10-17 Fernando Perez <fperez@colorado.edu>
2374
2375 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2376 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2377
2378 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2379 this function to fix a problem reported by Alex Schmolck. He saw
2380 it with list comprehensions and generators, which were getting
2381 called twice. The real problem was an 'eval' call in testing for
2382 automagic which was evaluating the input line silently.
2383
2384 This is a potentially very nasty bug, if the input has side
2385 effects which must not be repeated. The code is much cleaner now,
2386 without any blanket 'except' left and with a regexp test for
2387 actual function names.
2388
2389 But an eval remains, which I'm not fully comfortable with. I just
2390 don't know how to find out if an expression could be a callable in
2391 the user's namespace without doing an eval on the string. However
2392 that string is now much more strictly checked so that no code
2393 slips by, so the eval should only happen for things that can
2394 really be only function/method names.
2395
2396 2002-10-15 Fernando Perez <fperez@colorado.edu>
2397
2398 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2399 OSX information to main manual, removed README_Mac_OSX file from
2400 distribution. Also updated credits for recent additions.
2401
2402 2002-10-10 Fernando Perez <fperez@colorado.edu>
2403
2404 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2405 terminal-related issues. Many thanks to Andrea Riciputi
2406 <andrea.riciputi-AT-libero.it> for writing it.
2407
2408 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2409 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2410
2411 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2412 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2413 <syver-en-AT-online.no> who both submitted patches for this problem.
2414
2415 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2416 global embedding to make sure that things don't overwrite user
2417 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2418
2419 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2420 compatibility. Thanks to Hayden Callow
2421 <h.callow-AT-elec.canterbury.ac.nz>
2422
2423 2002-10-04 Fernando Perez <fperez@colorado.edu>
2424
2425 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2426 Gnuplot.File objects.
2427
2428 2002-07-23 Fernando Perez <fperez@colorado.edu>
2429
2430 * IPython/genutils.py (timing): Added timings() and timing() for
2431 quick access to the most commonly needed data, the execution
2432 times. Old timing() renamed to timings_out().
2433
2434 2002-07-18 Fernando Perez <fperez@colorado.edu>
2435
2436 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2437 bug with nested instances disrupting the parent's tab completion.
2438
2439 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2440 all_completions code to begin the emacs integration.
2441
2442 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2443 argument to allow titling individual arrays when plotting.
2444
2445 2002-07-15 Fernando Perez <fperez@colorado.edu>
2446
2447 * setup.py (make_shortcut): changed to retrieve the value of
2448 'Program Files' directory from the registry (this value changes in
2449 non-english versions of Windows). Thanks to Thomas Fanslau
2450 <tfanslau-AT-gmx.de> for the report.
2451
2452 2002-07-10 Fernando Perez <fperez@colorado.edu>
2453
2454 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2455 a bug in pdb, which crashes if a line with only whitespace is
2456 entered. Bug report submitted to sourceforge.
2457
2458 2002-07-09 Fernando Perez <fperez@colorado.edu>
2459
2460 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2461 reporting exceptions (it's a bug in inspect.py, I just set a
2462 workaround).
2463
2464 2002-07-08 Fernando Perez <fperez@colorado.edu>
2465
2466 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2467 __IPYTHON__ in __builtins__ to show up in user_ns.
2468
2469 2002-07-03 Fernando Perez <fperez@colorado.edu>
2470
2471 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2472 name from @gp_set_instance to @gp_set_default.
2473
2474 * IPython/ipmaker.py (make_IPython): default editor value set to
2475 '0' (a string), to match the rc file. Otherwise will crash when
2476 .strip() is called on it.
2477
2478
2479 2002-06-28 Fernando Perez <fperez@colorado.edu>
2480
2481 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2482 of files in current directory when a file is executed via
2483 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2484
2485 * setup.py (manfiles): fix for rpm builds, submitted by RA
2486 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2487
2488 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2489 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2490 string!). A. Schmolck caught this one.
2491
2492 2002-06-27 Fernando Perez <fperez@colorado.edu>
2493
2494 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2495 defined files at the cmd line. __name__ wasn't being set to
2496 __main__.
2497
2498 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2499 regular lists and tuples besides Numeric arrays.
2500
2501 * IPython/Prompts.py (CachedOutput.__call__): Added output
2502 supression for input ending with ';'. Similar to Mathematica and
2503 Matlab. The _* vars and Out[] list are still updated, just like
2504 Mathematica behaves.
2505
2506 2002-06-25 Fernando Perez <fperez@colorado.edu>
2507
2508 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2509 .ini extensions for profiels under Windows.
2510
2511 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2512 string form. Fix contributed by Alexander Schmolck
2513 <a.schmolck-AT-gmx.net>
2514
2515 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2516 pre-configured Gnuplot instance.
2517
2518 2002-06-21 Fernando Perez <fperez@colorado.edu>
2519
2520 * IPython/numutils.py (exp_safe): new function, works around the
2521 underflow problems in Numeric.
2522 (log2): New fn. Safe log in base 2: returns exact integer answer
2523 for exact integer powers of 2.
2524
2525 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2526 properly.
2527
2528 2002-06-20 Fernando Perez <fperez@colorado.edu>
2529
2530 * IPython/genutils.py (timing): new function like
2531 Mathematica's. Similar to time_test, but returns more info.
2532
2533 2002-06-18 Fernando Perez <fperez@colorado.edu>
2534
2535 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2536 according to Mike Heeter's suggestions.
2537
2538 2002-06-16 Fernando Perez <fperez@colorado.edu>
2539
2540 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2541 system. GnuplotMagic is gone as a user-directory option. New files
2542 make it easier to use all the gnuplot stuff both from external
2543 programs as well as from IPython. Had to rewrite part of
2544 hardcopy() b/c of a strange bug: often the ps files simply don't
2545 get created, and require a repeat of the command (often several
2546 times).
2547
2548 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2549 resolve output channel at call time, so that if sys.stderr has
2550 been redirected by user this gets honored.
2551
2552 2002-06-13 Fernando Perez <fperez@colorado.edu>
2553
2554 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2555 IPShell. Kept a copy with the old names to avoid breaking people's
2556 embedded code.
2557
2558 * IPython/ipython: simplified it to the bare minimum after
2559 Holger's suggestions. Added info about how to use it in
2560 PYTHONSTARTUP.
2561
2562 * IPython/Shell.py (IPythonShell): changed the options passing
2563 from a string with funky %s replacements to a straight list. Maybe
2564 a bit more typing, but it follows sys.argv conventions, so there's
2565 less special-casing to remember.
2566
2567 2002-06-12 Fernando Perez <fperez@colorado.edu>
2568
2569 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2570 command. Thanks to a suggestion by Mike Heeter.
2571 (Magic.magic_pfile): added behavior to look at filenames if given
2572 arg is not a defined object.
2573 (Magic.magic_save): New @save function to save code snippets. Also
2574 a Mike Heeter idea.
2575
2576 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2577 plot() and replot(). Much more convenient now, especially for
2578 interactive use.
2579
2580 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2581 filenames.
2582
2583 2002-06-02 Fernando Perez <fperez@colorado.edu>
2584
2585 * IPython/Struct.py (Struct.__init__): modified to admit
2586 initialization via another struct.
2587
2588 * IPython/genutils.py (SystemExec.__init__): New stateful
2589 interface to xsys and bq. Useful for writing system scripts.
2590
2591 2002-05-30 Fernando Perez <fperez@colorado.edu>
2592
2593 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2594 documents. This will make the user download smaller (it's getting
2595 too big).
2596
2597 2002-05-29 Fernando Perez <fperez@colorado.edu>
2598
2599 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2600 fix problems with shelve and pickle. Seems to work, but I don't
2601 know if corner cases break it. Thanks to Mike Heeter
2602 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
2603
2604 2002-05-24 Fernando Perez <fperez@colorado.edu>
2605
2606 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
2607 macros having broken.
2608
2609 2002-05-21 Fernando Perez <fperez@colorado.edu>
2610
2611 * IPython/Magic.py (Magic.magic_logstart): fixed recently
2612 introduced logging bug: all history before logging started was
2613 being written one character per line! This came from the redesign
2614 of the input history as a special list which slices to strings,
2615 not to lists.
2616
2617 2002-05-20 Fernando Perez <fperez@colorado.edu>
2618
2619 * IPython/Prompts.py (CachedOutput.__init__): made the color table
2620 be an attribute of all classes in this module. The design of these
2621 classes needs some serious overhauling.
2622
2623 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
2624 which was ignoring '_' in option names.
2625
2626 * IPython/ultraTB.py (FormattedTB.__init__): Changed
2627 'Verbose_novars' to 'Context' and made it the new default. It's a
2628 bit more readable and also safer than verbose.
2629
2630 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
2631 triple-quoted strings.
2632
2633 * IPython/OInspect.py (__all__): new module exposing the object
2634 introspection facilities. Now the corresponding magics are dummy
2635 wrappers around this. Having this module will make it much easier
2636 to put these functions into our modified pdb.
2637 This new object inspector system uses the new colorizing module,
2638 so source code and other things are nicely syntax highlighted.
2639
2640 2002-05-18 Fernando Perez <fperez@colorado.edu>
2641
2642 * IPython/ColorANSI.py: Split the coloring tools into a separate
2643 module so I can use them in other code easier (they were part of
2644 ultraTB).
2645
2646 2002-05-17 Fernando Perez <fperez@colorado.edu>
2647
2648 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2649 fixed it to set the global 'g' also to the called instance, as
2650 long as 'g' was still a gnuplot instance (so it doesn't overwrite
2651 user's 'g' variables).
2652
2653 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
2654 global variables (aliases to _ih,_oh) so that users which expect
2655 In[5] or Out[7] to work aren't unpleasantly surprised.
2656 (InputList.__getslice__): new class to allow executing slices of
2657 input history directly. Very simple class, complements the use of
2658 macros.
2659
2660 2002-05-16 Fernando Perez <fperez@colorado.edu>
2661
2662 * setup.py (docdirbase): make doc directory be just doc/IPython
2663 without version numbers, it will reduce clutter for users.
2664
2665 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
2666 execfile call to prevent possible memory leak. See for details:
2667 http://mail.python.org/pipermail/python-list/2002-February/088476.html
2668
2669 2002-05-15 Fernando Perez <fperez@colorado.edu>
2670
2671 * IPython/Magic.py (Magic.magic_psource): made the object
2672 introspection names be more standard: pdoc, pdef, pfile and
2673 psource. They all print/page their output, and it makes
2674 remembering them easier. Kept old names for compatibility as
2675 aliases.
2676
2677 2002-05-14 Fernando Perez <fperez@colorado.edu>
2678
2679 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
2680 what the mouse problem was. The trick is to use gnuplot with temp
2681 files and NOT with pipes (for data communication), because having
2682 both pipes and the mouse on is bad news.
2683
2684 2002-05-13 Fernando Perez <fperez@colorado.edu>
2685
2686 * IPython/Magic.py (Magic._ofind): fixed namespace order search
2687 bug. Information would be reported about builtins even when
2688 user-defined functions overrode them.
2689
2690 2002-05-11 Fernando Perez <fperez@colorado.edu>
2691
2692 * IPython/__init__.py (__all__): removed FlexCompleter from
2693 __all__ so that things don't fail in platforms without readline.
2694
2695 2002-05-10 Fernando Perez <fperez@colorado.edu>
2696
2697 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
2698 it requires Numeric, effectively making Numeric a dependency for
2699 IPython.
2700
2701 * Released 0.2.13
2702
2703 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
2704 profiler interface. Now all the major options from the profiler
2705 module are directly supported in IPython, both for single
2706 expressions (@prun) and for full programs (@run -p).
2707
2708 2002-05-09 Fernando Perez <fperez@colorado.edu>
2709
2710 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
2711 magic properly formatted for screen.
2712
2713 * setup.py (make_shortcut): Changed things to put pdf version in
2714 doc/ instead of doc/manual (had to change lyxport a bit).
2715
2716 * IPython/Magic.py (Profile.string_stats): made profile runs go
2717 through pager (they are long and a pager allows searching, saving,
2718 etc.)
2719
2720 2002-05-08 Fernando Perez <fperez@colorado.edu>
2721
2722 * Released 0.2.12
2723
2724 2002-05-06 Fernando Perez <fperez@colorado.edu>
2725
2726 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
2727 introduced); 'hist n1 n2' was broken.
2728 (Magic.magic_pdb): added optional on/off arguments to @pdb
2729 (Magic.magic_run): added option -i to @run, which executes code in
2730 the IPython namespace instead of a clean one. Also added @irun as
2731 an alias to @run -i.
2732
2733 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2734 fixed (it didn't really do anything, the namespaces were wrong).
2735
2736 * IPython/Debugger.py (__init__): Added workaround for python 2.1
2737
2738 * IPython/__init__.py (__all__): Fixed package namespace, now
2739 'import IPython' does give access to IPython.<all> as
2740 expected. Also renamed __release__ to Release.
2741
2742 * IPython/Debugger.py (__license__): created new Pdb class which
2743 functions like a drop-in for the normal pdb.Pdb but does NOT
2744 import readline by default. This way it doesn't muck up IPython's
2745 readline handling, and now tab-completion finally works in the
2746 debugger -- sort of. It completes things globally visible, but the
2747 completer doesn't track the stack as pdb walks it. That's a bit
2748 tricky, and I'll have to implement it later.
2749
2750 2002-05-05 Fernando Perez <fperez@colorado.edu>
2751
2752 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
2753 magic docstrings when printed via ? (explicit \'s were being
2754 printed).
2755
2756 * IPython/ipmaker.py (make_IPython): fixed namespace
2757 identification bug. Now variables loaded via logs or command-line
2758 files are recognized in the interactive namespace by @who.
2759
2760 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
2761 log replay system stemming from the string form of Structs.
2762
2763 * IPython/Magic.py (Macro.__init__): improved macros to properly
2764 handle magic commands in them.
2765 (Magic.magic_logstart): usernames are now expanded so 'logstart
2766 ~/mylog' now works.
2767
2768 * IPython/iplib.py (complete): fixed bug where paths starting with
2769 '/' would be completed as magic names.
2770
2771 2002-05-04 Fernando Perez <fperez@colorado.edu>
2772
2773 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
2774 allow running full programs under the profiler's control.
2775
2776 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
2777 mode to report exceptions verbosely but without formatting
2778 variables. This addresses the issue of ipython 'freezing' (it's
2779 not frozen, but caught in an expensive formatting loop) when huge
2780 variables are in the context of an exception.
2781 (VerboseTB.text): Added '--->' markers at line where exception was
2782 triggered. Much clearer to read, especially in NoColor modes.
2783
2784 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
2785 implemented in reverse when changing to the new parse_options().
2786
2787 2002-05-03 Fernando Perez <fperez@colorado.edu>
2788
2789 * IPython/Magic.py (Magic.parse_options): new function so that
2790 magics can parse options easier.
2791 (Magic.magic_prun): new function similar to profile.run(),
2792 suggested by Chris Hart.
2793 (Magic.magic_cd): fixed behavior so that it only changes if
2794 directory actually is in history.
2795
2796 * IPython/usage.py (__doc__): added information about potential
2797 slowness of Verbose exception mode when there are huge data
2798 structures to be formatted (thanks to Archie Paulson).
2799
2800 * IPython/ipmaker.py (make_IPython): Changed default logging
2801 (when simply called with -log) to use curr_dir/ipython.log in
2802 rotate mode. Fixed crash which was occuring with -log before
2803 (thanks to Jim Boyle).
2804
2805 2002-05-01 Fernando Perez <fperez@colorado.edu>
2806
2807 * Released 0.2.11 for these fixes (mainly the ultraTB one which
2808 was nasty -- though somewhat of a corner case).
2809
2810 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
2811 text (was a bug).
2812
2813 2002-04-30 Fernando Perez <fperez@colorado.edu>
2814
2815 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
2816 a print after ^D or ^C from the user so that the In[] prompt
2817 doesn't over-run the gnuplot one.
2818
2819 2002-04-29 Fernando Perez <fperez@colorado.edu>
2820
2821 * Released 0.2.10
2822
2823 * IPython/__release__.py (version): get date dynamically.
2824
2825 * Misc. documentation updates thanks to Arnd's comments. Also ran
2826 a full spellcheck on the manual (hadn't been done in a while).
2827
2828 2002-04-27 Fernando Perez <fperez@colorado.edu>
2829
2830 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
2831 starting a log in mid-session would reset the input history list.
2832
2833 2002-04-26 Fernando Perez <fperez@colorado.edu>
2834
2835 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
2836 all files were being included in an update. Now anything in
2837 UserConfig that matches [A-Za-z]*.py will go (this excludes
2838 __init__.py)
2839
2840 2002-04-25 Fernando Perez <fperez@colorado.edu>
2841
2842 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
2843 to __builtins__ so that any form of embedded or imported code can
2844 test for being inside IPython.
2845
2846 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
2847 changed to GnuplotMagic because it's now an importable module,
2848 this makes the name follow that of the standard Gnuplot module.
2849 GnuplotMagic can now be loaded at any time in mid-session.
2850
2851 2002-04-24 Fernando Perez <fperez@colorado.edu>
2852
2853 * IPython/numutils.py: removed SIUnits. It doesn't properly set
2854 the globals (IPython has its own namespace) and the
2855 PhysicalQuantity stuff is much better anyway.
2856
2857 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
2858 embedding example to standard user directory for
2859 distribution. Also put it in the manual.
2860
2861 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
2862 instance as first argument (so it doesn't rely on some obscure
2863 hidden global).
2864
2865 * IPython/UserConfig/ipythonrc.py: put () back in accepted
2866 delimiters. While it prevents ().TAB from working, it allows
2867 completions in open (... expressions. This is by far a more common
2868 case.
2869
2870 2002-04-23 Fernando Perez <fperez@colorado.edu>
2871
2872 * IPython/Extensions/InterpreterPasteInput.py: new
2873 syntax-processing module for pasting lines with >>> or ... at the
2874 start.
2875
2876 * IPython/Extensions/PhysicalQ_Interactive.py
2877 (PhysicalQuantityInteractive.__int__): fixed to work with either
2878 Numeric or math.
2879
2880 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
2881 provided profiles. Now we have:
2882 -math -> math module as * and cmath with its own namespace.
2883 -numeric -> Numeric as *, plus gnuplot & grace
2884 -physics -> same as before
2885
2886 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
2887 user-defined magics wouldn't be found by @magic if they were
2888 defined as class methods. Also cleaned up the namespace search
2889 logic and the string building (to use %s instead of many repeated
2890 string adds).
2891
2892 * IPython/UserConfig/example-magic.py (magic_foo): updated example
2893 of user-defined magics to operate with class methods (cleaner, in
2894 line with the gnuplot code).
2895
2896 2002-04-22 Fernando Perez <fperez@colorado.edu>
2897
2898 * setup.py: updated dependency list so that manual is updated when
2899 all included files change.
2900
2901 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
2902 the delimiter removal option (the fix is ugly right now).
2903
2904 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
2905 all of the math profile (quicker loading, no conflict between
2906 g-9.8 and g-gnuplot).
2907
2908 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
2909 name of post-mortem files to IPython_crash_report.txt.
2910
2911 * Cleanup/update of the docs. Added all the new readline info and
2912 formatted all lists as 'real lists'.
2913
2914 * IPython/ipmaker.py (make_IPython): removed now-obsolete
2915 tab-completion options, since the full readline parse_and_bind is
2916 now accessible.
2917
2918 * IPython/iplib.py (InteractiveShell.init_readline): Changed
2919 handling of readline options. Now users can specify any string to
2920 be passed to parse_and_bind(), as well as the delimiters to be
2921 removed.
2922 (InteractiveShell.__init__): Added __name__ to the global
2923 namespace so that things like Itpl which rely on its existence
2924 don't crash.
2925 (InteractiveShell._prefilter): Defined the default with a _ so
2926 that prefilter() is easier to override, while the default one
2927 remains available.
2928
2929 2002-04-18 Fernando Perez <fperez@colorado.edu>
2930
2931 * Added information about pdb in the docs.
2932
2933 2002-04-17 Fernando Perez <fperez@colorado.edu>
2934
2935 * IPython/ipmaker.py (make_IPython): added rc_override option to
2936 allow passing config options at creation time which may override
2937 anything set in the config files or command line. This is
2938 particularly useful for configuring embedded instances.
2939
2940 2002-04-15 Fernando Perez <fperez@colorado.edu>
2941
2942 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
2943 crash embedded instances because of the input cache falling out of
2944 sync with the output counter.
2945
2946 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
2947 mode which calls pdb after an uncaught exception in IPython itself.
2948
2949 2002-04-14 Fernando Perez <fperez@colorado.edu>
2950
2951 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
2952 readline, fix it back after each call.
2953
2954 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
2955 method to force all access via __call__(), which guarantees that
2956 traceback references are properly deleted.
2957
2958 * IPython/Prompts.py (CachedOutput._display): minor fixes to
2959 improve printing when pprint is in use.
2960
2961 2002-04-13 Fernando Perez <fperez@colorado.edu>
2962
2963 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
2964 exceptions aren't caught anymore. If the user triggers one, he
2965 should know why he's doing it and it should go all the way up,
2966 just like any other exception. So now @abort will fully kill the
2967 embedded interpreter and the embedding code (unless that happens
2968 to catch SystemExit).
2969
2970 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
2971 and a debugger() method to invoke the interactive pdb debugger
2972 after printing exception information. Also added the corresponding
2973 -pdb option and @pdb magic to control this feature, and updated
2974 the docs. After a suggestion from Christopher Hart
2975 (hart-AT-caltech.edu).
2976
2977 2002-04-12 Fernando Perez <fperez@colorado.edu>
2978
2979 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
2980 the exception handlers defined by the user (not the CrashHandler)
2981 so that user exceptions don't trigger an ipython bug report.
2982
2983 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
2984 configurable (it should have always been so).
2985
2986 2002-03-26 Fernando Perez <fperez@colorado.edu>
2987
2988 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
2989 and there to fix embedding namespace issues. This should all be
2990 done in a more elegant way.
2991
2992 2002-03-25 Fernando Perez <fperez@colorado.edu>
2993
2994 * IPython/genutils.py (get_home_dir): Try to make it work under
2995 win9x also.
2996
2997 2002-03-20 Fernando Perez <fperez@colorado.edu>
2998
2999 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3000 sys.displayhook untouched upon __init__.
3001
3002 2002-03-19 Fernando Perez <fperez@colorado.edu>
3003
3004 * Released 0.2.9 (for embedding bug, basically).
3005
3006 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3007 exceptions so that enclosing shell's state can be restored.
3008
3009 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3010 naming conventions in the .ipython/ dir.
3011
3012 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3013 from delimiters list so filenames with - in them get expanded.
3014
3015 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3016 sys.displayhook not being properly restored after an embedded call.
3017
3018 2002-03-18 Fernando Perez <fperez@colorado.edu>
3019
3020 * Released 0.2.8
3021
3022 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3023 some files weren't being included in a -upgrade.
3024 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3025 on' so that the first tab completes.
3026 (InteractiveShell.handle_magic): fixed bug with spaces around
3027 quotes breaking many magic commands.
3028
3029 * setup.py: added note about ignoring the syntax error messages at
3030 installation.
3031
3032 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3033 streamlining the gnuplot interface, now there's only one magic @gp.
3034
3035 2002-03-17 Fernando Perez <fperez@colorado.edu>
3036
3037 * IPython/UserConfig/magic_gnuplot.py: new name for the
3038 example-magic_pm.py file. Much enhanced system, now with a shell
3039 for communicating directly with gnuplot, one command at a time.
3040
3041 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3042 setting __name__=='__main__'.
3043
3044 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3045 mini-shell for accessing gnuplot from inside ipython. Should
3046 extend it later for grace access too. Inspired by Arnd's
3047 suggestion.
3048
3049 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3050 calling magic functions with () in their arguments. Thanks to Arnd
3051 Baecker for pointing this to me.
3052
3053 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3054 infinitely for integer or complex arrays (only worked with floats).
3055
3056 2002-03-16 Fernando Perez <fperez@colorado.edu>
3057
3058 * setup.py: Merged setup and setup_windows into a single script
3059 which properly handles things for windows users.
3060
3061 2002-03-15 Fernando Perez <fperez@colorado.edu>
3062
3063 * Big change to the manual: now the magics are all automatically
3064 documented. This information is generated from their docstrings
3065 and put in a latex file included by the manual lyx file. This way
3066 we get always up to date information for the magics. The manual
3067 now also has proper version information, also auto-synced.
3068
3069 For this to work, an undocumented --magic_docstrings option was added.
3070
3071 2002-03-13 Fernando Perez <fperez@colorado.edu>
3072
3073 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3074 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3075
3076 2002-03-12 Fernando Perez <fperez@colorado.edu>
3077
3078 * IPython/ultraTB.py (TermColors): changed color escapes again to
3079 fix the (old, reintroduced) line-wrapping bug. Basically, if
3080 \001..\002 aren't given in the color escapes, lines get wrapped
3081 weirdly. But giving those screws up old xterms and emacs terms. So
3082 I added some logic for emacs terms to be ok, but I can't identify old
3083 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3084
3085 2002-03-10 Fernando Perez <fperez@colorado.edu>
3086
3087 * IPython/usage.py (__doc__): Various documentation cleanups and
3088 updates, both in usage docstrings and in the manual.
3089
3090 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3091 handling of caching. Set minimum acceptabe value for having a
3092 cache at 20 values.
3093
3094 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3095 install_first_time function to a method, renamed it and added an
3096 'upgrade' mode. Now people can update their config directory with
3097 a simple command line switch (-upgrade, also new).
3098
3099 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3100 @file (convenient for automagic users under Python >= 2.2).
3101 Removed @files (it seemed more like a plural than an abbrev. of
3102 'file show').
3103
3104 * IPython/iplib.py (install_first_time): Fixed crash if there were
3105 backup files ('~') in .ipython/ install directory.
3106
3107 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3108 system. Things look fine, but these changes are fairly
3109 intrusive. Test them for a few days.
3110
3111 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3112 the prompts system. Now all in/out prompt strings are user
3113 controllable. This is particularly useful for embedding, as one
3114 can tag embedded instances with particular prompts.
3115
3116 Also removed global use of sys.ps1/2, which now allows nested
3117 embeddings without any problems. Added command-line options for
3118 the prompt strings.
3119
3120 2002-03-08 Fernando Perez <fperez@colorado.edu>
3121
3122 * IPython/UserConfig/example-embed-short.py (ipshell): added
3123 example file with the bare minimum code for embedding.
3124
3125 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3126 functionality for the embeddable shell to be activated/deactivated
3127 either globally or at each call.
3128
3129 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3130 rewriting the prompt with '--->' for auto-inputs with proper
3131 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3132 this is handled by the prompts class itself, as it should.
3133
3134 2002-03-05 Fernando Perez <fperez@colorado.edu>
3135
3136 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3137 @logstart to avoid name clashes with the math log function.
3138
3139 * Big updates to X/Emacs section of the manual.
3140
3141 * Removed ipython_emacs. Milan explained to me how to pass
3142 arguments to ipython through Emacs. Some day I'm going to end up
3143 learning some lisp...
3144
3145 2002-03-04 Fernando Perez <fperez@colorado.edu>
3146
3147 * IPython/ipython_emacs: Created script to be used as the
3148 py-python-command Emacs variable so we can pass IPython
3149 parameters. I can't figure out how to tell Emacs directly to pass
3150 parameters to IPython, so a dummy shell script will do it.
3151
3152 Other enhancements made for things to work better under Emacs'
3153 various types of terminals. Many thanks to Milan Zamazal
3154 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3155
3156 2002-03-01 Fernando Perez <fperez@colorado.edu>
3157
3158 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3159 that loading of readline is now optional. This gives better
3160 control to emacs users.
3161
3162 * IPython/ultraTB.py (__date__): Modified color escape sequences
3163 and now things work fine under xterm and in Emacs' term buffers
3164 (though not shell ones). Well, in emacs you get colors, but all
3165 seem to be 'light' colors (no difference between dark and light
3166 ones). But the garbage chars are gone, and also in xterms. It
3167 seems that now I'm using 'cleaner' ansi sequences.
3168
3169 2002-02-21 Fernando Perez <fperez@colorado.edu>
3170
3171 * Released 0.2.7 (mainly to publish the scoping fix).
3172
3173 * IPython/Logger.py (Logger.logstate): added. A corresponding
3174 @logstate magic was created.
3175
3176 * IPython/Magic.py: fixed nested scoping problem under Python
3177 2.1.x (automagic wasn't working).
3178
3179 2002-02-20 Fernando Perez <fperez@colorado.edu>
3180
3181 * Released 0.2.6.
3182
3183 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3184 option so that logs can come out without any headers at all.
3185
3186 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3187 SciPy.
3188
3189 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3190 that embedded IPython calls don't require vars() to be explicitly
3191 passed. Now they are extracted from the caller's frame (code
3192 snatched from Eric Jones' weave). Added better documentation to
3193 the section on embedding and the example file.
3194
3195 * IPython/genutils.py (page): Changed so that under emacs, it just
3196 prints the string. You can then page up and down in the emacs
3197 buffer itself. This is how the builtin help() works.
3198
3199 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3200 macro scoping: macros need to be executed in the user's namespace
3201 to work as if they had been typed by the user.
3202
3203 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3204 execute automatically (no need to type 'exec...'). They then
3205 behave like 'true macros'. The printing system was also modified
3206 for this to work.
3207
3208 2002-02-19 Fernando Perez <fperez@colorado.edu>
3209
3210 * IPython/genutils.py (page_file): new function for paging files
3211 in an OS-independent way. Also necessary for file viewing to work
3212 well inside Emacs buffers.
3213 (page): Added checks for being in an emacs buffer.
3214 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3215 same bug in iplib.
3216
3217 2002-02-18 Fernando Perez <fperez@colorado.edu>
3218
3219 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3220 of readline so that IPython can work inside an Emacs buffer.
3221
3222 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3223 method signatures (they weren't really bugs, but it looks cleaner
3224 and keeps PyChecker happy).
3225
3226 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3227 for implementing various user-defined hooks. Currently only
3228 display is done.
3229
3230 * IPython/Prompts.py (CachedOutput._display): changed display
3231 functions so that they can be dynamically changed by users easily.
3232
3233 * IPython/Extensions/numeric_formats.py (num_display): added an
3234 extension for printing NumPy arrays in flexible manners. It
3235 doesn't do anything yet, but all the structure is in
3236 place. Ultimately the plan is to implement output format control
3237 like in Octave.
3238
3239 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3240 methods are found at run-time by all the automatic machinery.
3241
3242 2002-02-17 Fernando Perez <fperez@colorado.edu>
3243
3244 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3245 whole file a little.
3246
3247 * ToDo: closed this document. Now there's a new_design.lyx
3248 document for all new ideas. Added making a pdf of it for the
3249 end-user distro.
3250
3251 * IPython/Logger.py (Logger.switch_log): Created this to replace
3252 logon() and logoff(). It also fixes a nasty crash reported by
3253 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3254
3255 * IPython/iplib.py (complete): got auto-completion to work with
3256 automagic (I had wanted this for a long time).
3257
3258 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3259 to @file, since file() is now a builtin and clashes with automagic
3260 for @file.
3261
3262 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3263 of this was previously in iplib, which had grown to more than 2000
3264 lines, way too long. No new functionality, but it makes managing
3265 the code a bit easier.
3266
3267 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3268 information to crash reports.
3269
3270 2002-02-12 Fernando Perez <fperez@colorado.edu>
3271
3272 * Released 0.2.5.
3273
3274 2002-02-11 Fernando Perez <fperez@colorado.edu>
3275
3276 * Wrote a relatively complete Windows installer. It puts
3277 everything in place, creates Start Menu entries and fixes the
3278 color issues. Nothing fancy, but it works.
3279
3280 2002-02-10 Fernando Perez <fperez@colorado.edu>
3281
3282 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3283 os.path.expanduser() call so that we can type @run ~/myfile.py and
3284 have thigs work as expected.
3285
3286 * IPython/genutils.py (page): fixed exception handling so things
3287 work both in Unix and Windows correctly. Quitting a pager triggers
3288 an IOError/broken pipe in Unix, and in windows not finding a pager
3289 is also an IOError, so I had to actually look at the return value
3290 of the exception, not just the exception itself. Should be ok now.
3291
3292 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3293 modified to allow case-insensitive color scheme changes.
3294
3295 2002-02-09 Fernando Perez <fperez@colorado.edu>
3296
3297 * IPython/genutils.py (native_line_ends): new function to leave
3298 user config files with os-native line-endings.
3299
3300 * README and manual updates.
3301
3302 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3303 instead of StringType to catch Unicode strings.
3304
3305 * IPython/genutils.py (filefind): fixed bug for paths with
3306 embedded spaces (very common in Windows).
3307
3308 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3309 files under Windows, so that they get automatically associated
3310 with a text editor. Windows makes it a pain to handle
3311 extension-less files.
3312
3313 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3314 warning about readline only occur for Posix. In Windows there's no
3315 way to get readline, so why bother with the warning.
3316
3317 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3318 for __str__ instead of dir(self), since dir() changed in 2.2.
3319
3320 * Ported to Windows! Tested on XP, I suspect it should work fine
3321 on NT/2000, but I don't think it will work on 98 et al. That
3322 series of Windows is such a piece of junk anyway that I won't try
3323 porting it there. The XP port was straightforward, showed a few
3324 bugs here and there (fixed all), in particular some string
3325 handling stuff which required considering Unicode strings (which
3326 Windows uses). This is good, but hasn't been too tested :) No
3327 fancy installer yet, I'll put a note in the manual so people at
3328 least make manually a shortcut.
3329
3330 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3331 into a single one, "colors". This now controls both prompt and
3332 exception color schemes, and can be changed both at startup
3333 (either via command-line switches or via ipythonrc files) and at
3334 runtime, with @colors.
3335 (Magic.magic_run): renamed @prun to @run and removed the old
3336 @run. The two were too similar to warrant keeping both.
3337
3338 2002-02-03 Fernando Perez <fperez@colorado.edu>
3339
3340 * IPython/iplib.py (install_first_time): Added comment on how to
3341 configure the color options for first-time users. Put a <return>
3342 request at the end so that small-terminal users get a chance to
3343 read the startup info.
3344
3345 2002-01-23 Fernando Perez <fperez@colorado.edu>
3346
3347 * IPython/iplib.py (CachedOutput.update): Changed output memory
3348 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3349 input history we still use _i. Did this b/c these variable are
3350 very commonly used in interactive work, so the less we need to
3351 type the better off we are.
3352 (Magic.magic_prun): updated @prun to better handle the namespaces
3353 the file will run in, including a fix for __name__ not being set
3354 before.
3355
3356 2002-01-20 Fernando Perez <fperez@colorado.edu>
3357
3358 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3359 extra garbage for Python 2.2. Need to look more carefully into
3360 this later.
3361
3362 2002-01-19 Fernando Perez <fperez@colorado.edu>
3363
3364 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3365 display SyntaxError exceptions properly formatted when they occur
3366 (they can be triggered by imported code).
3367
3368 2002-01-18 Fernando Perez <fperez@colorado.edu>
3369
3370 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3371 SyntaxError exceptions are reported nicely formatted, instead of
3372 spitting out only offset information as before.
3373 (Magic.magic_prun): Added the @prun function for executing
3374 programs with command line args inside IPython.
3375
3376 2002-01-16 Fernando Perez <fperez@colorado.edu>
3377
3378 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3379 to *not* include the last item given in a range. This brings their
3380 behavior in line with Python's slicing:
3381 a[n1:n2] -> a[n1]...a[n2-1]
3382 It may be a bit less convenient, but I prefer to stick to Python's
3383 conventions *everywhere*, so users never have to wonder.
3384 (Magic.magic_macro): Added @macro function to ease the creation of
3385 macros.
3386
3387 2002-01-05 Fernando Perez <fperez@colorado.edu>
3388
3389 * Released 0.2.4.
3390
3391 * IPython/iplib.py (Magic.magic_pdef):
3392 (InteractiveShell.safe_execfile): report magic lines and error
3393 lines without line numbers so one can easily copy/paste them for
3394 re-execution.
3395
3396 * Updated manual with recent changes.
3397
3398 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3399 docstring printing when class? is called. Very handy for knowing
3400 how to create class instances (as long as __init__ is well
3401 documented, of course :)
3402 (Magic.magic_doc): print both class and constructor docstrings.
3403 (Magic.magic_pdef): give constructor info if passed a class and
3404 __call__ info for callable object instances.
3405
3406 2002-01-04 Fernando Perez <fperez@colorado.edu>
3407
3408 * Made deep_reload() off by default. It doesn't always work
3409 exactly as intended, so it's probably safer to have it off. It's
3410 still available as dreload() anyway, so nothing is lost.
3411
3412 2002-01-02 Fernando Perez <fperez@colorado.edu>
3413
3414 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3415 so I wanted an updated release).
3416
3417 2001-12-27 Fernando Perez <fperez@colorado.edu>
3418
3419 * IPython/iplib.py (InteractiveShell.interact): Added the original
3420 code from 'code.py' for this module in order to change the
3421 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3422 the history cache would break when the user hit Ctrl-C, and
3423 interact() offers no way to add any hooks to it.
3424
3425 2001-12-23 Fernando Perez <fperez@colorado.edu>
3426
3427 * setup.py: added check for 'MANIFEST' before trying to remove
3428 it. Thanks to Sean Reifschneider.
3429
3430 2001-12-22 Fernando Perez <fperez@colorado.edu>
3431
3432 * Released 0.2.2.
3433
3434 * Finished (reasonably) writing the manual. Later will add the
3435 python-standard navigation stylesheets, but for the time being
3436 it's fairly complete. Distribution will include html and pdf
3437 versions.
3438
3439 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3440 (MayaVi author).
3441
3442 2001-12-21 Fernando Perez <fperez@colorado.edu>
3443
3444 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3445 good public release, I think (with the manual and the distutils
3446 installer). The manual can use some work, but that can go
3447 slowly. Otherwise I think it's quite nice for end users. Next
3448 summer, rewrite the guts of it...
3449
3450 * Changed format of ipythonrc files to use whitespace as the
3451 separator instead of an explicit '='. Cleaner.
3452
3453 2001-12-20 Fernando Perez <fperez@colorado.edu>
3454
3455 * Started a manual in LyX. For now it's just a quick merge of the
3456 various internal docstrings and READMEs. Later it may grow into a
3457 nice, full-blown manual.
3458
3459 * Set up a distutils based installer. Installation should now be
3460 trivially simple for end-users.
3461
3462 2001-12-11 Fernando Perez <fperez@colorado.edu>
3463
3464 * Released 0.2.0. First public release, announced it at
3465 comp.lang.python. From now on, just bugfixes...
3466
3467 * Went through all the files, set copyright/license notices and
3468 cleaned up things. Ready for release.
3469
3470 2001-12-10 Fernando Perez <fperez@colorado.edu>
3471
3472 * Changed the first-time installer not to use tarfiles. It's more
3473 robust now and less unix-dependent. Also makes it easier for
3474 people to later upgrade versions.
3475
3476 * Changed @exit to @abort to reflect the fact that it's pretty
3477 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3478 becomes significant only when IPyhton is embedded: in that case,
3479 C-D closes IPython only, but @abort kills the enclosing program
3480 too (unless it had called IPython inside a try catching
3481 SystemExit).
3482
3483 * Created Shell module which exposes the actuall IPython Shell
3484 classes, currently the normal and the embeddable one. This at
3485 least offers a stable interface we won't need to change when
3486 (later) the internals are rewritten. That rewrite will be confined
3487 to iplib and ipmaker, but the Shell interface should remain as is.
3488
3489 * Added embed module which offers an embeddable IPShell object,
3490 useful to fire up IPython *inside* a running program. Great for
3491 debugging or dynamical data analysis.
3492
3493 2001-12-08 Fernando Perez <fperez@colorado.edu>
3494
3495 * Fixed small bug preventing seeing info from methods of defined
3496 objects (incorrect namespace in _ofind()).
3497
3498 * Documentation cleanup. Moved the main usage docstrings to a
3499 separate file, usage.py (cleaner to maintain, and hopefully in the
3500 future some perlpod-like way of producing interactive, man and
3501 html docs out of it will be found).
3502
3503 * Added @profile to see your profile at any time.
3504
3505 * Added @p as an alias for 'print'. It's especially convenient if
3506 using automagic ('p x' prints x).
3507
3508 * Small cleanups and fixes after a pychecker run.
3509
3510 * Changed the @cd command to handle @cd - and @cd -<n> for
3511 visiting any directory in _dh.
3512
3513 * Introduced _dh, a history of visited directories. @dhist prints
3514 it out with numbers.
3515
3516 2001-12-07 Fernando Perez <fperez@colorado.edu>
3517
3518 * Released 0.1.22
3519
3520 * Made initialization a bit more robust against invalid color
3521 options in user input (exit, not traceback-crash).
3522
3523 * Changed the bug crash reporter to write the report only in the
3524 user's .ipython directory. That way IPython won't litter people's
3525 hard disks with crash files all over the place. Also print on
3526 screen the necessary mail command.
3527
3528 * With the new ultraTB, implemented LightBG color scheme for light
3529 background terminals. A lot of people like white backgrounds, so I
3530 guess we should at least give them something readable.
3531
3532 2001-12-06 Fernando Perez <fperez@colorado.edu>
3533
3534 * Modified the structure of ultraTB. Now there's a proper class
3535 for tables of color schemes which allow adding schemes easily and
3536 switching the active scheme without creating a new instance every
3537 time (which was ridiculous). The syntax for creating new schemes
3538 is also cleaner. I think ultraTB is finally done, with a clean
3539 class structure. Names are also much cleaner (now there's proper
3540 color tables, no need for every variable to also have 'color' in
3541 its name).
3542
3543 * Broke down genutils into separate files. Now genutils only
3544 contains utility functions, and classes have been moved to their
3545 own files (they had enough independent functionality to warrant
3546 it): ConfigLoader, OutputTrap, Struct.
3547
3548 2001-12-05 Fernando Perez <fperez@colorado.edu>
3549
3550 * IPython turns 21! Released version 0.1.21, as a candidate for
3551 public consumption. If all goes well, release in a few days.
3552
3553 * Fixed path bug (files in Extensions/ directory wouldn't be found
3554 unless IPython/ was explicitly in sys.path).
3555
3556 * Extended the FlexCompleter class as MagicCompleter to allow
3557 completion of @-starting lines.
3558
3559 * Created __release__.py file as a central repository for release
3560 info that other files can read from.
3561
3562 * Fixed small bug in logging: when logging was turned on in
3563 mid-session, old lines with special meanings (!@?) were being
3564 logged without the prepended comment, which is necessary since
3565 they are not truly valid python syntax. This should make session
3566 restores produce less errors.
3567
3568 * The namespace cleanup forced me to make a FlexCompleter class
3569 which is nothing but a ripoff of rlcompleter, but with selectable
3570 namespace (rlcompleter only works in __main__.__dict__). I'll try
3571 to submit a note to the authors to see if this change can be
3572 incorporated in future rlcompleter releases (Dec.6: done)
3573
3574 * More fixes to namespace handling. It was a mess! Now all
3575 explicit references to __main__.__dict__ are gone (except when
3576 really needed) and everything is handled through the namespace
3577 dicts in the IPython instance. We seem to be getting somewhere
3578 with this, finally...
3579
3580 * Small documentation updates.
3581
3582 * Created the Extensions directory under IPython (with an
3583 __init__.py). Put the PhysicalQ stuff there. This directory should
3584 be used for all special-purpose extensions.
3585
3586 * File renaming:
3587 ipythonlib --> ipmaker
3588 ipplib --> iplib
3589 This makes a bit more sense in terms of what these files actually do.
3590
3591 * Moved all the classes and functions in ipythonlib to ipplib, so
3592 now ipythonlib only has make_IPython(). This will ease up its
3593 splitting in smaller functional chunks later.
3594
3595 * Cleaned up (done, I think) output of @whos. Better column
3596 formatting, and now shows str(var) for as much as it can, which is
3597 typically what one gets with a 'print var'.
3598
3599 2001-12-04 Fernando Perez <fperez@colorado.edu>
3600
3601 * Fixed namespace problems. Now builtin/IPyhton/user names get
3602 properly reported in their namespace. Internal namespace handling
3603 is finally getting decent (not perfect yet, but much better than
3604 the ad-hoc mess we had).
3605
3606 * Removed -exit option. If people just want to run a python
3607 script, that's what the normal interpreter is for. Less
3608 unnecessary options, less chances for bugs.
3609
3610 * Added a crash handler which generates a complete post-mortem if
3611 IPython crashes. This will help a lot in tracking bugs down the
3612 road.
3613
3614 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
3615 which were boud to functions being reassigned would bypass the
3616 logger, breaking the sync of _il with the prompt counter. This
3617 would then crash IPython later when a new line was logged.
3618
3619 2001-12-02 Fernando Perez <fperez@colorado.edu>
3620
3621 * Made IPython a package. This means people don't have to clutter
3622 their sys.path with yet another directory. Changed the INSTALL
3623 file accordingly.
3624
3625 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
3626 sorts its output (so @who shows it sorted) and @whos formats the
3627 table according to the width of the first column. Nicer, easier to
3628 read. Todo: write a generic table_format() which takes a list of
3629 lists and prints it nicely formatted, with optional row/column
3630 separators and proper padding and justification.
3631
3632 * Released 0.1.20
3633
3634 * Fixed bug in @log which would reverse the inputcache list (a
3635 copy operation was missing).
3636
3637 * Code cleanup. @config was changed to use page(). Better, since
3638 its output is always quite long.
3639
3640 * Itpl is back as a dependency. I was having too many problems
3641 getting the parametric aliases to work reliably, and it's just
3642 easier to code weird string operations with it than playing %()s
3643 games. It's only ~6k, so I don't think it's too big a deal.
3644
3645 * Found (and fixed) a very nasty bug with history. !lines weren't
3646 getting cached, and the out of sync caches would crash
3647 IPython. Fixed it by reorganizing the prefilter/handlers/logger
3648 division of labor a bit better. Bug fixed, cleaner structure.
3649
3650 2001-12-01 Fernando Perez <fperez@colorado.edu>
3651
3652 * Released 0.1.19
3653
3654 * Added option -n to @hist to prevent line number printing. Much
3655 easier to copy/paste code this way.
3656
3657 * Created global _il to hold the input list. Allows easy
3658 re-execution of blocks of code by slicing it (inspired by Janko's
3659 comment on 'macros').
3660
3661 * Small fixes and doc updates.
3662
3663 * Rewrote @history function (was @h). Renamed it to @hist, @h is
3664 much too fragile with automagic. Handles properly multi-line
3665 statements and takes parameters.
3666
3667 2001-11-30 Fernando Perez <fperez@colorado.edu>
3668
3669 * Version 0.1.18 released.
3670
3671 * Fixed nasty namespace bug in initial module imports.
3672
3673 * Added copyright/license notes to all code files (except
3674 DPyGetOpt). For the time being, LGPL. That could change.
3675
3676 * Rewrote a much nicer README, updated INSTALL, cleaned up
3677 ipythonrc-* samples.
3678
3679 * Overall code/documentation cleanup. Basically ready for
3680 release. Only remaining thing: licence decision (LGPL?).
3681
3682 * Converted load_config to a class, ConfigLoader. Now recursion
3683 control is better organized. Doesn't include the same file twice.
3684
3685 2001-11-29 Fernando Perez <fperez@colorado.edu>
3686
3687 * Got input history working. Changed output history variables from
3688 _p to _o so that _i is for input and _o for output. Just cleaner
3689 convention.
3690
3691 * Implemented parametric aliases. This pretty much allows the
3692 alias system to offer full-blown shell convenience, I think.
3693
3694 * Version 0.1.17 released, 0.1.18 opened.
3695
3696 * dot_ipython/ipythonrc (alias): added documentation.
3697 (xcolor): Fixed small bug (xcolors -> xcolor)
3698
3699 * Changed the alias system. Now alias is a magic command to define
3700 aliases just like the shell. Rationale: the builtin magics should
3701 be there for things deeply connected to IPython's
3702 architecture. And this is a much lighter system for what I think
3703 is the really important feature: allowing users to define quickly
3704 magics that will do shell things for them, so they can customize
3705 IPython easily to match their work habits. If someone is really
3706 desperate to have another name for a builtin alias, they can
3707 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
3708 works.
3709
3710 2001-11-28 Fernando Perez <fperez@colorado.edu>
3711
3712 * Changed @file so that it opens the source file at the proper
3713 line. Since it uses less, if your EDITOR environment is
3714 configured, typing v will immediately open your editor of choice
3715 right at the line where the object is defined. Not as quick as
3716 having a direct @edit command, but for all intents and purposes it
3717 works. And I don't have to worry about writing @edit to deal with
3718 all the editors, less does that.
3719
3720 * Version 0.1.16 released, 0.1.17 opened.
3721
3722 * Fixed some nasty bugs in the page/page_dumb combo that could
3723 crash IPython.
3724
3725 2001-11-27 Fernando Perez <fperez@colorado.edu>
3726
3727 * Version 0.1.15 released, 0.1.16 opened.
3728
3729 * Finally got ? and ?? to work for undefined things: now it's
3730 possible to type {}.get? and get information about the get method
3731 of dicts, or os.path? even if only os is defined (so technically
3732 os.path isn't). Works at any level. For example, after import os,
3733 os?, os.path?, os.path.abspath? all work. This is great, took some
3734 work in _ofind.
3735
3736 * Fixed more bugs with logging. The sanest way to do it was to add
3737 to @log a 'mode' parameter. Killed two in one shot (this mode
3738 option was a request of Janko's). I think it's finally clean
3739 (famous last words).
3740
3741 * Added a page_dumb() pager which does a decent job of paging on
3742 screen, if better things (like less) aren't available. One less
3743 unix dependency (someday maybe somebody will port this to
3744 windows).
3745
3746 * Fixed problem in magic_log: would lock of logging out if log
3747 creation failed (because it would still think it had succeeded).
3748
3749 * Improved the page() function using curses to auto-detect screen
3750 size. Now it can make a much better decision on whether to print
3751 or page a string. Option screen_length was modified: a value 0
3752 means auto-detect, and that's the default now.
3753
3754 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
3755 go out. I'll test it for a few days, then talk to Janko about
3756 licences and announce it.
3757
3758 * Fixed the length of the auto-generated ---> prompt which appears
3759 for auto-parens and auto-quotes. Getting this right isn't trivial,
3760 with all the color escapes, different prompt types and optional
3761 separators. But it seems to be working in all the combinations.
3762
3763 2001-11-26 Fernando Perez <fperez@colorado.edu>
3764
3765 * Wrote a regexp filter to get option types from the option names
3766 string. This eliminates the need to manually keep two duplicate
3767 lists.
3768
3769 * Removed the unneeded check_option_names. Now options are handled
3770 in a much saner manner and it's easy to visually check that things
3771 are ok.
3772
3773 * Updated version numbers on all files I modified to carry a
3774 notice so Janko and Nathan have clear version markers.
3775
3776 * Updated docstring for ultraTB with my changes. I should send
3777 this to Nathan.
3778
3779 * Lots of small fixes. Ran everything through pychecker again.
3780
3781 * Made loading of deep_reload an cmd line option. If it's not too
3782 kosher, now people can just disable it. With -nodeep_reload it's
3783 still available as dreload(), it just won't overwrite reload().
3784
3785 * Moved many options to the no| form (-opt and -noopt
3786 accepted). Cleaner.
3787
3788 * Changed magic_log so that if called with no parameters, it uses
3789 'rotate' mode. That way auto-generated logs aren't automatically
3790 over-written. For normal logs, now a backup is made if it exists
3791 (only 1 level of backups). A new 'backup' mode was added to the
3792 Logger class to support this. This was a request by Janko.
3793
3794 * Added @logoff/@logon to stop/restart an active log.
3795
3796 * Fixed a lot of bugs in log saving/replay. It was pretty
3797 broken. Now special lines (!@,/) appear properly in the command
3798 history after a log replay.
3799
3800 * Tried and failed to implement full session saving via pickle. My
3801 idea was to pickle __main__.__dict__, but modules can't be
3802 pickled. This would be a better alternative to replaying logs, but
3803 seems quite tricky to get to work. Changed -session to be called
3804 -logplay, which more accurately reflects what it does. And if we
3805 ever get real session saving working, -session is now available.
3806
3807 * Implemented color schemes for prompts also. As for tracebacks,
3808 currently only NoColor and Linux are supported. But now the
3809 infrastructure is in place, based on a generic ColorScheme
3810 class. So writing and activating new schemes both for the prompts
3811 and the tracebacks should be straightforward.
3812
3813 * Version 0.1.13 released, 0.1.14 opened.
3814
3815 * Changed handling of options for output cache. Now counter is
3816 hardwired starting at 1 and one specifies the maximum number of
3817 entries *in the outcache* (not the max prompt counter). This is
3818 much better, since many statements won't increase the cache
3819 count. It also eliminated some confusing options, now there's only
3820 one: cache_size.
3821
3822 * Added 'alias' magic function and magic_alias option in the
3823 ipythonrc file. Now the user can easily define whatever names he
3824 wants for the magic functions without having to play weird
3825 namespace games. This gives IPython a real shell-like feel.
3826
3827 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
3828 @ or not).
3829
3830 This was one of the last remaining 'visible' bugs (that I know
3831 of). I think if I can clean up the session loading so it works
3832 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
3833 about licensing).
3834
3835 2001-11-25 Fernando Perez <fperez@colorado.edu>
3836
3837 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
3838 there's a cleaner distinction between what ? and ?? show.
3839
3840 * Added screen_length option. Now the user can define his own
3841 screen size for page() operations.
3842
3843 * Implemented magic shell-like functions with automatic code
3844 generation. Now adding another function is just a matter of adding
3845 an entry to a dict, and the function is dynamically generated at
3846 run-time. Python has some really cool features!
3847
3848 * Renamed many options to cleanup conventions a little. Now all
3849 are lowercase, and only underscores where needed. Also in the code
3850 option name tables are clearer.
3851
3852 * Changed prompts a little. Now input is 'In [n]:' instead of
3853 'In[n]:='. This allows it the numbers to be aligned with the
3854 Out[n] numbers, and removes usage of ':=' which doesn't exist in
3855 Python (it was a Mathematica thing). The '...' continuation prompt
3856 was also changed a little to align better.
3857
3858 * Fixed bug when flushing output cache. Not all _p<n> variables
3859 exist, so their deletion needs to be wrapped in a try:
3860
3861 * Figured out how to properly use inspect.formatargspec() (it
3862 requires the args preceded by *). So I removed all the code from
3863 _get_pdef in Magic, which was just replicating that.
3864
3865 * Added test to prefilter to allow redefining magic function names
3866 as variables. This is ok, since the @ form is always available,
3867 but whe should allow the user to define a variable called 'ls' if
3868 he needs it.
3869
3870 * Moved the ToDo information from README into a separate ToDo.
3871
3872 * General code cleanup and small bugfixes. I think it's close to a
3873 state where it can be released, obviously with a big 'beta'
3874 warning on it.
3875
3876 * Got the magic function split to work. Now all magics are defined
3877 in a separate class. It just organizes things a bit, and now
3878 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
3879 was too long).
3880
3881 * Changed @clear to @reset to avoid potential confusions with
3882 the shell command clear. Also renamed @cl to @clear, which does
3883 exactly what people expect it to from their shell experience.
3884
3885 Added a check to the @reset command (since it's so
3886 destructive, it's probably a good idea to ask for confirmation).
3887 But now reset only works for full namespace resetting. Since the
3888 del keyword is already there for deleting a few specific
3889 variables, I don't see the point of having a redundant magic
3890 function for the same task.
3891
3892 2001-11-24 Fernando Perez <fperez@colorado.edu>
3893
3894 * Updated the builtin docs (esp. the ? ones).
3895
3896 * Ran all the code through pychecker. Not terribly impressed with
3897 it: lots of spurious warnings and didn't really find anything of
3898 substance (just a few modules being imported and not used).
3899
3900 * Implemented the new ultraTB functionality into IPython. New
3901 option: xcolors. This chooses color scheme. xmode now only selects
3902 between Plain and Verbose. Better orthogonality.
3903
3904 * Large rewrite of ultraTB. Much cleaner now, with a separation of
3905 mode and color scheme for the exception handlers. Now it's
3906 possible to have the verbose traceback with no coloring.
3907
3908 2001-11-23 Fernando Perez <fperez@colorado.edu>
3909
3910 * Version 0.1.12 released, 0.1.13 opened.
3911
3912 * Removed option to set auto-quote and auto-paren escapes by
3913 user. The chances of breaking valid syntax are just too high. If
3914 someone *really* wants, they can always dig into the code.
3915
3916 * Made prompt separators configurable.
3917
3918 2001-11-22 Fernando Perez <fperez@colorado.edu>
3919
3920 * Small bugfixes in many places.
3921
3922 * Removed the MyCompleter class from ipplib. It seemed redundant
3923 with the C-p,C-n history search functionality. Less code to
3924 maintain.
3925
3926 * Moved all the original ipython.py code into ipythonlib.py. Right
3927 now it's just one big dump into a function called make_IPython, so
3928 no real modularity has been gained. But at least it makes the
3929 wrapper script tiny, and since ipythonlib is a module, it gets
3930 compiled and startup is much faster.
3931
3932 This is a reasobably 'deep' change, so we should test it for a
3933 while without messing too much more with the code.
3934
3935 2001-11-21 Fernando Perez <fperez@colorado.edu>
3936
3937 * Version 0.1.11 released, 0.1.12 opened for further work.
3938
3939 * Removed dependency on Itpl. It was only needed in one place. It
3940 would be nice if this became part of python, though. It makes life
3941 *a lot* easier in some cases.
3942
3943 * Simplified the prefilter code a bit. Now all handlers are
3944 expected to explicitly return a value (at least a blank string).
3945
3946 * Heavy edits in ipplib. Removed the help system altogether. Now
3947 obj?/?? is used for inspecting objects, a magic @doc prints
3948 docstrings, and full-blown Python help is accessed via the 'help'
3949 keyword. This cleans up a lot of code (less to maintain) and does
3950 the job. Since 'help' is now a standard Python component, might as
3951 well use it and remove duplicate functionality.
3952
3953 Also removed the option to use ipplib as a standalone program. By
3954 now it's too dependent on other parts of IPython to function alone.
3955
3956 * Fixed bug in genutils.pager. It would crash if the pager was
3957 exited immediately after opening (broken pipe).
3958
3959 * Trimmed down the VerboseTB reporting a little. The header is
3960 much shorter now and the repeated exception arguments at the end
3961 have been removed. For interactive use the old header seemed a bit
3962 excessive.
3963
3964 * Fixed small bug in output of @whos for variables with multi-word
3965 types (only first word was displayed).
3966
3967 2001-11-17 Fernando Perez <fperez@colorado.edu>
3968
3969 * Version 0.1.10 released, 0.1.11 opened for further work.
3970
3971 * Modified dirs and friends. dirs now *returns* the stack (not
3972 prints), so one can manipulate it as a variable. Convenient to
3973 travel along many directories.
3974
3975 * Fixed bug in magic_pdef: would only work with functions with
3976 arguments with default values.
3977
3978 2001-11-14 Fernando Perez <fperez@colorado.edu>
3979
3980 * Added the PhysicsInput stuff to dot_ipython so it ships as an
3981 example with IPython. Various other minor fixes and cleanups.
3982
3983 * Version 0.1.9 released, 0.1.10 opened for further work.
3984
3985 * Added sys.path to the list of directories searched in the
3986 execfile= option. It used to be the current directory and the
3987 user's IPYTHONDIR only.
3988
3989 2001-11-13 Fernando Perez <fperez@colorado.edu>
3990
3991 * Reinstated the raw_input/prefilter separation that Janko had
3992 initially. This gives a more convenient setup for extending the
3993 pre-processor from the outside: raw_input always gets a string,
3994 and prefilter has to process it. We can then redefine prefilter
3995 from the outside and implement extensions for special
3996 purposes.
3997
3998 Today I got one for inputting PhysicalQuantity objects
3999 (from Scientific) without needing any function calls at
4000 all. Extremely convenient, and it's all done as a user-level
4001 extension (no IPython code was touched). Now instead of:
4002 a = PhysicalQuantity(4.2,'m/s**2')
4003 one can simply say
4004 a = 4.2 m/s**2
4005 or even
4006 a = 4.2 m/s^2
4007
4008 I use this, but it's also a proof of concept: IPython really is
4009 fully user-extensible, even at the level of the parsing of the
4010 command line. It's not trivial, but it's perfectly doable.
4011
4012 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4013 the problem of modules being loaded in the inverse order in which
4014 they were defined in
4015
4016 * Version 0.1.8 released, 0.1.9 opened for further work.
4017
4018 * Added magics pdef, source and file. They respectively show the
4019 definition line ('prototype' in C), source code and full python
4020 file for any callable object. The object inspector oinfo uses
4021 these to show the same information.
4022
4023 * Version 0.1.7 released, 0.1.8 opened for further work.
4024
4025 * Separated all the magic functions into a class called Magic. The
4026 InteractiveShell class was becoming too big for Xemacs to handle
4027 (de-indenting a line would lock it up for 10 seconds while it
4028 backtracked on the whole class!)
4029
4030 FIXME: didn't work. It can be done, but right now namespaces are
4031 all messed up. Do it later (reverted it for now, so at least
4032 everything works as before).
4033
4034 * Got the object introspection system (magic_oinfo) working! I
4035 think this is pretty much ready for release to Janko, so he can
4036 test it for a while and then announce it. Pretty much 100% of what
4037 I wanted for the 'phase 1' release is ready. Happy, tired.
4038
4039 2001-11-12 Fernando Perez <fperez@colorado.edu>
4040
4041 * Version 0.1.6 released, 0.1.7 opened for further work.
4042
4043 * Fixed bug in printing: it used to test for truth before
4044 printing, so 0 wouldn't print. Now checks for None.
4045
4046 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4047 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4048 reaches by hand into the outputcache. Think of a better way to do
4049 this later.
4050
4051 * Various small fixes thanks to Nathan's comments.
4052
4053 * Changed magic_pprint to magic_Pprint. This way it doesn't
4054 collide with pprint() and the name is consistent with the command
4055 line option.
4056
4057 * Changed prompt counter behavior to be fully like
4058 Mathematica's. That is, even input that doesn't return a result
4059 raises the prompt counter. The old behavior was kind of confusing
4060 (getting the same prompt number several times if the operation
4061 didn't return a result).
4062
4063 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4064
4065 * Fixed -Classic mode (wasn't working anymore).
4066
4067 * Added colored prompts using Nathan's new code. Colors are
4068 currently hardwired, they can be user-configurable. For
4069 developers, they can be chosen in file ipythonlib.py, at the
4070 beginning of the CachedOutput class def.
4071
4072 2001-11-11 Fernando Perez <fperez@colorado.edu>
4073
4074 * Version 0.1.5 released, 0.1.6 opened for further work.
4075
4076 * Changed magic_env to *return* the environment as a dict (not to
4077 print it). This way it prints, but it can also be processed.
4078
4079 * Added Verbose exception reporting to interactive
4080 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4081 traceback. Had to make some changes to the ultraTB file. This is
4082 probably the last 'big' thing in my mental todo list. This ties
4083 in with the next entry:
4084
4085 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4086 has to specify is Plain, Color or Verbose for all exception
4087 handling.
4088
4089 * Removed ShellServices option. All this can really be done via
4090 the magic system. It's easier to extend, cleaner and has automatic
4091 namespace protection and documentation.
4092
4093 2001-11-09 Fernando Perez <fperez@colorado.edu>
4094
4095 * Fixed bug in output cache flushing (missing parameter to
4096 __init__). Other small bugs fixed (found using pychecker).
4097
4098 * Version 0.1.4 opened for bugfixing.
4099
4100 2001-11-07 Fernando Perez <fperez@colorado.edu>
4101
4102 * Version 0.1.3 released, mainly because of the raw_input bug.
4103
4104 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4105 and when testing for whether things were callable, a call could
4106 actually be made to certain functions. They would get called again
4107 once 'really' executed, with a resulting double call. A disaster
4108 in many cases (list.reverse() would never work!).
4109
4110 * Removed prefilter() function, moved its code to raw_input (which
4111 after all was just a near-empty caller for prefilter). This saves
4112 a function call on every prompt, and simplifies the class a tiny bit.
4113
4114 * Fix _ip to __ip name in magic example file.
4115
4116 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4117 work with non-gnu versions of tar.
4118
4119 2001-11-06 Fernando Perez <fperez@colorado.edu>
4120
4121 * Version 0.1.2. Just to keep track of the recent changes.
4122
4123 * Fixed nasty bug in output prompt routine. It used to check 'if
4124 arg != None...'. Problem is, this fails if arg implements a
4125 special comparison (__cmp__) which disallows comparing to
4126 None. Found it when trying to use the PhysicalQuantity module from
4127 ScientificPython.
4128
4129 2001-11-05 Fernando Perez <fperez@colorado.edu>
4130
4131 * Also added dirs. Now the pushd/popd/dirs family functions
4132 basically like the shell, with the added convenience of going home
4133 when called with no args.
4134
4135 * pushd/popd slightly modified to mimic shell behavior more
4136 closely.
4137
4138 * Added env,pushd,popd from ShellServices as magic functions. I
4139 think the cleanest will be to port all desired functions from
4140 ShellServices as magics and remove ShellServices altogether. This
4141 will provide a single, clean way of adding functionality
4142 (shell-type or otherwise) to IP.
4143
4144 2001-11-04 Fernando Perez <fperez@colorado.edu>
4145
4146 * Added .ipython/ directory to sys.path. This way users can keep
4147 customizations there and access them via import.
4148
4149 2001-11-03 Fernando Perez <fperez@colorado.edu>
4150
4151 * Opened version 0.1.1 for new changes.
4152
4153 * Changed version number to 0.1.0: first 'public' release, sent to
4154 Nathan and Janko.
4155
4156 * Lots of small fixes and tweaks.
4157
4158 * Minor changes to whos format. Now strings are shown, snipped if
4159 too long.
4160
4161 * Changed ShellServices to work on __main__ so they show up in @who
4162
4163 * Help also works with ? at the end of a line:
4164 ?sin and sin?
4165 both produce the same effect. This is nice, as often I use the
4166 tab-complete to find the name of a method, but I used to then have
4167 to go to the beginning of the line to put a ? if I wanted more
4168 info. Now I can just add the ? and hit return. Convenient.
4169
4170 2001-11-02 Fernando Perez <fperez@colorado.edu>
4171
4172 * Python version check (>=2.1) added.
4173
4174 * Added LazyPython documentation. At this point the docs are quite
4175 a mess. A cleanup is in order.
4176
4177 * Auto-installer created. For some bizarre reason, the zipfiles
4178 module isn't working on my system. So I made a tar version
4179 (hopefully the command line options in various systems won't kill
4180 me).
4181
4182 * Fixes to Struct in genutils. Now all dictionary-like methods are
4183 protected (reasonably).
4184
4185 * Added pager function to genutils and changed ? to print usage
4186 note through it (it was too long).
4187
4188 * Added the LazyPython functionality. Works great! I changed the
4189 auto-quote escape to ';', it's on home row and next to '. But
4190 both auto-quote and auto-paren (still /) escapes are command-line
4191 parameters.
4192
4193
4194 2001-11-01 Fernando Perez <fperez@colorado.edu>
4195
4196 * Version changed to 0.0.7. Fairly large change: configuration now
4197 is all stored in a directory, by default .ipython. There, all
4198 config files have normal looking names (not .names)
4199
4200 * Version 0.0.6 Released first to Lucas and Archie as a test
4201 run. Since it's the first 'semi-public' release, change version to
4202 > 0.0.6 for any changes now.
4203
4204 * Stuff I had put in the ipplib.py changelog:
4205
4206 Changes to InteractiveShell:
4207
4208 - Made the usage message a parameter.
4209
4210 - Require the name of the shell variable to be given. It's a bit
4211 of a hack, but allows the name 'shell' not to be hardwire in the
4212 magic (@) handler, which is problematic b/c it requires
4213 polluting the global namespace with 'shell'. This in turn is
4214 fragile: if a user redefines a variable called shell, things
4215 break.
4216
4217 - magic @: all functions available through @ need to be defined
4218 as magic_<name>, even though they can be called simply as
4219 @<name>. This allows the special command @magic to gather
4220 information automatically about all existing magic functions,
4221 even if they are run-time user extensions, by parsing the shell
4222 instance __dict__ looking for special magic_ names.
4223
4224 - mainloop: added *two* local namespace parameters. This allows
4225 the class to differentiate between parameters which were there
4226 before and after command line initialization was processed. This
4227 way, later @who can show things loaded at startup by the
4228 user. This trick was necessary to make session saving/reloading
4229 really work: ideally after saving/exiting/reloading a session,
4230 *everythin* should look the same, including the output of @who. I
4231 was only able to make this work with this double namespace
4232 trick.
4233
4234 - added a header to the logfile which allows (almost) full
4235 session restoring.
4236
4237 - prepend lines beginning with @ or !, with a and log
4238 them. Why? !lines: may be useful to know what you did @lines:
4239 they may affect session state. So when restoring a session, at
4240 least inform the user of their presence. I couldn't quite get
4241 them to properly re-execute, but at least the user is warned.
4242
4243 * Started ChangeLog.
@@ -0,0 +1,14 b''
1 Current version information
2 ---------------------------
3
4 Please open manual.pdf for a PDF version of IPython's user manual, or go to
5 the manual/ directory for an HTML version.
6
7
8 Bugs and future developments
9 ----------------------------
10
11 The new_design.pdf document is a description of the goals for IPython's future
12 development. It includes a TODO/bugs section listing all currently known bugs
13 in IPython. Please report any bug you encounter if it is not already listed
14 there.
@@ -0,0 +1,39 b''
1 Notes for Windows Users
2 =======================
3
4 These are just minimal notes. The manual contains more detailed
5 information.
6
7 Requirements
8 ------------
9
10 IPython runs under (as far as the Windows family is concerned):
11
12 - Windows XP (I think WinNT/2000 are ok): works well. It needs:
13
14 * Gary Bishop's readline from
15 http://sourceforge.net/projects/uncpythontools.
16
17 * This in turn requires Tomas Heller's ctypes from
18 http://starship.python.net/crew/theller/ctypes.
19
20 - Windows 95/98/ME: I have no idea. It should work, but I can't test.
21
22 - CygWin environments should work, they are basically Posix.
23
24 It needs Python 2.2 or newer.
25
26
27 Installation
28 ------------
29
30 Double-click the supplied .exe installer file. If all goes well, that's all
31 you need to do. You should now have an IPython entry in your Start Menu.
32
33 In case the automatic installer does not work for some reason, you can
34 download the ipython-XXX.tar.gz file, which contains the full IPython source
35 distribution (the popular WinZip can read .tar.gz files). After uncompressing
36 the archive, you can install it at a command terminal just like any other
37 Python module, by using python setup.py install'. After this completes, you
38 can run the supplied win32_manual_post_install.py script which will add
39 the relevant shortcuts to your startup menu.
@@ -0,0 +1,51 b''
1 """Quick code snippets for embedding IPython into other programs.
2
3 See example-embed.py for full details, this file has the bare minimum code for
4 cut and paste use once you understand how to use the system."""
5
6 #---------------------------------------------------------------------------
7 # This code loads IPython but modifies a few things if it detects it's running
8 # embedded in another IPython session (helps avoid confusion)
9
10 try:
11 __IPYTHON__
12 except NameError:
13 argv = ['']
14 banner = exit_msg = ''
15 else:
16 # Command-line options for IPython (a list like sys.argv)
17 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
18 banner = '*** Nested interpreter ***'
19 exit_msg = '*** Back in main IPython ***'
20
21 # First import the embeddable shell class
22 from IPython.Shell import IPShellEmbed
23 # Now create the IPython shell instance. Put ipshell() anywhere in your code
24 # where you want it to open.
25 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
26
27 #---------------------------------------------------------------------------
28 # This code will load an embeddable IPython shell always with no changes for
29 # nested embededings.
30
31 from IPython.Shell import IPShellEmbed
32 ipshell = IPShellEmbed()
33 # Now ipshell() will open IPython anywhere in the code.
34
35 #---------------------------------------------------------------------------
36 # This code loads an embeddable shell only if NOT running inside
37 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
38 # dummy function.
39
40 try:
41 __IPYTHON__
42 except NameError:
43 from IPython.Shell import IPShellEmbed
44 ipshell = IPShellEmbed()
45 # Now ipshell() will open IPython anywhere in the code
46 else:
47 # Define a dummy ipshell() so the same code doesn't crash inside an
48 # interactive IPython
49 def ipshell(): pass
50
51 #******************* End of file <example-embed-short.py> ********************
@@ -0,0 +1,127 b''
1 #!/usr/bin/env python
2
3 """An example of how to embed an IPython shell into a running program.
4
5 Please see the documentation in the IPython.Shell module for more details.
6
7 The accompanying file example-embed-short.py has quick code fragments for
8 embedding which you can cut and paste in your code once you understand how
9 things work.
10
11 The code in this file is deliberately extra-verbose, meant for learning."""
12
13 # The basics to get you going:
14
15 # IPython sets the __IPYTHON__ variable so you can know if you have nested
16 # copies running.
17
18 # Try running this code both at the command line and from inside IPython (with
19 # %run example-embed.py)
20 try:
21 __IPYTHON__
22 except NameError:
23 nested = 0
24 args = ['']
25 else:
26 print "Running nested copies of IPython."
27 print "The prompts for the nested copy have been modified"
28 nested = 1
29 # what the embedded instance will see as sys.argv:
30 args = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:','-nosep']
31
32 # First import the embeddable shell class
33 from IPython.Shell import IPShellEmbed
34
35 # Now create an instance of the embeddable shell. The first argument is a
36 # string with options exactly as you would type them if you were starting
37 # IPython at the system command line. Any parameters you want to define for
38 # configuration can thus be specified here.
39 ipshell = IPShellEmbed(args,
40 banner = 'Dropping into IPython',
41 exit_msg = 'Leaving Interpreter, back to program.')
42
43 # Make a second instance, you can have as many as you want.
44 if nested:
45 args[1] = 'In2<\\#>'
46 else:
47 args = ['-pi1','In2<\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:','-nosep']
48 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
49
50 print '\nHello. This is printed from the main controller program.\n'
51
52 # You can then call ipshell() anywhere you need it (with an optional
53 # message):
54 ipshell('***Called from top level. '
55 'Hit Ctrl-D to exit interpreter and continue program.')
56
57 print '\nBack in caller program, moving along...\n'
58
59 #---------------------------------------------------------------------------
60 # More details:
61
62 # IPShellEmbed instances don't print the standard system banner and
63 # messages. The IPython banner (which actually may contain initialization
64 # messages) is available as <instance>.IP.BANNER in case you want it.
65
66 # IPShellEmbed instances print the following information everytime they
67 # start:
68
69 # - A global startup banner.
70
71 # - A call-specific header string, which you can use to indicate where in the
72 # execution flow the shell is starting.
73
74 # They also print an exit message every time they exit.
75
76 # Both the startup banner and the exit message default to None, and can be set
77 # either at the instance constructor or at any other time with the
78 # set_banner() and set_exit_msg() methods.
79
80 # The shell instance can be also put in 'dummy' mode globally or on a per-call
81 # basis. This gives you fine control for debugging without having to change
82 # code all over the place.
83
84 # The code below illustrates all this.
85
86
87 # This is how the global banner and exit_msg can be reset at any point
88 ipshell.set_banner('Entering interpreter - New Banner')
89 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
90
91 def foo(m):
92 s = 'spam'
93 ipshell('***In foo(). Try @whos, or print s or m:')
94 print 'foo says m = ',m
95
96 def bar(n):
97 s = 'eggs'
98 ipshell('***In bar(). Try @whos, or print s or n:')
99 print 'bar says n = ',n
100
101 # Some calls to the above functions which will trigger IPython:
102 print 'Main program calling foo("eggs")\n'
103 foo('eggs')
104
105 # The shell can be put in 'dummy' mode where calls to it silently return. This
106 # allows you, for example, to globally turn off debugging for a program with a
107 # single call.
108 ipshell.set_dummy_mode(1)
109 print '\nTrying to call IPython which is now "dummy":'
110 ipshell()
111 print 'Nothing happened...'
112 # The global 'dummy' mode can still be overridden for a single call
113 print '\nOverriding dummy mode manually:'
114 ipshell(dummy=0)
115
116 # Reactivate the IPython shell
117 ipshell.set_dummy_mode(0)
118
119 print 'You can even have multiple embedded instances:'
120 ipshell2()
121
122 print '\nMain program calling bar("spam")\n'
123 bar('spam')
124
125 print 'Main program finished. Bye!'
126
127 #********************** End of file <example-embed.py> ***********************
@@ -0,0 +1,36 b''
1 #!/usr/bin/env python
2 """
3 Example code showing how to use Gnuplot and an embedded IPython shell.
4 """
5
6 from Numeric import *
7 from IPython.numutils import *
8 from IPython.Shell import IPShellEmbed
9
10 # Arguments to start IPython shell with. Load numeric profile.
11 ipargs = ['-profile','numeric']
12 ipshell = IPShellEmbed(ipargs)
13
14 # Compute sin(x) over the 0..2pi range at 200 points
15 x = frange(0,2*pi,npts=200)
16 y = sin(x)
17
18 # In the 'numeric' profile, IPython has an internal gnuplot instance:
19 g = ipshell.IP.gnuplot
20
21 # Change some defaults
22 g('set style data lines')
23
24 # Or also call a multi-line set of gnuplot commands on it:
25 g("""
26 set xrange [0:pi] # Set the visible range to half the data only
27 set title 'Half sine' # Global gnuplot labels
28 set xlabel 'theta'
29 set ylabel 'sin(theta)'
30 """)
31
32 # Now start an embedded ipython.
33 ipshell('Starting the embedded IPyhton.\n'
34 'Try calling plot(x,y), or @gpc for direct access to Gnuplot"\n')
35
36 #********************** End of file <example-gnuplot.py> *********************
@@ -0,0 +1,36 b''
1 """Example of how to define a magic function for extending IPython.
2
3 The name of the function *must* begin with magic_. IPython mangles it so
4 that magic_foo() becomes available as %foo.
5
6 The argument list must be *exactly* (self,parameter_s='').
7
8 The single string parameter_s will have the user's input. It is the magic
9 function's responsability to parse this string.
10
11 That is, if the user types
12 >>>%foo a b c
13
14 The followinng internal call is generated:
15 self.magic_foo(parameter_s='a b c').
16
17 To have any functions defined here available as magic functions in your
18 IPython environment, import this file in your configuration file with an
19 execfile = this_file.py statement. See the details at the end of the sample
20 ipythonrc file. """
21
22 # fisrt define a function with the proper form:
23 def magic_foo(self,parameter_s=''):
24 """My very own magic!. (Use docstrings, IPython reads them)."""
25 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
26 print 'The self object is:',self
27
28 # Add the new magic function to the class dict:
29 from IPython.iplib import InteractiveShell
30 InteractiveShell.magic_foo = magic_foo
31
32 # And remove the global name to keep global namespace clean. Don't worry, the
33 # copy bound to IPython stays, we're just removing the global name.
34 del magic_foo
35
36 #********************** End of file <example-magic.py> ***********************
@@ -0,0 +1,60 b''
1 """This function implements a simple grep-like function in pure python.
2
3 You can enable it by copying it to your ~/.ipython directory and putting
4
5 execfile = magic_grepl.py
6
7 in your ipythonrc file.
8
9 Code contributed by Gever Tulley <gever@helium.com>, minor changes applied.
10 """
11
12 import glob
13 import re
14 import os
15
16 def magic_grepl(self, parameter_s=''):
17 """Search for a pattern in a list of files.
18
19 It prints the names of the files containing the pattern. Similar to 'grep
20 -l' in Unix-like environments.
21
22 Usage: @grepl pattern [files]
23
24 - pattern: any regular expression pattern which re.compile() will accept.
25 - files: list of files to scan. It can contain standard unix wildcards.
26 """
27
28 # argument processing
29 params = parameter_s.split()
30 if len(params) > 1:
31 target = params[0] # first one is the target
32 file_patterns = params[1:] # all the rest are filenames or patterns
33
34 # build the regular expression
35 expr = re.compile(target)
36
37 for pattern in file_patterns:
38 flist = [f for f in glob.glob(pattern) if os.path.isfile(f)]
39 for filename in flist:
40 # open and read the whole file
41 f = open(filename,'r')
42 data = f.read()
43 f.close()
44
45 # see if pattern occurs in the file
46 if expr.search(data):
47 print filename
48 else:
49 # no parameters given
50 print("Usage: @grepl pattern [files]");
51
52 # Add the new magic function to the class dict:
53 from IPython.iplib import InteractiveShell
54 InteractiveShell.magic_grepl = magic_grepl
55
56 # And remove the global name to keep global namespace clean. Don't worry, the
57 # copy bound to IPython stays, we're just removing the global name.
58 del magic_grepl
59
60 #********************** End of file <magic_grepl.py> ***********************
This diff has been collapsed as it changes many lines, (645 lines changed) Show them Hide them
@@ -0,0 +1,645 b''
1 #LyX 1.3 created this file. For more info see http://www.lyx.org/
2 \lyxformat 221
3 \textclass article
4 \begin_preamble
5 \usepackage{hyperref}
6
7 \usepackage{color}
8 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
9 \definecolor{brown}{cmyk}{0,0.75,0.75,0.35}
10
11 % Use and configure listings package for nicely formatted code
12 \usepackage{listings}
13 \lstset{
14 language=Python,
15 basicstyle=\small\ttfamily,
16 commentstyle=\ttfamily\color{blue},
17 stringstyle=\ttfamily\color{brown},
18 showstringspaces=false,
19 breaklines=true,
20 postbreak = \space\dots
21 }
22 \end_preamble
23 \language english
24 \inputencoding auto
25 \fontscheme palatino
26 \graphics default
27 \paperfontsize 11
28 \spacing single
29 \papersize Default
30 \paperpackage a4
31 \use_geometry 1
32 \use_amsmath 0
33 \use_natbib 0
34 \use_numerical_citations 0
35 \paperorientation portrait
36 \leftmargin 1in
37 \topmargin 0.9in
38 \rightmargin 1in
39 \bottommargin 0.9in
40 \secnumdepth 3
41 \tocdepth 3
42 \paragraph_separation skip
43 \defskip medskip
44 \quotes_language english
45 \quotes_times 2
46 \papercolumns 1
47 \papersides 1
48 \paperpagestyle default
49
50 \layout Title
51
52 Interactive Notebooks for Python
53 \newline
54
55 \size small
56 An IPython project for Google's Summer of Code 2005
57 \layout Author
58
59 Fernando P
60 \begin_inset ERT
61 status Collapsed
62
63 \layout Standard
64
65 \backslash
66 '{e}
67 \end_inset
68
69 rez
70 \begin_inset Foot
71 collapsed true
72
73 \layout Standard
74
75
76 \family typewriter
77 \size small
78 Fernando.Perez@colorado.edu
79 \end_inset
80
81
82 \layout Abstract
83
84 This project aims to develop a file format and interactive support for documents
85 which can combine Python code with rich text and embedded graphics.
86 The initial requirements only aim at being able to edit such documents
87 with a normal programming editor, with final rendering to PDF or HTML being
88 done by calling an external program.
89 The editing component would have to be integrated with IPython.
90
91 \layout Abstract
92
93 This document was written by the IPython developer; it is made available
94 to students looking for projects of interest and for inclusion in their
95 application.
96 \layout Section
97
98 Project overview
99 \layout Standard
100
101 Python's interactive interpreter is one of the language's most appealing
102 features for certain types of usage, yet the basic shell which ships with
103 the language is very limited.
104 Over the last few years, IPython
105 \begin_inset Foot
106 collapsed true
107
108 \layout Standard
109
110
111 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
112
113 \end_inset
114
115
116 \end_inset
117
118 has become the de facto standard interactive shell in the scientific computing
119 community, and it enjoys wide popularity with general audiences.
120 All the major Linux distributions (Fedora Core via Extras, SUSE, Debian)
121 and OS X (via fink) carry IPython, and Windows users report using it as
122 a viable system shell.
123 \layout Standard
124
125 However, IPython is currently a command-line only application, based on
126 the readline library and hence with single-line editing capabilities.
127 While this kind of usage is sufficient for many contexts, there are usage
128 cases where integration in a graphical user interface (GUI) is desirable.
129
130 \layout Standard
131
132 In particular, we wish to have an interface where users can execute Python
133 code, input regular text (neither code nor comments) and keep inline graphics,
134 which we will call
135 \emph on
136 Python notebooks
137 \emph default
138 .
139 This kind of system is very popular in scientific computing; well known
140 implementations can be found in Mathematica
141 \begin_inset ERT
142 status Collapsed
143
144 \layout Standard
145
146 \backslash
147 texttrademark
148 \end_inset
149
150 \SpecialChar ~
151
152 \begin_inset Foot
153 collapsed true
154
155 \layout Standard
156
157
158 \begin_inset LatexCommand \htmlurl{http://www.wolfram.com/products/mathematica}
159
160 \end_inset
161
162
163 \end_inset
164
165 and Maple
166 \begin_inset ERT
167 status Collapsed
168
169 \layout Standard
170
171 \backslash
172 texttrademark
173 \end_inset
174
175 \SpecialChar ~
176
177 \begin_inset Foot
178 collapsed true
179
180 \layout Standard
181
182
183 \begin_inset LatexCommand \htmlurl{http://www.maplesoft.com}
184
185 \end_inset
186
187
188 \end_inset
189
190 , among others.
191 However, these are proprietary (and quite expensive) systems aimed at an
192 audience of mathematicians, scientists and engineers.
193 \layout Standard
194
195 The full-blown implementation of a graphical shell supporting this kind
196 of work model is probably too ambitious for a summer project.
197 Simultaneous support for rich-text editing, embedded graphics and syntax-highli
198 ghted code is extremely complex, and likely to require far more effort than
199 can be mustered by an individual developer for a short-term project.
200 \layout Standard
201
202 This project will thus aim to build the necessary base infrastructure to
203 be able to edit such documents from a plain text editor, and to render
204 them to suitable formats for printing or online distribution, such as HTML,
205 PDF or PostScript.
206 This model follows that for the production of LaTeX documents, which can
207 be edited with any text editor.
208 \layout Standard
209
210 Such documents would be extremely useful for many audiences beyond scientists:
211 one can use them to produce additionally documented code, to explore a
212 problem with Python and maintain all relevant information in the same place,
213 as a way to distribute enhanced Python-based educational materials, etc.
214 \layout Standard
215
216 Demand for such a system exists, as evidenced by repeated requests made
217 to me by IPython users over the last few years.
218 Unfortunately IPython is only a spare-time project for me, and I have not
219 had the time to devote to this, despite being convinced of its long term
220 value and wide appeal.
221 \layout Standard
222
223 If this project is successful, the infrastructure laid out by it will be
224 immediately useful for Python users wishing to maintain `literate' programs
225 which include rich formatting.
226 In addition, this will open the door for the future development of graphical
227 shells which can render such documents in real time: this is exactly the
228 development model successfully followed by the LyX
229 \begin_inset Foot
230 collapsed true
231
232 \layout Standard
233
234
235 \begin_inset LatexCommand \htmlurl{http://www.lyx.org}
236
237 \end_inset
238
239
240 \end_inset
241
242 document processing system.
243 \layout Section
244
245 Implementation effort
246 \layout Subsection
247
248 Specific goals
249 \layout Standard
250
251 This is a brief outline of the main points of this project.
252 The next section provides details on all of them.
253 The student(s) working on the project would need to:
254 \layout Enumerate
255
256 Make design decisions for the internal file structure to enable valid Python
257 notebooks.
258
259 \layout Enumerate
260
261 Implement the rendering library, capable of processing an input notebook
262 through reST or LaTeX and producing HTML or PDF output, as well as exporting
263 a `pure-code' Python file stripped of all markup calls.
264 \layout Enumerate
265
266 Study existing programming editor widgets to find the most suitable one
267 for extending with an IPython connector for interactive execution of the
268 notebooks.
269 \layout Subsection
270
271 Complexity level
272 \layout Standard
273
274 This project is relatively complicated.
275 While I will gladly assist the student with design and implementation issues,
276 it will require a fair amount of thinking in terms of overall library architect
277 ure.
278 The actual implementation does not require any sophisticated concepts,
279 but rather a reasonably broad knowledge of a wide set of topics (markup,
280 interaction with external programs and libraries, namespace tricks to provide
281 runtime changes in the effect of the markup calls, etc.)
282 \layout Standard
283
284 While raw novices are welcome to try, I suspect that it may be a bit too
285 much for them.
286 Students wanting to apply should keep in mind, if the money is an important
287 consideration, that Google only gives the $4500 reward upon
288 \emph on
289 successful completion
290 \emph default
291 of the project.
292 So don't bite more than you can chew.
293 Obviously if this doesn't matter, anyone is welcome to participate, since
294 the project can be a very interesting learning experience, and it will
295 provide a genuinely useful tool for many.
296 \layout Section
297
298 Technical details
299 \layout Subsection
300
301 The files
302 \layout Standard
303
304 A basic requirement of this project will be that the Python notebooks shall
305 be valid Python source files, typically with a
306 \family typewriter
307 .py
308 \family default
309 extension.
310 A renderer program can be used to process the markup calls in them and
311 generate output.
312 If run at a regular command line, these files should execute like normal
313 Python files.
314 But when run via a special rendering script, the result should be a properly
315 formatted file.
316 Output formats could be PDF or HTML depending on user-supplied options.
317 \layout Standard
318
319 A reST markup mode should be implemented, as reST is already widely used
320 in the Python community and is a very simple format to write.
321 The following is a sketch of what such files could look like using reST
322 markup:
323 \layout Standard
324
325
326 \begin_inset ERT
327 status Open
328
329 \layout Standard
330
331 \backslash
332 lstinputlisting{nbexample.py}
333 \end_inset
334
335
336 \layout Standard
337
338 Additionally, a LaTeX markup mode should also be implemented.
339 Here's a mockup example of what code using the LaTeX mode could look like.
340 \layout Standard
341
342
343 \begin_inset ERT
344 status Open
345
346 \layout Standard
347
348 \backslash
349 lstinputlisting{nbexample_latex.py}
350 \end_inset
351
352
353 \layout Standard
354
355 At this point, it must be noted that the code above is simply a sketch of
356 these ideas, not a finalized design.
357 An important part of this project will be to think about what the best
358 API and structure for this problem should be.
359 \layout Subsection
360
361 From notebooks to PDF, HTML or Python
362 \layout Standard
363
364 Once a clean API for markup has been specified, converters will be written
365 to take a python source file which uses notebook constructs, and generate
366 final output in printable formats, such as HTML or PDF.
367 For example, if
368 \family typewriter
369 nbfile.py
370 \family default
371 is a python notebook, then
372 \layout LyX-Code
373
374 $ pynb --export=pdf nbfile.py
375 \layout Standard
376
377 should produce
378 \family typewriter
379 nbfile.pdf
380 \family default
381 , while
382 \layout LyX-Code
383
384 $ pynb --export=html nbfile.py
385 \layout Standard
386
387 would produce an HTML version.
388 The actual rendering will be done by calling appropriate utilities, such
389 as the reST toolchain or LaTeX, depending on the markup used by the file.
390 \layout Standard
391
392 Additionally, while the notebooks will be valid Python files, if executed
393 on their own, all the markup calls will still return their results, which
394 are not really needed when the file is being treated as pure code.
395 For this reason, a module to execute these files turning the markup calls
396 into no-ops should be written.
397 Using Python 2.4's -m switch, one can then use something like
398 \layout LyX-Code
399
400 $ python -m notebook nbfile.py
401 \layout Standard
402
403 and the notebook file
404 \family typewriter
405 nbfile.py
406 \family default
407 will be executed without any overhead introduced by the markup (other than
408 making calls to functions which return immediately).
409 Finally, an exporter to clean code can be trivially implemented, so that:
410 \layout LyX-Code
411
412 $ pynb --export=python nbfile.py nbcode.py
413 \layout Standard
414
415 would export only the code in
416 \family typewriter
417 nbfile.py
418 \family default
419 to
420 \family typewriter
421 nbcode.py
422 \family default
423 , removing the markup completely.
424 This can be used to generate final production versions of large modules
425 implemented as notebooks, if one wants to eliminate the markup overhead.
426 \layout Subsection
427
428 The editing environment
429 \layout Standard
430
431 The first and most important part of the project should be the definition
432 of a clean API and the implementation of the exporter modules as indicated
433 above.
434 Ultimately, such files can be developed using any text editor, since they
435 are nothing more than regular Python code.
436 \layout Standard
437
438 But once these goals are reached, further integration with an editor will
439 be done, without the need for a full-blown GUI shell.
440 In fact, already today the (X)Emacs editors can provide for interactive
441 usage of such files.
442 Using python-mode in (X)Emacs, one can pass highlighted regions of a file
443 for execution to an underlying python process, and the results are printed
444 in the python window.
445 With recent versions of python-mode, IPython can be used instead of the
446 plain python interpreter, so that IPython's extended interactive capabilities
447 become available within (X)Emacs (improved tracebacks, automatic debugger
448 integration, variable information, easy filesystem access to Python, etc).
449 \layout Standard
450
451 But even with IPython integration, the usage within (X)Emacs is not ideal
452 for a notebook environment, since the python process buffer is separate
453 from the python file.
454 Therefore, the next stage of the project will be to enable tighter integration
455 between the editing and execution environments.
456 The basic idea is to provide an easy way to mark regions of the file to
457 be executed interactively, and to have the output inserted automatically
458 into the file.
459 The following listing is a mockup of what the resulting file could look
460 like
461 \layout Standard
462
463
464 \begin_inset ERT
465 status Open
466
467 \layout Standard
468
469 \backslash
470 lstinputlisting{nbexample_output.py}
471 \end_inset
472
473
474 \layout Standard
475
476 Basically, the editor will execute
477 \family typewriter
478 add(2,3)
479 \family default
480 and insert the string representation of the output into the file, so it
481 can be used for rendering later.
482
483 \layout Section
484
485 Available resources
486 \layout Standard
487
488 IPython currently has all the necessary infrastructure for code execution,
489 albeit in a rather messy code base.
490 Most I/O is already abstracted out, a necessary condition for embedding
491 in a GUI (since you are not writing to stdout/err but to the GUI's text
492 area).
493
494 \layout Standard
495
496 For interaction with an editor, it will be necessary to identify a good
497 programming editor with a Python-compatible license, which can be extended
498 to communicate with the underlying IPython engine.
499 IDLE, the Tk-based IDE which ships with Python, should obviously be considered.
500 The Scintilla editing component
501 \begin_inset Foot
502 collapsed true
503
504 \layout Standard
505
506
507 \begin_inset LatexCommand \htmlurl{http://www.scintilla.org}
508
509 \end_inset
510
511
512 \end_inset
513
514 may also be a viable candidate.
515
516 \layout Standard
517
518 It will also be interesting to look at the LyX editor
519 \begin_inset Foot
520 collapsed true
521
522 \layout Standard
523
524
525 \begin_inset LatexCommand \htmlurl{http://www.lyx.org}
526
527 \end_inset
528
529
530 \end_inset
531
532 , which already offers a Python client
533 \begin_inset Foot
534 collapsed true
535
536 \layout Standard
537
538
539 \begin_inset LatexCommand \htmlurl{http://wiki.lyx.org/Tools/PyClient}
540
541 \end_inset
542
543
544 \end_inset
545
546 .
547 Since LyX has very sophisticated LaTeX support, this is a very interesting
548 direction to consider for the future (though LyX makes a poor programming
549 editor).
550 \layout Section
551
552 Support offered to the students
553 \layout Standard
554
555 The IPython project already has an established Open Source infrastructure,
556 including CVS repositories, a bug tracker and mailing lists.
557 As the main author and sole maintainer of IPython, I will personally assist
558 the student(s) funded with architectural and design guidance, preferably
559 on the public development mailing list.
560 I expect them to start working by submitting patches until they show, by
561 the quality of their work, that they can be granted CVS write access.
562 I expect most actual implementation work to be done by the students, though
563 I will provide assistance if they need it with a specific technical issue.
564 \layout Standard
565
566 If more than one applicant is accepted to work on this project, there is
567 more than enough work to be done which can be coordinated between them.
568 \layout Section
569
570 Licensing and copyright
571 \layout Standard
572
573 IPython is licensed under BSD terms, and copyright of all sources rests
574 with the original authors of the core modules.
575 Over the years, all external contributions have been small enough patches
576 that they have been simply folded into the main source tree without additional
577 copyright attributions, though explicit credit has always been given to
578 all contributors.
579 \layout Standard
580
581 I expect the students participating in this project to contribute enough
582 standalone code that they can retain the copyright to it if they so desire,
583 as long as they accept all their work to be licensed under BSD terms.
584 \layout Section
585
586 Acknowledgements
587 \layout Standard
588
589 I'd like to thank John D.
590 Hunter, the author of matplotlib
591 \begin_inset Foot
592 collapsed true
593
594 \layout Standard
595
596
597 \begin_inset LatexCommand \htmlurl{http://matplotlib.sf.net}
598
599 \end_inset
600
601
602 \end_inset
603
604 , for lengthy discussions which helped clarify much of this project.
605 In particular, the important decision of embedding the notebook markup
606 calls in true Python functions instead of specially-tagged strings or comments
607 was an idea I thank him for pushing hard enough to convince me of using.
608
609 \layout Standard
610
611 My conversations with Brian Granger, the author of PyXG
612 \begin_inset Foot
613 collapsed true
614
615 \layout Standard
616
617
618 \begin_inset LatexCommand \htmlurl{http://hammonds.scu.edu/~classes/pyxg.html}
619
620 \end_inset
621
622
623 \end_inset
624
625 and braid
626 \begin_inset Foot
627 collapsed true
628
629 \layout Standard
630
631
632 \begin_inset LatexCommand \htmlurl{http://hammonds.scu.edu/~classes/braid.html}
633
634 \end_inset
635
636
637 \end_inset
638
639 , have also been very useful in clarifying details of the necessary underlying
640 infrastructure and future evolution of IPython for this kind of system.
641 \layout Standard
642
643 Thank you also to the IPython users who have, in the past, discussed this
644 topic with me either in private or on the IPython or Scipy lists.
645 \the_end
@@ -0,0 +1,392 b''
1 .\" Hey, EMACS: -*- nroff -*-
2 .\" First parameter, NAME, should be all caps
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
4 .\" other parameters are allowed: see man(7), man(1)
5 .TH IPYTHON 1 "November 30, 2004"
6 .\" Please adjust this date whenever revising the manpage.
7 .\"
8 .\" Some roff macros, for reference:
9 .\" .nh disable hyphenation
10 .\" .hy enable hyphenation
11 .\" .ad l left justify
12 .\" .ad b justify to both left and right margins
13 .\" .nf disable filling
14 .\" .fi enable filling
15 .\" .br insert line break
16 .\" .sp <n> insert n+1 empty lines
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
18 .\" .SH section heading
19 .\" .SS secondary section heading
20 .\"
21 .\"
22 .\" To preview this page as plain text: nroff -man ipython.1
23 .\"
24 .SH NAME
25 ipython \- An Enhanced Interactive Python
26 .SH SYNOPSIS
27 .B ipython
28 .RI [ options ] " files" ...
29 .SH DESCRIPTION
30 An interactive Python shell with automatic history (input and output),
31 dynamic object introspection, easier configuration, command
32 completion, access to the system shell, integration with numerical and
33 scientific computing tools, and more.
34 .SH SPECIAL THREADING OPTIONS
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
37 ipython itself, before the normal option-handling mechanism is active.
38 .TP
39 .B \-gthread, \-qthread, \-wthread, \-pylab
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
42 provide threading support for the GTK, QT and WXWidgets toolkits, and for the
43 matplotlib library.
44 .br
45 .sp 1
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
48 graphical elements from within an IPython command line, without blocking. All
49 three provide essentially the same functionality, respectively for GTK, QT and
50 WXWidgets (via their Python interfaces).
51 .br
52 .sp 1
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
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
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.
59 .TP
60 .B \-tk
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
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.
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,
67 \-wthread or \-pylab).
68 .br
69 .sp 1
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
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
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
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
78 user reports are available.
79 .br
80 .sp 1
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
83 relying on it for regular work.
84 .
85 .SS A WARNING ABOUT SIGNALS AND THREADS
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
88 long-running Python code via Ctrl\-C. IPython can not pass the
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
91 to be killed via an external (OS-based) mechanism.
92 .br
93 .sp 1
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
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,
98 look at the Shell.py module, and in particular at the runcode() method.
99 .
100 .SH REGULAR OPTIONS
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
103 form and are case-sensitive. One or two dashes can be used. Some options
104 have an alternate short form, indicated after a |.
105 .br
106 .sp 1
107 Most options can also be set from your ipythonrc configuration file.
108 See the provided examples for assistance. Options given on the
109 commandline override the values set in the ipythonrc file.
110 .br
111 .sp 1
112 All options with a no| prepended can be specified in 'no' form
113 (\-nooption instead of \-option) to turn the feature off.
114 .TP
115 .B \-h, \-\-help
116 Show summary of options.
117 .TP
118 .B \-no|autocall
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.
121 .TP
122 .B \-no|autoindent
123 Turn automatic indentation on/off.
124 .TP
125 .B \-no|automagic
126 Make magic commands automatic (without needing their first character
127 to be @). Type @magic at the IPython prompt for more information.
128 .TP
129 .B \-no|autoparens
130 Make IPython automatically call any callable object even if you didn't
131 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
132 automatically.
133 .TP
134 .B \-no|banner
135 Print the intial information banner (default on).
136 .TP
137 .B \-c <command>
138 Execute the given command string, and set sys.argv to ['c']. This is similar
139 to the \-c option in the normal Python interpreter.
140 .TP
141 .B \-cache_size|cs <n>
142 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
144 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
146 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
148 than working.
149 .TP
150 .B \-classic|cl
151 Gives IPython a similar feel to the classic Python prompt.
152 .TP
153 .B \-colors <scheme>
154 Color scheme for prompts and exception reporting. Currently
155 implemented: NoColor, Linux, and LightBG.
156 .TP
157 .B \-no|color_info
158 IPython can display information about objects via a set of functions,
159 and optionally can use colors for this, syntax highlighting source
160 code and various other elements. However, because this information is
161 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
163 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
165 that in RedHat 7.2 doesn't.
166 .br
167 .sp 1
168 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
170 testing.
171 .TP
172 .B \-no|confirm_exit
173 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
175 @Exit or @Quit you can force a direct exit, bypassing any
176 confirmation.
177 .TP
178 .B \-no|debug
179 Show information about the loading process. Very useful to pin down
180 problems with your configuration files or to get details about session
181 restores.
182 .TP
183 .B \-no|deep_reload
184 IPython can use the deep_reload module which reloads changes in
185 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
187 of modules whose code may have changed, which the default reload()
188 function does not.
189 .br
190 .sp 1
191 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
193 by default [which means that you have both normal reload() and
194 dreload()].
195 .TP
196 .B \-editor <name>
197 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
199 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
201 may want to use a small, lightweight editor here (in case your default
202 EDITOR is something like Emacs).
203 .TP
204 .B \-ipythondir <name>
205 The name of your IPython configuration directory IPYTHONDIR. This can
206 also be specified through the environment variable IPYTHONDIR.
207 .TP
208 .B \-log|l
209 Generate a log file of all input. The file is named ipython.log in
210 your current directory (which prevents logs from multiple IPython
211 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
213 -logplay (see below).
214 .TP
215 .B \-logfile|lf
216 Specifu the name of your logfile.
217 .TP
218 .B \-logplay|lp
219 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
221 logfile). With \-logplay, IPython will try to reconstruct the previous
222 working environment in full, not just execute the commands in the
223 logfile.
224 .br
225 .sh 1
226 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
228 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
230 continue to log its history and restore from the beginning every time.
231 .br
232 .sp 1
233 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
235 to implement full session saving by writing and retrieving a
236 'snapshot' of the memory state of IPython. But our first attempts
237 failed because of inherent limitations of Python's Pickle module, so
238 this may have to wait.
239 .TP
240 .B \-no|messages
241 Print messages which IPython collects about its startup process
242 (default on).
243 .TP
244 .B \-no|pdb
245 Automatically call the pdb debugger after every uncaught exception. If
246 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
248 it) which triggers an exception which goes uncaught.
249 .TP
250 .B \-no|pprint
251 IPython can optionally use the pprint (pretty printer) module for
252 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
254 your config file (default off).
255 .TP
256 .B \-profile|p <name>
257 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
259 multiple config files for different tasks, especially if you use the
260 include option of config files. You can keep a basic
261 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
262 this one and load extra things for particular tasks. For example:
263 .br
264 .sp 1
265 1) $HOME/.ipython/ipythonrc : load basic things you always want.
266 .br
267 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
268 modules.
269 .br
270 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
271 plotting modules.
272 .br
273 .sp 1
274 Since it is possible to create an endless loop by having circular file
275 inclusions, IPython will stop if it reaches 15 recursive inclusions.
276 .TP
277 .B \-prompt_in1|pi1 <string>
278 Specify the string used for input prompts. Note that if you are using
279 numbered prompts, the number is represented with a '\\#' in the
280 string. Don't forget to quote strings with spaces embedded in
281 them. Default: 'In [\\#]:'.
282 .br
283 .sp 1
284 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
286 are described in detail in the Customization section of the IPython HTML/PDF
287 manual.
288 .TP
289 .B \-prompt_in2|pi2 <string>
290 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
292 (so you can have your continuation prompt aligned with your input
293 prompt). Default: ' .\\D.:' (note three spaces at the start for alignment
294 with 'In [\\#]').
295 .TP
296 .B \-prompt_out|po <string>
297 String used for output prompts, also uses numbers like prompt_in1.
298 Default: 'Out[\\#]:'.
299 .TP
300 .B \-quick
301 Start in bare bones mode (no config file loaded).
302 .TP
303 .B \-rcfile <name>
304 Name of your IPython resource configuration file. normally IPython
305 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
306 the loading of your config file fails, IPython starts with a bare
307 bones configuration (no modules loaded at all).
308 .TP
309 .B \-no|readline
310 Use the readline library, which is needed to support name completion
311 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
313 buffers.
314 .br
315 .sp 1
316 Note that emacs 'eterm' buffers (opened with M-x term) support
317 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
318 and C-c !) buffers do not.
319 .TP
320 .B \-screen_length|sl <n>
321 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
323 sent through a pager instead of directly printed.
324 .br
325 .sp 1
326 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
328 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
330 (it needs curses support), specify it yourself. Otherwise don't change
331 the default.
332 .TP
333 .B \-separate_in|si <string>
334 Separator before input prompts. Default '\n'.
335 .TP
336 .B \-separate_out|so <string>
337 Separator before output prompts. Default: 0 (nothing).
338 .TP
339 .B \-separate_out2|so2 <string>
340 Separator after output prompts. Default: 0 (nothing).
341 .TP
342 .B \-nosep
343 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
344 Simply removes all input/output separators.
345 .TP
346 .B \-upgrade
347 Allows you to upgrade your IPYTHONDIR configuration when you install a
348 new version of IPython. Since new versions may include new command
349 lines options or example files, this copies updated ipythonrc-type
350 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
352 have in your personal files.
353 .TP
354 .B \-Version
355 Print version information and exit.
356 .TP
357 .B \-xmode <modename>
358 Mode for exception reporting. The valid modes are Plain, Context, and
359 Verbose.
360 .br
361 .sp 1
362 \- Plain: similar to python's normal traceback printing.
363 .br
364 .sp 1
365 \- Context: prints 5 lines of context source code around each line in the
366 traceback.
367 .br
368 .sp 1
369 \- Verbose: similar to Context, but additionally prints the variables
370 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
372 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
374 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
375 once).
376 .
377 .SH EMBEDDING
378 It is possible to start an IPython instance inside your own Python
379 programs. In the documentation example files there are some
380 illustrations on how to do this.
381 .br
382 .sp 1
383 This feature allows you to evalutate dynamically the state of your
384 code, operate with your variables, analyze them, etc. Note however
385 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
387 values because you won't break your code in bizarre ways by doing so.
388 .SH AUTHOR
389 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
390 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
391 <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).
@@ -0,0 +1,398 b''
1 ;;; ipython.el --- Adds support for IPython to python-mode.el
2
3 ;; Copyright (C) 2002, 2003, 2004, 2005 Alexander Schmolck
4 ;; Author: Alexander Schmolck
5 ;; Keywords: ipython python languages oop
6 ;; URL: http://ipython.scipy.org
7 ;; Compatibility: Emacs21, XEmacs21
8 ;; FIXME: #$@! INPUT RING
9 (defconst ipython-version "$Revision: 565 $"
10 "VC version number.")
11
12 ;;; Commentary
13 ;; This library makes all the functionality python-mode has when running with
14 ;; the normal python-interpreter available for ipython, too. It also enables a
15 ;; persistent py-shell command history accross sessions (if you exit python
16 ;; with C-d in py-shell) and defines the command `ipython-to-doctest', which
17 ;; can be used to convert bits of a ipython session into something that can be
18 ;; used for doctests. To install, put this file somewhere in your emacs
19 ;; `load-path' [1] and add the following line to your ~/.emacs file (the first
20 ;; line only needed if the default (``"ipython"``) is wrong)::
21 ;;
22 ;; (setq ipython-command "/SOME-PATH/ipython")
23 ;; (require 'ipython)
24 ;;
25 ;; Ipython will be set as the default python shell, but only if the ipython
26 ;; executable is in the path. For ipython sessions autocompletion with <tab>
27 ;; is also enabled (experimental feature!). Please also note that all the
28 ;; terminal functions in py-shell are handled by emacs's comint, **not** by
29 ;; (i)python, so importing readline etc. will have 0 effect.
30 ;;
31 ;; To start an interactive ipython session run `py-shell' with ``M-x py-shell``
32 ;; (or the default keybinding ``C-c C-!``).
33 ;;
34 ;; NOTE: This mode is currently somewhat alpha and although I hope that it
35 ;; will work fine for most cases, doing certain things (like the
36 ;; autocompletion and a decent scheme to switch between python interpreters)
37 ;; properly will also require changes to ipython that will likely have to wait
38 ;; for a larger rewrite scheduled some time in the future.
39 ;;
40 ;; Also note that you currently NEED THE CVS VERSION OF PYTHON.EL.
41 ;;
42 ;; Further note that I don't know whether this runs under windows or not and
43 ;; that if it doesn't I can't really help much, not being afflicted myself.
44 ;;
45 ;;
46 ;; Hints for effective usage
47 ;; -------------------------
48 ;;
49 ;; - IMO the best feature by far of the ipython/emacs combo is how much easier it
50 ;; makes it to find and fix bugs thanks to the ``@pdb on``/ pdbtrack combo. Try
51 ;; it: first in the ipython to shell do ``@pdb on`` then do something that will
52 ;; raise an exception (FIXME nice example) -- and be amazed how easy it is to
53 ;; inspect the live objects in each stack frames and to jump to the
54 ;; corresponding sourcecode locations as you walk up and down the stack trace
55 ;; (even without ``%pdb on`` you can always use ``C-c -`` (`py-up-exception')
56 ;; to jump to the corresponding source code locations).
57 ;;
58 ;; - emacs gives you much more powerful commandline editing and output searching
59 ;; capabilities than ipython-standalone -- isearch is your friend if you
60 ;; quickly want to print 'DEBUG ...' to stdout out etc.
61 ;;
62 ;; - This is not really specific to ipython, but for more convenient history
63 ;; access you might want to add something like the following to *the beggining*
64 ;; of your ``.emacs`` (if you want behavior that's more similar to stand-alone
65 ;; ipython, you can change ``meta p`` etc. for ``control p``)::
66 ;;
67 ;; (require 'comint)
68 ;; (define-key comint-mode-map [(meta p)]
69 ;; 'comint-previous-matching-input-from-input)
70 ;; (define-key comint-mode-map [(meta n)]
71 ;; 'comint-next-matching-input-from-input)
72 ;; (define-key comint-mode-map [(control meta n)]
73 ;; 'comint-next-input)
74 ;; (define-key comint-mode-map [(control meta p)]
75 ;; 'comint-previous-input)
76 ;;
77 ;; - Be aware that if you customize py-python-command previously, this value
78 ;; will override what ipython.el does (because loading the customization
79 ;; variables comes later).
80 ;;
81 ;; Please send comments and feedback to the ipython-list
82 ;; (<ipython-user@scipy.net>) where I (a.s.) or someone else will try to
83 ;; answer them (it helps if you specify your emacs version, OS etc;
84 ;; familiarity with <http://www.catb.org/~esr/faqs/smart-questions.html> might
85 ;; speed up things further).
86 ;;
87 ;; Footnotes:
88 ;;
89 ;; [1] If you don't know what `load-path' is, C-h v load-path will tell
90 ;; you; if required you can also add a new directory. So assuming that
91 ;; ipython.el resides in ~/el/, put this in your emacs:
92 ;;
93 ;;
94 ;; (add-to-list 'load-path "~/el")
95 ;; (setq ipython-command "/some-path/ipython")
96 ;; (require 'ipython)
97 ;;
98 ;;
99 ;;
100 ;;
101 ;; TODO:
102 ;; - do autocompletion properly
103 ;; - implement a proper switching between python interpreters
104 ;;
105 ;; BUGS:
106 ;; - neither::
107 ;;
108 ;; (py-shell "-c print 'FOOBAR'")
109 ;;
110 ;; nor::
111 ;;
112 ;; (let ((py-python-command-args (append py-python-command-args
113 ;; '("-c" "print 'FOOBAR'"))))
114 ;; (py-shell))
115 ;;
116 ;; seem to print anything as they should
117 ;;
118 ;; - look into init priority issues with `py-python-command' (if it's set
119 ;; via custom)
120
121
122 ;;; Code
123 (require 'cl)
124 (require 'shell)
125 (require 'executable)
126 (require 'ansi-color)
127
128 (defcustom ipython-command "ipython"
129 "*Shell command used to start ipython."
130 :type 'string
131 :group 'python)
132
133 ;; Users can set this to nil
134 (defvar py-shell-initial-switch-buffers t
135 "If nil, don't switch to the *Python* buffer on the first call to
136 `py-shell'.")
137
138 (defvar ipython-backup-of-py-python-command nil
139 "HACK")
140
141
142 (defvar ipython-de-input-prompt-regexp "\\(?:
143 In \\[[0-9]+\\]: *.*
144 ----+> \\(.*
145 \\)[\n]?\\)\\|\\(?:
146 In \\[[0-9]+\\]: *\\(.*
147 \\)\\)\\|^[ ]\\{3\\}[.]\\{3,\\}: *\\(.*
148 \\)"
149 "A regular expression to match the IPython input prompt and the python
150 command after it. The first match group is for a command that is rewritten,
151 the second for a 'normal' command, and the third for a multiline command.")
152 (defvar ipython-de-output-prompt-regexp "^Out\\[[0-9]+\\]: "
153 "A regular expression to match the output prompt of IPython.")
154
155
156 (if (not (executable-find ipython-command))
157 (message (format "Can't find executable %s - ipython.el *NOT* activated!!!"
158 ipython-command))
159 ;; XXX load python-mode, so that we can screw around with its variables
160 ;; this has the disadvantage that python-mode is loaded even if no
161 ;; python-file is ever edited etc. but it means that `py-shell' works
162 ;; without loading a python-file first. Obviously screwing around with
163 ;; python-mode's variables like this is a mess, but well.
164 (require 'python-mode)
165 ;; turn on ansi colors for ipython and activate completion
166 (defun ipython-shell-hook ()
167 ;; the following is to synchronize dir-changes
168 (make-local-variable 'shell-dirstack)
169 (setq shell-dirstack nil)
170 (make-local-variable 'shell-last-dir)
171 (setq shell-last-dir nil)
172 (make-local-variable 'shell-dirtrackp)
173 (setq shell-dirtrackp t)
174 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
175
176 (ansi-color-for-comint-mode-on)
177 (define-key py-shell-map [tab] 'ipython-complete)
178 ;;XXX this is really just a cheap hack, it only completes symbols in the
179 ;;interactive session -- useful nonetheless.
180 (define-key py-mode-map [(meta tab)] 'ipython-complete))
181 (add-hook 'py-shell-hook 'ipython-shell-hook)
182 ;; Regular expression that describes tracebacks for IPython in context and
183 ;; verbose mode.
184
185 ;;Adapt python-mode settings for ipython.
186 ;; (this works for %xmode 'verbose' or 'context')
187
188 ;; XXX putative regexps for syntax errors; unfortunately the
189 ;; current python-mode traceback-line-re scheme is too primitive,
190 ;; so it's either matching syntax errors, *or* everything else
191 ;; (XXX: should ask Fernando for a change)
192 ;;"^ File \"\\(.*?\\)\", line \\([0-9]+\\).*\n.*\n.*\nSyntaxError:"
193 ;;^ File \"\\(.*?\\)\", line \\([0-9]+\\)"
194 (setq py-traceback-line-re
195 "\\(^[^\t ].+?\\.py\\).*\n +[0-9]+[^\00]*?\n-+> \\([0-9]+\\) +")
196
197 (setq py-shell-input-prompt-1-regexp "^In \\[[0-9]+\\]: *"
198 py-shell-input-prompt-2-regexp "^ [.][.][.]+: *" )
199 ;; select a suitable color-scheme
200 (unless (member "-colors" py-python-command-args)
201 (setq py-python-command-args
202 (nconc py-python-command-args
203 (list "-colors"
204 (cond
205 ((eq frame-background-mode 'dark)
206 "DarkBG")
207 ((eq frame-background-mode 'light)
208 "LightBG")
209 (t ; default (backg-mode isn't always set by XEmacs)
210 "LightBG"))))))
211 (unless (equal ipython-backup-of-py-python-command py-python-command)
212 (setq ipython-backup-of-py-python-command py-python-command))
213 (setq py-python-command ipython-command))
214
215
216 ;; MODIFY py-shell so that it loads the editing history
217 (defadvice py-shell (around py-shell-with-history)
218 "Add persistent command-history support (in
219 $PYTHONHISTORY (or \"~/.ipython/history\", if we use IPython)). Also, if
220 `py-shell-initial-switch-buffers' is nil, it only switches to *Python* if that
221 buffer already exists."
222 (if (comint-check-proc "*Python*")
223 ad-do-it
224 (setq comint-input-ring-file-name
225 (if (string-equal py-python-command ipython-command)
226 (concat (or (getenv "IPYTHONDIR") "~/.ipython") "/history")
227 (or (getenv "PYTHONHISTORY") "~/.python-history.py")))
228 (comint-read-input-ring t)
229 (let ((buf (current-buffer)))
230 ad-do-it
231 (unless py-shell-initial-switch-buffers
232 (switch-to-buffer-other-window buf)))))
233 (ad-activate 'py-shell)
234 ;; (defadvice py-execute-region (before py-execute-buffer-ensure-process)
235 ;; "HACK: test that ipython is already running before executing something.
236 ;; Doing this properly seems not worth the bother (unless people actually
237 ;; request it)."
238 ;; (unless (comint-check-proc "*Python*")
239 ;; (error "Sorry you have to first do M-x py-shell to send something to ipython.")))
240 ;; (ad-activate 'py-execute-region)
241
242 (defadvice py-execute-region (around py-execute-buffer-ensure-process)
243 "HACK: if `py-shell' is not active or ASYNC is explicitly desired, fall back
244 to python instead of ipython."
245 (let ((py-python-command (if (and (comint-check-proc "*Python*") (not async))
246 py-python-command
247 ipython-backup-of-py-python-command)))
248 ad-do-it))
249 (ad-activate 'py-execute-region)
250
251 (defun ipython-to-doctest (start end)
252 "Transform a cut-and-pasted bit from an IPython session into something that
253 looks like it came from a normal interactive python session, so that it can
254 be used in doctests. Example:
255
256
257 In [1]: import sys
258
259 In [2]: sys.stdout.write 'Hi!\n'
260 ------> sys.stdout.write ('Hi!\n')
261 Hi!
262
263 In [3]: 3 + 4
264 Out[3]: 7
265
266 gets converted to:
267
268 >>> import sys
269 >>> sys.stdout.write ('Hi!\n')
270 Hi!
271 >>> 3 + 4
272 7
273
274 "
275 (interactive "*r\n")
276 ;(message (format "###DEBUG s:%de:%d" start end))
277 (save-excursion
278 (save-match-data
279 ;; replace ``In [3]: bla`` with ``>>> bla`` and
280 ;; ``... : bla`` with ``... bla``
281 (goto-char start)
282 (while (re-search-forward ipython-de-input-prompt-regexp end t)
283 ;(message "finding 1")
284 (cond ((match-string 3) ;continued
285 (replace-match "... \\3" t nil))
286 (t
287 (replace-match ">>> \\1\\2" t nil))))
288 ;; replace ``
289 (goto-char start)
290 (while (re-search-forward ipython-de-output-prompt-regexp end t)
291 (replace-match "" t nil)))))
292
293 (defvar ipython-completion-command-string
294 "print ';'.join(__IP.Completer.all_completions('%s')) #PYTHON-MODE SILENT\n"
295 "The string send to ipython to query for all possible completions")
296
297
298 ;; xemacs doesn't have `comint-preoutput-filter-functions' so we'll try the
299 ;; following wonderful hack to work around this case
300 (if (featurep 'xemacs)
301 ;;xemacs
302 (defun ipython-complete ()
303 "Try to complete the python symbol before point. Only knows about the stuff
304 in the current *Python* session."
305 (interactive)
306 (let* ((ugly-return nil)
307 (sep ";")
308 ;; XXX currently we go backwards to find the beginning of an
309 ;; expression part; a more powerful approach in the future might be
310 ;; to let ipython have the complete line, so that context can be used
311 ;; to do things like filename completion etc.
312 (beg (save-excursion (skip-chars-backward "a-z0-9A-Z_." (point-at-bol))
313 (point)))
314 (end (point))
315 (pattern (buffer-substring-no-properties beg end))
316 (completions nil)
317 (completion-table nil)
318 completion
319 (comint-output-filter-functions
320 (append comint-output-filter-functions
321 '(ansi-color-filter-apply
322 (lambda (string)
323 ;(message (format "DEBUG filtering: %s" string))
324 (setq ugly-return (concat ugly-return string))
325 (delete-region comint-last-output-start
326 (process-mark (get-buffer-process (current-buffer)))))))))
327 ;(message (format "#DEBUG pattern: '%s'" pattern))
328 (process-send-string (or (get-buffer-process (current-buffer))
329 (get-process py-which-bufname)) ;XXX hack for .py buffers
330 (format ipython-completion-command-string pattern))
331 (accept-process-output (get-buffer-process (current-buffer)))
332 ;(message (format "DEBUG return: %s" ugly-return))
333 (setq completions
334 (split-string (substring ugly-return 0 (position ?\n ugly-return)) sep))
335 (setq completion-table (loop for str in completions
336 collect (list str nil)))
337 (setq completion (try-completion pattern completion-table))
338 (cond ((eq completion t))
339 ((null completion)
340 (message "Can't find completion for \"%s\"" pattern)
341 (ding))
342 ((not (string= pattern completion))
343 (delete-region beg end)
344 (insert completion))
345 (t
346 (message "Making completion list...")
347 (with-output-to-temp-buffer "*Python Completions*"
348 (display-completion-list (all-completions pattern completion-table)))
349 (message "Making completion list...%s" "done")))))
350 ;; emacs
351 (defun ipython-complete ()
352 "Try to complete the python symbol before point. Only knows about the stuff
353 in the current *Python* session."
354 (interactive)
355 (let* ((ugly-return nil)
356 (sep ";")
357 ;; XXX currently we go backwards to find the beginning of an
358 ;; expression part; a more powerful approach in the future might be
359 ;; to let ipython have the complete line, so that context can be used
360 ;; to do things like filename completion etc.
361 (beg (save-excursion (skip-chars-backward "a-z0-9A-Z_." (point-at-bol))
362 (point)))
363 (end (point))
364 (pattern (buffer-substring-no-properties beg end))
365 (completions nil)
366 (completion-table nil)
367 completion
368 (comint-preoutput-filter-functions
369 (append comint-preoutput-filter-functions
370 '(ansi-color-filter-apply
371 (lambda (string)
372 (setq ugly-return (concat ugly-return string))
373 "")))))
374 (process-send-string (or (get-buffer-process (current-buffer))
375 (get-process py-which-bufname)) ;XXX hack for .py buffers
376 (format ipython-completion-command-string pattern))
377 (accept-process-output (get-buffer-process (current-buffer)))
378 (setq completions
379 (split-string (substring ugly-return 0 (position ?\n ugly-return)) sep))
380 ;(message (format "DEBUG completions: %S" completions))
381 (setq completion-table (loop for str in completions
382 collect (list str nil)))
383 (setq completion (try-completion pattern completion-table))
384 (cond ((eq completion t))
385 ((null completion)
386 (message "Can't find completion for \"%s\"" pattern)
387 (ding))
388 ((not (string= pattern completion))
389 (delete-region beg end)
390 (insert completion))
391 (t
392 (message "Making completion list...")
393 (with-output-to-temp-buffer "*IPython Completions*"
394 (display-completion-list (all-completions pattern completion-table)))
395 (message "Making completion list...%s" "done")))))
396 )
397
398 (provide 'ipython)
This diff has been collapsed as it changes many lines, (8777 lines changed) Show them Hide them
@@ -0,0 +1,8777 b''
1 #LyX 1.3 created this file. For more info see http://www.lyx.org/
2 \lyxformat 221
3 \textclass article
4 \begin_preamble
5 \usepackage{ae,aecompl}
6 \usepackage{hyperref}
7 \usepackage{html}
8 \end_preamble
9 \language english
10 \inputencoding latin1
11 \fontscheme default
12 \graphics default
13 \paperfontsize default
14 \spacing single
15 \papersize Default
16 \paperpackage a4
17 \use_geometry 1
18 \use_amsmath 0
19 \use_natbib 0
20 \use_numerical_citations 0
21 \paperorientation portrait
22 \leftmargin 1.25in
23 \topmargin 1in
24 \rightmargin 1.25in
25 \bottommargin 1in
26 \secnumdepth 3
27 \tocdepth 3
28 \paragraph_separation skip
29 \defskip medskip
30 \quotes_language english
31 \quotes_times 2
32 \papercolumns 1
33 \papersides 1
34 \paperpagestyle fancy
35
36 \layout Title
37
38 IPython
39 \newline
40
41 \size larger
42 An enhanced Interactive Python
43 \size large
44
45 \newline
46 User Manual, v.
47 __version__
48 \layout Author
49
50 Fernando P�rez
51 \layout Standard
52
53
54 \begin_inset ERT
55 status Collapsed
56
57 \layout Standard
58
59 \backslash
60 latex{
61 \end_inset
62
63
64 \begin_inset LatexCommand \tableofcontents{}
65
66 \end_inset
67
68
69 \begin_inset ERT
70 status Collapsed
71
72 \layout Standard
73 }
74 \end_inset
75
76
77 \layout Standard
78
79
80 \begin_inset ERT
81 status Open
82
83 \layout Standard
84
85 \backslash
86 html{
87 \backslash
88 bodytext{bgcolor=#ffffff}}
89 \end_inset
90
91
92 \layout Section
93 \pagebreak_top
94 Overview
95 \layout Standard
96
97 One of Python's most useful features is its interactive interpreter.
98 This system allows very fast testing of ideas without the overhead of creating
99 test files as is typical in most programming languages.
100 However, the interpreter supplied with the standard Python distribution
101 is somewhat limited for extended interactive use.
102 \layout Standard
103
104 IPython is a free software project (released under the BSD license) which
105 tries to:
106 \layout Enumerate
107
108 Provide an interactive shell superior to Python's default.
109 IPython has many features for object introspection, system shell access,
110 and its own special command system for adding functionality when working
111 interactively.
112 It tries to be a very efficient environment both for Python code development
113 and for exploration of problems using Python objects (in situations like
114 data analysis).
115 \layout Enumerate
116
117 Serve as an embeddable, ready to use interpreter for your own programs.
118 IPython can be started with a single call from inside another program,
119 providing access to the current namespace.
120 This can be very useful both for debugging purposes and for situations
121 where a blend of batch-processing and interactive exploration are needed.
122 \layout Enumerate
123
124 Offer a flexible framework which can be used as the base environment for
125 other systems with Python as the underlying language.
126 Specifically scientific environments like Mathematica, IDL and Matlab inspired
127 its design, but similar ideas can be useful in many fields.
128 \layout Subsection
129
130 Main features
131 \layout Itemize
132
133 Dynamic object introspection.
134 One can access docstrings, function definition prototypes, source code,
135 source files and other details of any object accessible to the interpreter
136 with a single keystroke (`
137 \family typewriter
138 ?
139 \family default
140 ').
141 \layout Itemize
142
143 Completion in the local namespace, by typing TAB at the prompt.
144 This works for keywords, methods, variables and files in the current directory.
145 This is supported via the readline library, and full access to configuring
146 readline's behavior is provided.
147 \layout Itemize
148
149 Numbered input/output prompts with command history (persistent across sessions
150 and tied to each profile), full searching in this history and caching of
151 all input and output.
152 \layout Itemize
153
154 User-extensible `magic' commands.
155 A set of commands prefixed with
156 \family typewriter
157 %
158 \family default
159 is available for controlling IPython itself and provides directory control,
160 namespace information and many aliases to common system shell commands.
161 \layout Itemize
162
163 Alias facility for defining your own system aliases.
164 \layout Itemize
165
166 Complete system shell access.
167 Lines starting with ! are passed directly to the system shell, and using
168 !! captures shell output into python variables for further use.
169 \layout Itemize
170
171 All calls to the system (via aliases or via !) have their standard output/error
172 automatically stored as strings, and also available as lists.
173 \layout Itemize
174
175 Background execution of Python commands in a separate thread.
176 IPython has an internal job manager called
177 \family typewriter
178 jobs
179 \family default
180 , and a conveninence backgrounding magic function called
181 \family typewriter
182 %bg
183 \family default
184 .
185 \layout Itemize
186
187 The ability to expand python variables when calling the system shell.
188 In a shell command, any python variable prefixed with
189 \family typewriter
190 $
191 \family default
192 is expanded.
193 A double
194 \family typewriter
195 $$
196 \family default
197 allows passing a literal
198 \family typewriter
199 $
200 \family default
201 to the shell (for access to shell and environment variables like
202 \family typewriter
203 $PATH
204 \family default
205 ).
206 \layout Itemize
207
208 Filesystem navigation, via a magic
209 \family typewriter
210 %cd
211 \family default
212 command, along with a persistent bookmark system (using
213 \family typewriter
214 %bookmark
215 \family default
216 ) for fast access to frequently visited directories.
217 \layout Itemize
218
219 Automatic indentation (optional) of code as you type (through the readline
220 library).
221 \layout Itemize
222
223 Macro system for quickly re-executing multiple lines of previous input with
224 a single name.
225 \layout Itemize
226
227 Session logging (you can then later use these logs as code in your programs).
228 \layout Itemize
229
230 Session restoring: logs can be replayed to restore a previous session to
231 the state where you left it.
232 \layout Itemize
233
234 Verbose and colored exception traceback printouts.
235 Easier to parse visually, and in verbose mode they produce a lot of useful
236 debugging information (basically a terminal version of the cgitb module).
237 \layout Itemize
238
239 Auto-parentheses: callable objects can be executed without parentheses:
240
241 \family typewriter
242 `sin 3'
243 \family default
244 is automatically converted to
245 \family typewriter
246 `sin(3)
247 \family default
248 '.
249 \layout Itemize
250
251 Auto-quoting: using `
252 \family typewriter
253 ,
254 \family default
255 ' or `
256 \family typewriter
257 ;
258 \family default
259 ' as the first character forces auto-quoting of the rest of the line:
260 \family typewriter
261 `,my_function a\SpecialChar ~
262 b'
263 \family default
264 becomes automatically
265 \family typewriter
266 `my_function("a","b")'
267 \family default
268 , while
269 \family typewriter
270 `;my_function a\SpecialChar ~
271 b'
272 \family default
273 becomes
274 \family typewriter
275 `my_function("a b")'
276 \family default
277 .
278 \layout Itemize
279
280 Extensible input syntax.
281 You can define filters that pre-process user input to simplify input in
282 special situations.
283 This allows for example pasting multi-line code fragments which start with
284
285 \family typewriter
286 `>>>'
287 \family default
288 or
289 \family typewriter
290 `...'
291 \family default
292 such as those from other python sessions or the standard Python documentation.
293 \layout Itemize
294
295 Flexible configuration system.
296 It uses a configuration file which allows permanent setting of all command-line
297 options, module loading, code and file execution.
298 The system allows recursive file inclusion, so you can have a base file
299 with defaults and layers which load other customizations for particular
300 projects.
301 \layout Itemize
302
303 Embeddable.
304 You can call IPython as a python shell inside your own python programs.
305 This can be used both for debugging code or for providing interactive abilities
306 to your programs with knowledge about the local namespaces (very useful
307 in debugging and data analysis situations).
308 \layout Itemize
309
310 Easy debugger access.
311 You can set IPython to call up the Python debugger (pdb) every time there
312 is an uncaught exception.
313 This drops you inside the code which triggered the exception with all the
314 data live and it is possible to navigate the stack to rapidly isolate the
315 source of a bug.
316 The
317 \family typewriter
318 %run
319 \family default
320 magic command --with the
321 \family typewriter
322 -d
323 \family default
324 option-- can run any script under
325 \family typewriter
326 pdb
327 \family default
328 's control, automatically setting initial breakpoints for you.
329 \layout Itemize
330
331 Profiler support.
332 You can run single statements (similar to
333 \family typewriter
334 profile.run()
335 \family default
336 ) or complete programs under the profiler's control.
337 While this is possible with the standard
338 \family typewriter
339 profile
340 \family default
341 module, IPython wraps this functionality with magic commands (see
342 \family typewriter
343 `%prun'
344 \family default
345 and
346 \family typewriter
347 `%run -p
348 \family default
349 ') convenient for rapid interactive work.
350 \layout Subsection
351
352 Portability and Python requirements
353 \layout Standard
354
355
356 \series bold
357 Python requirements:
358 \series default
359 IPython works with Python version 2.2 or newer.
360 It has been tested with Python 2.4 and no problems have been reported.
361 Support for Python 2.1 hasn't been recently tested, since I don't have access
362 to it on any of my systems.
363 But I suspect there may be some problems with Python 2.1, because some of
364 the newer code may use 2.2 features.
365 \layout Standard
366
367 IPython is developed under
368 \series bold
369 Linux
370 \series default
371 , but it should work in any reasonable Unix-type system (tested OK under
372 Solaris and the *BSD family, for which a port exists thanks to Dryice Liu).
373 \layout Standard
374
375
376 \series bold
377 Mac OS X
378 \series default
379 : it works, apparently without any problems (thanks to Jim Boyle at Lawrence
380 Livermore for the information).
381 Thanks to Andrea Riciputi, Fink support is available.
382 \layout Standard
383
384
385 \series bold
386 CygWin
387 \series default
388 : it works mostly OK, though some users have reported problems with prompt
389 coloring.
390 No satisfactory solution to this has been found so far, you may want to
391 disable colors permanently in the
392 \family typewriter
393 ipythonrc
394 \family default
395 configuration file if you experience problems.
396 If you have proper color support under cygwin, please post to the IPython
397 mailing list so this issue can be resolved for all users.
398 \layout Standard
399
400
401 \series bold
402 Windows
403 \series default
404 : it works well under Windows XP/2k, and I suspect NT should behave similarly.
405 Section\SpecialChar ~
406
407 \begin_inset LatexCommand \ref{sub:Under-Windows}
408
409 \end_inset
410
411 describes installation details for Windows, including some additional tools
412 needed on this platform.
413 \layout Standard
414
415 Windows 9x support is present, and has been reported to work fine (at least
416 on WinME).
417 \layout Standard
418
419 Please note, however, that I have very little access to and experience with
420 Windows development.
421 For this reason, Windows-specific bugs tend to linger far longer than I
422 would like, and often I just can't find a satisfactory solution.
423 If any Windows user wants to join in with development help, all hands are
424 always welcome.
425 \layout Subsection
426
427 Location
428 \layout Standard
429
430 IPython is generously hosted at
431 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
432
433 \end_inset
434
435 by the SciPy project.
436 This site offers downloads, CVS access, mailing lists and a bug tracking
437 system.
438 I am very grateful to Enthought (
439 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
440
441 \end_inset
442
443 ) and all of the SciPy team for their contribution.
444 \layout Section
445
446
447 \begin_inset LatexCommand \label{sec:install}
448
449 \end_inset
450
451 Installation
452 \layout Subsection
453
454 Instant instructions
455 \layout Standard
456
457 If you are of the impatient kind, under Linux/Unix simply untar/unzip the
458 download, then install with
459 \family typewriter
460 `python setup.py install'
461 \family default
462 .
463 Under Windows, double-click on the provided
464 \family typewriter
465 .exe
466 \family default
467 binary installer.
468 \layout Standard
469
470 Then, take a look at Sections
471 \begin_inset LatexCommand \ref{sec:good_config}
472
473 \end_inset
474
475 for configuring things optimally and
476 \begin_inset LatexCommand \ref{sec:quick_tips}
477
478 \end_inset
479
480 for quick tips on efficient use of IPython.
481 You can later refer to the rest of the manual for all the gory details.
482 \layout Standard
483
484 See the notes in sec.
485
486 \begin_inset LatexCommand \ref{sec:upgrade}
487
488 \end_inset
489
490 for upgrading IPython versions.
491 \layout Subsection
492
493 Detailed Unix instructions (Linux, Mac OS X, etc.)
494 \layout Standard
495
496
497 \begin_inset ERT
498 status Open
499
500 \layout Standard
501
502 \backslash
503 html{
504 \backslash
505 textbf{A warning to readers of the HTML version of this manual}: all options below are preceded with with TWO dashes and no intervening space between the dashes (e.g. Dash-Dash-home). The default HTML conversion tools mangle these into a single dash.}
506 \end_inset
507
508
509 \layout Standard
510
511 For RPM based systems, simply install the supplied package in the usual
512 manner.
513 If you download the tar archive, the process is:
514 \layout Enumerate
515
516 Unzip/untar the
517 \family typewriter
518 ipython-XXX.tar.gz
519 \family default
520 file wherever you want (
521 \family typewriter
522 XXX
523 \family default
524 is the version number).
525 It will make a directory called
526 \family typewriter
527 ipython-XXX.
528
529 \family default
530 Change into that directory where you will find the files
531 \family typewriter
532 README
533 \family default
534 and
535 \family typewriter
536 setup.py
537 \family default
538 .
539
540 \family typewriter
541 O
542 \family default
543 nce you've completed the installation, you can safely remove this directory.
544
545 \layout Enumerate
546
547 If you are installing over a previous installation of version 0.2.0 or earlier,
548 first remove your
549 \family typewriter
550 $HOME/.ipython
551 \family default
552 directory, since the configuration file format has changed somewhat (the
553 '=' were removed from all option specifications).
554 Or you can call ipython with the
555 \family typewriter
556 -upgrade
557 \family default
558 option and it will do this automatically for you.
559 \layout Enumerate
560
561 IPython uses distutils, so you can install it by simply typing at the system
562 prompt (don't type the
563 \family typewriter
564 $
565 \family default
566 )
567 \newline
568
569 \family typewriter
570 $ python setup.py install
571 \family default
572
573 \newline
574 Note that this assumes you have root access to your machine.
575 If you don't have root access or don't want IPython to go in the default
576 python directories, you'll need to use the
577 \family typewriter
578 --home
579 \family default
580 option (or
581 \family typewriter
582 --prefix
583 \family default
584 ).
585 For example:
586 \newline
587
588 \family typewriter
589 $ python setup.py install --home $HOME/local
590 \family default
591
592 \newline
593 will install
594 \begin_inset Foot
595 collapsed true
596
597 \layout Standard
598
599 If you are reading these instructions in HTML format, please note that the
600 option is --home, with
601 \emph on
602 two
603 \emph default
604 dashes.
605 The automatic HTML conversion program seems to eat up one of the dashes,
606 unfortunately (it's ok in the PDF version).
607 \end_inset
608
609 IPython into
610 \family typewriter
611 $HOME/local
612 \family default
613 and its subdirectories (creating them if necessary).
614 \newline
615 You can type
616 \newline
617
618 \family typewriter
619 $ python setup.py --help
620 \family default
621
622 \newline
623 for more details.
624 \newline
625 Note that if you change the default location for
626 \family typewriter
627 --home
628 \family default
629 at installation, IPython may end up installed at a location which is not
630 part of your
631 \family typewriter
632 $PYTHONPATH
633 \family default
634 environment variable.
635 In this case, you'll need to configure this variable to include the actual
636 directory where the
637 \family typewriter
638 IPython/
639 \family default
640 directory ended (typically the value you give to
641 \family typewriter
642 --home
643 \family default
644 plus
645 \family typewriter
646 /lib/python
647 \family default
648 ).
649 \layout Subsubsection
650
651 Mac OSX information
652 \layout Subsubsection*
653
654 GUI problems
655 \layout Standard
656
657 The following instructions apply to an install of IPython under OSX from
658 unpacking the
659 \family typewriter
660 .tar.gz
661 \family default
662 distribution and installing it for the default Python interpreter shipped
663 by Apple.
664 If you are using a fink install, fink will take care of these details for
665 you, by installing IPython against fink's Python.
666 \layout Standard
667
668 IPython offers various forms of support for interacting with graphical applicati
669 ons from the command line, from simple Tk apps (which are in principle always
670 supported by Python) to interactive control of WX, QT and GTK apps.
671 Under OSX, however, this requires that ipython is installed by calling
672 the special
673 \family typewriter
674 pythonw
675 \family default
676 script at installation time, which takes care of coordinating things with
677 Apple's graphical environment.
678 \layout Standard
679
680 So when installing under OSX, it is best to use the following command
681 \begin_inset ERT
682 status Collapsed
683
684 \layout Standard
685
686 \backslash
687 html{
688 \backslash
689 emph{[Again, in the HTML manual, the option is called -~-install=scripts, with TWO dashes and no intervening space between the dashes]}}
690 \end_inset
691
692 :
693 \family typewriter
694
695 \newline
696 \SpecialChar ~
697 \SpecialChar ~
698 $ sudo pythonw setup.py install --install-scripts=/usr/local/bin
699 \family default
700
701 \newline
702 or
703 \family typewriter
704
705 \newline
706 \SpecialChar ~
707 \SpecialChar ~
708 $ sudo pythonw setup.py install --install-scripts=/usr/bin
709 \newline
710
711 \family default
712 depending on where you like to keep hand-installed executables.
713 \layout Standard
714
715 The resulting script will have an appropriate shebang line (the first line
716 in the script whic begins with
717 \family typewriter
718 #!...
719 \family default
720 ) such that the ipython interpreter can interact with the OS X GUI.
721 If the installed version does not work and has a shebang line that points
722 to, for example, just
723 \family typewriter
724 /usr/bin/python
725 \family default
726 , then you might have a stale, cached version in your
727 \family typewriter
728 build/scripts-<python-version>
729 \family default
730 directory.
731 Delete that directory and rerun the
732 \family typewriter
733 setup.py
734 \family default
735 .
736
737 \layout Standard
738
739 It is also a good idea to use the special flag
740 \family typewriter
741 --install-scripts
742 \family default
743 as indicated above, to ensure that the ipython scripts end up in a location
744 which is part of your
745 \family typewriter
746 $PATH
747 \family default
748 .
749 Otherwise Apple's Python will put the scripts in an internal directory
750 not available by default at the command line (if you use
751 \family typewriter
752 /usr/local/bin
753 \family default
754 , you need to make sure this is in your
755 \family typewriter
756 $PATH
757 \family default
758 , which may not be true by default).
759 \layout Subsubsection*
760
761 Readline problems
762 \layout Standard
763
764 By default, the Python version shipped by Apple does
765 \emph on
766 not
767 \emph default
768 include the readline library, so central to IPython's behavior.
769 If you install IPython against Apple's Python, you will not have arrow
770 keys, tab completion, etc.
771 For Mac OSX 10.3 (Panther), you can find a prebuilt readline library here:
772 \newline
773
774 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip}
775
776 \end_inset
777
778
779 \layout Standard
780
781 At this point I don't know of such a released version for OSX 10.4 (Tiger),
782 or if the problem even occurs with Tiger at all (feedback welcome).
783 \layout Standard
784
785 Users installing against fink's Python or a properly hand-built one should
786 not have this problem.
787 \layout Subsection
788
789
790 \begin_inset LatexCommand \label{sub:Under-Windows}
791
792 \end_inset
793
794 Windows instructions
795 \layout Standard
796
797 While you can use IPython under Windows with only a stock Python installation,
798 there is one extension,
799 \family typewriter
800 readline
801 \family default
802 , which will make the whole experience a lot more pleasant.
803 It is almost a requirement, since IPython will complain in its absence
804 (though it will function).
805
806 \layout Standard
807
808 The
809 \family typewriter
810 readline
811 \family default
812 extension needs two other libraries to work, so in all you need:
813 \layout Enumerate
814
815
816 \family typewriter
817 PyWin32
818 \family default
819 from
820 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
821
822 \end_inset
823
824 .
825 \layout Enumerate
826
827
828 \family typewriter
829 CTypes
830 \family default
831 from
832 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
833
834 \end_inset
835
836 (you
837 \emph on
838 must
839 \emph default
840 use version 0.9.1 or newer).
841 \layout Enumerate
842
843
844 \family typewriter
845 Readline
846 \family default
847 for Windows from
848 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
849
850 \end_inset
851
852 .
853 \layout Standard
854
855
856 \series bold
857 Warning about a broken readline-like library:
858 \series default
859 several users have reported problems stemming from using the pseudo-readline
860 library at
861 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
862
863 \end_inset
864
865 .
866 This is a broken library which, while called readline, only implements
867 an incomplete subset of the readline API.
868 Since it is still called readline, it fools IPython's detection mechanisms
869 and causes unpredictable crashes later.
870 If you wish to use IPython under Windows, you must NOT use this library,
871 which for all purposes is (at least as of version 1.6) terminally broken.
872 \layout Subsubsection
873
874 Gary Bishop's readline and color support for Windows
875 \layout Standard
876
877 Some of IPython's very useful features are:
878 \layout Itemize
879
880 Integrated readline support (Tab-based file, object and attribute completion,
881 input history across sessions, editable command line, etc.)
882 \layout Itemize
883
884 Coloring of prompts, code and tracebacks.
885 \layout Standard
886
887 These, by default, are only available under Unix-like operating systems.
888 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
889 from them.
890 His readline library implements both GNU readline functionality and color
891 support, so that IPython under Windows XP/2k can be as friendly and powerful
892 as under Unix-like environments.
893 \layout Standard
894
895 You can find Gary's tools at
896 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
897
898 \end_inset
899
900 ; Gary's
901 \family typewriter
902 readline
903 \family default
904 requires in turn the
905 \family typewriter
906 ctypes
907 \family default
908 library by Thomas Heller, available at
909 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
910
911 \end_inset
912
913 , and Mark Hammond's
914 \family typewriter
915 PyWin32
916 \family default
917 from
918 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
919
920 \end_inset
921
922 (
923 \family typewriter
924 PyWin32
925 \family default
926 is great for anything Windows-related anyway, so you might as well get
927 it).
928 \layout Standard
929
930 Under MS\SpecialChar ~
931 Windows, IPython will complain if it can not find this
932 \family typewriter
933 readline
934 \family default
935 library at startup and any time the
936 \family typewriter
937 %colors
938 \family default
939 command is issued, so you can consider it to be a quasi-requirement.
940 \layout Subsubsection
941
942 Installation procedure
943 \layout Standard
944
945 Once you have the above installed, from the IPython download directory grab
946 the
947 \family typewriter
948 ipython-XXX.win32.exe
949 \family default
950 file, where
951 \family typewriter
952 XXX
953 \family default
954 represents the version number.
955 This is a regular windows executable installer, which you can simply double-cli
956 ck to install.
957 It will add an entry for IPython to your Start Menu, as well as registering
958 IPython in the Windows list of applications, so you can later uninstall
959 it from the Control Panel.
960
961 \layout Standard
962
963 IPython tries to install the configuration information in a directory named
964
965 \family typewriter
966 .ipython
967 \family default
968 (
969 \family typewriter
970 _ipython
971 \family default
972 under Windows) located in your `home' directory.
973 IPython sets this directory by looking for a
974 \family typewriter
975 HOME
976 \family default
977 environment variable; if such a variable does not exist, it uses
978 \family typewriter
979 HOMEDRIVE
980 \backslash
981 HOMEPATH
982 \family default
983 (these are always defined by Windows).
984 This typically gives something like
985 \family typewriter
986 C:
987 \backslash
988 Documents and Settings
989 \backslash
990 YourUserName
991 \family default
992 , but your local details may vary.
993 In this directory you will find all the files that configure IPython's
994 defaults, and you can put there your profiles and extensions.
995 This directory is automatically added by IPython to
996 \family typewriter
997 sys.path
998 \family default
999 , so anything you place there can be found by
1000 \family typewriter
1001 import
1002 \family default
1003 statements.
1004 \layout Paragraph
1005
1006 Upgrading
1007 \layout Standard
1008
1009 For an IPython upgrade, you should first uninstall the previous version.
1010 This will ensure that all files and directories (such as the documentation)
1011 which carry embedded version strings in their names are properly removed.
1012 \layout Paragraph
1013
1014 Manual installation under Win32
1015 \layout Standard
1016
1017 In case the automatic installer does not work for some reason, you can download
1018 the
1019 \family typewriter
1020 ipython-XXX.tar.gz
1021 \family default
1022 file, which contains the full IPython source distribution (the popular
1023 WinZip can read
1024 \family typewriter
1025 .tar.gz
1026 \family default
1027 files).
1028 After uncompressing the archive, you can install it at a command terminal
1029 just like any other Python module, by using
1030 \family typewriter
1031 `python setup.py install'
1032 \family default
1033 .
1034
1035 \layout Standard
1036
1037 After the installation, run the supplied
1038 \family typewriter
1039 win32_manual_post_install.py
1040 \family default
1041 script, which creates the necessary Start Menu shortcuts for you.
1042 \layout Subsection
1043
1044
1045 \begin_inset LatexCommand \label{sec:upgrade}
1046
1047 \end_inset
1048
1049 Upgrading from a previous version
1050 \layout Standard
1051
1052 If you are upgrading from a previous version of IPython, after doing the
1053 routine installation described above, you should call IPython with the
1054
1055 \family typewriter
1056 -upgrade
1057 \family default
1058 option the first time you run your new copy.
1059 This will automatically update your configuration directory while preserving
1060 copies of your old files.
1061 You can then later merge back any personal customizations you may have
1062 made into the new files.
1063 It is a good idea to do this as there may be new options available in the
1064 new configuration files which you will not have.
1065 \layout Standard
1066
1067 Under Windows, if you don't know how to call python scripts with arguments
1068 from a command line, simply delete the old config directory and IPython
1069 will make a new one.
1070 Win2k and WinXP users will find it in
1071 \family typewriter
1072 C:
1073 \backslash
1074 Documents and Settings
1075 \backslash
1076 YourUserName
1077 \backslash
1078 .ipython
1079 \family default
1080 , and Win 9x users under
1081 \family typewriter
1082 C:
1083 \backslash
1084 Program Files
1085 \backslash
1086 IPython
1087 \backslash
1088 .ipython.
1089 \layout Section
1090
1091
1092 \begin_inset LatexCommand \label{sec:good_config}
1093
1094 \end_inset
1095
1096
1097 \begin_inset OptArg
1098 collapsed true
1099
1100 \layout Standard
1101
1102 Initial configuration
1103 \begin_inset ERT
1104 status Collapsed
1105
1106 \layout Standard
1107
1108 \backslash
1109 ldots
1110 \end_inset
1111
1112
1113 \end_inset
1114
1115 Initial configuration of your environment
1116 \layout Standard
1117
1118 This section will help you set various things in your environment for your
1119 IPython sessions to be as efficient as possible.
1120 All of IPython's configuration information, along with several example
1121 files, is stored in a directory named by default
1122 \family typewriter
1123 $HOME/.ipython
1124 \family default
1125 .
1126 You can change this by defining the environment variable
1127 \family typewriter
1128 IPYTHONDIR
1129 \family default
1130 , or at runtime with the command line option
1131 \family typewriter
1132 -ipythondir
1133 \family default
1134 .
1135 \layout Standard
1136
1137 If all goes well, the first time you run IPython it should automatically
1138 create a user copy of the config directory for you, based on its builtin
1139 defaults.
1140 You can look at the files it creates to learn more about configuring the
1141 system.
1142 The main file you will modify to configure IPython's behavior is called
1143
1144 \family typewriter
1145 ipythonrc
1146 \family default
1147 (with a
1148 \family typewriter
1149 .ini
1150 \family default
1151 extension under Windows), included for reference in Sec.
1152
1153 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1154
1155 \end_inset
1156
1157 .
1158 This file is very commented and has many variables you can change to suit
1159 your taste, you can find more details in Sec.
1160
1161 \begin_inset LatexCommand \ref{sec:customization}
1162
1163 \end_inset
1164
1165 .
1166 Here we discuss the basic things you will want to make sure things are
1167 working properly from the beginning.
1168 \layout Subsection
1169
1170
1171 \begin_inset LatexCommand \label{sec:help-access}
1172
1173 \end_inset
1174
1175 Access to the Python help system
1176 \layout Standard
1177
1178 This is true for Python in general (not just for IPython): you should have
1179 an environment variable called
1180 \family typewriter
1181 PYTHONDOCS
1182 \family default
1183 pointing to the directory where your HTML Python documentation lives.
1184 In my system it's
1185 \family typewriter
1186 /usr/share/doc/python-docs-2.3.4/html
1187 \family default
1188 , check your local details or ask your systems administrator.
1189
1190 \layout Standard
1191
1192 This is the directory which holds the HTML version of the Python manuals.
1193 Unfortunately it seems that different Linux distributions package these
1194 files differently, so you may have to look around a bit.
1195 Below I show the contents of this directory on my system for reference:
1196 \layout Standard
1197
1198
1199 \family typewriter
1200 [html]> ls
1201 \newline
1202 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1203 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1204 \layout Standard
1205
1206 You should really make sure this variable is correctly set so that Python's
1207 pydoc-based help system works.
1208 It is a powerful and convenient system with full access to the Python manuals
1209 and all modules accessible to you.
1210 \layout Standard
1211
1212 Under Windows it seems that pydoc finds the documentation automatically,
1213 so no extra setup appears necessary.
1214 \layout Subsection
1215
1216 Editor
1217 \layout Standard
1218
1219 The
1220 \family typewriter
1221 %edit
1222 \family default
1223 command (and its alias
1224 \family typewriter
1225 %ed
1226 \family default
1227 ) will invoke the editor set in your environment as
1228 \family typewriter
1229 EDITOR
1230 \family default
1231 .
1232 If this variable is not set, it will default to
1233 \family typewriter
1234 vi
1235 \family default
1236 under Linux/Unix and to
1237 \family typewriter
1238 notepad
1239 \family default
1240 under Windows.
1241 You may want to set this variable properly and to a lightweight editor
1242 which doesn't take too long to start (that is, something other than a new
1243 instance of
1244 \family typewriter
1245 Emacs
1246 \family default
1247 ).
1248 This way you can edit multi-line code quickly and with the power of a real
1249 editor right inside IPython.
1250
1251 \layout Standard
1252
1253 If you are a dedicated
1254 \family typewriter
1255 Emacs
1256 \family default
1257 user, you should set up the
1258 \family typewriter
1259 Emacs
1260 \family default
1261 server so that new requests are handled by the original process.
1262 This means that almost no time is spent in handling the request (assuming
1263 an
1264 \family typewriter
1265 Emacs
1266 \family default
1267 process is already running).
1268 For this to work, you need to set your
1269 \family typewriter
1270 EDITOR
1271 \family default
1272 environment variable to
1273 \family typewriter
1274 'emacsclient'
1275 \family default
1276 .
1277
1278 \family typewriter
1279
1280 \family default
1281 The code below, supplied by Francois Pinard, can then be used in your
1282 \family typewriter
1283 .emacs
1284 \family default
1285 file to enable the server:
1286 \layout Standard
1287
1288
1289 \family typewriter
1290 (defvar server-buffer-clients)
1291 \newline
1292 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1293 \newline
1294
1295 \begin_inset ERT
1296 status Collapsed
1297
1298 \layout Standard
1299
1300 \backslash
1301 hspace*{0mm}
1302 \end_inset
1303
1304 \SpecialChar ~
1305 \SpecialChar ~
1306 (server-start)
1307 \newline
1308
1309 \begin_inset ERT
1310 status Collapsed
1311
1312 \layout Standard
1313
1314 \backslash
1315 hspace*{0mm}
1316 \end_inset
1317
1318 \SpecialChar ~
1319 \SpecialChar ~
1320 (defun fp-kill-server-with-buffer-routine ()
1321 \newline
1322
1323 \begin_inset ERT
1324 status Collapsed
1325
1326 \layout Standard
1327
1328 \backslash
1329 hspace*{0mm}
1330 \end_inset
1331
1332 \SpecialChar ~
1333 \SpecialChar ~
1334 \SpecialChar ~
1335 \SpecialChar ~
1336 (and server-buffer-clients (server-done)))
1337 \newline
1338
1339 \begin_inset ERT
1340 status Collapsed
1341
1342 \layout Standard
1343
1344 \backslash
1345 hspace*{0mm}
1346 \end_inset
1347
1348 \SpecialChar ~
1349 \SpecialChar ~
1350 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1351 \layout Standard
1352
1353 You can also set the value of this editor via the commmand-line option '-
1354 \family typewriter
1355 editor'
1356 \family default
1357 or in your
1358 \family typewriter
1359 ipythonrc
1360 \family default
1361 file.
1362 This is useful if you wish to use specifically for IPython an editor different
1363 from your typical default (and for Windows users who tend to use fewer
1364 environment variables).
1365 \layout Subsection
1366
1367 Color
1368 \layout Standard
1369
1370 The default IPython configuration has most bells and whistles turned on
1371 (they're pretty safe).
1372 But there's one that
1373 \emph on
1374 may
1375 \emph default
1376 cause problems on some systems: the use of color on screen for displaying
1377 information.
1378 This is very useful, since IPython can show prompts and exception tracebacks
1379 with various colors, display syntax-highlighted source code, and in general
1380 make it easier to visually parse information.
1381 \layout Standard
1382
1383 The following terminals seem to handle the color sequences fine:
1384 \layout Itemize
1385
1386 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1387 \layout Itemize
1388
1389 CDE terminal (tested under Solaris).
1390 This one boldfaces light colors.
1391 \layout Itemize
1392
1393 (X)Emacs buffers.
1394 See sec.
1395 \begin_inset LatexCommand \ref{sec:emacs}
1396
1397 \end_inset
1398
1399 for more details on using IPython with (X)Emacs.
1400 \layout Itemize
1401
1402 A Windows (XP/2k) command prompt
1403 \emph on
1404 with Gary Bishop's support extensions
1405 \emph default
1406 .
1407 Gary's extensions are discussed in Sec.\SpecialChar ~
1408
1409 \begin_inset LatexCommand \ref{sub:Under-Windows}
1410
1411 \end_inset
1412
1413 .
1414 \layout Itemize
1415
1416 A Windows (XP/2k) CygWin shell.
1417 Although some users have reported problems; it is not clear whether there
1418 is an issue for everyone or only under specific configurations.
1419 If you have full color support under cygwin, please post to the IPython
1420 mailing list so this issue can be resolved for all users.
1421 \layout Standard
1422
1423 These have shown problems:
1424 \layout Itemize
1425
1426 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1427 or ssh.
1428 \layout Itemize
1429
1430 Windows native command prompt in WinXP/2k,
1431 \emph on
1432 without
1433 \emph default
1434 Gary Bishop's extensions.
1435 Once Gary's readline library is installed, the normal WinXP/2k command
1436 prompt works perfectly.
1437 \layout Standard
1438
1439 Currently the following color schemes are available:
1440 \layout Itemize
1441
1442
1443 \family typewriter
1444 NoColor
1445 \family default
1446 : uses no color escapes at all (all escapes are empty
1447 \begin_inset Quotes eld
1448 \end_inset
1449
1450
1451 \begin_inset Quotes eld
1452 \end_inset
1453
1454 strings).
1455 This 'scheme' is thus fully safe to use in any terminal.
1456 \layout Itemize
1457
1458
1459 \family typewriter
1460 Linux
1461 \family default
1462 : works well in Linux console type environments: dark background with light
1463 fonts.
1464 It uses bright colors for information, so it is difficult to read if you
1465 have a light colored background.
1466 \layout Itemize
1467
1468
1469 \family typewriter
1470 LightBG
1471 \family default
1472 : the basic colors are similar to those in the
1473 \family typewriter
1474 Linux
1475 \family default
1476 scheme but darker.
1477 It is easy to read in terminals with light backgrounds.
1478 \layout Standard
1479
1480 IPython uses colors for two main groups of things: prompts and tracebacks
1481 which are directly printed to the terminal, and the object introspection
1482 system which passes large sets of data through a pager.
1483 \layout Subsubsection
1484
1485 Input/Output prompts and exception tracebacks
1486 \layout Standard
1487
1488 You can test whether the colored prompts and tracebacks work on your system
1489 interactively by typing
1490 \family typewriter
1491 '%colors Linux'
1492 \family default
1493 at the prompt (use '
1494 \family typewriter
1495 %colors LightBG'
1496 \family default
1497 if your terminal has a light background).
1498 If the input prompt shows garbage like:
1499 \newline
1500
1501 \family typewriter
1502 [0;32mIn [[1;32m1[0;32m]: [0;00m
1503 \family default
1504
1505 \newline
1506 instead of (in color) something like:
1507 \newline
1508
1509 \family typewriter
1510 In [1]:
1511 \family default
1512
1513 \newline
1514 this means that your terminal doesn't properly handle color escape sequences.
1515 You can go to a 'no color' mode by typing '
1516 \family typewriter
1517 %colors NoColor
1518 \family default
1519 '.
1520
1521 \layout Standard
1522
1523 You can try using a different terminal emulator program.
1524 To permanently set your color preferences, edit the file
1525 \family typewriter
1526 $HOME/.ipython/ipythonrc
1527 \family default
1528 and set the
1529 \family typewriter
1530 colors
1531 \family default
1532 option to the desired value.
1533 \layout Subsubsection
1534
1535 Object details (types, docstrings, source code, etc.)
1536 \layout Standard
1537
1538 IPython has a set of special functions for studying the objects you are
1539 working with, discussed in detail in Sec.
1540
1541 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1542
1543 \end_inset
1544
1545 .
1546 But this system relies on passing information which is longer than your
1547 screen through a data pager, such as the common Unix
1548 \family typewriter
1549 less
1550 \family default
1551 and
1552 \family typewriter
1553 more
1554 \family default
1555 programs.
1556 In order to be able to see this information in color, your pager needs
1557 to be properly configured.
1558 I strongly recommend using
1559 \family typewriter
1560 less
1561 \family default
1562 instead of
1563 \family typewriter
1564 more
1565 \family default
1566 , as it seems that
1567 \family typewriter
1568 more
1569 \family default
1570 simply can not understand colored text correctly.
1571 \layout Standard
1572
1573 In order to configure
1574 \family typewriter
1575 less
1576 \family default
1577 as your default pager, do the following:
1578 \layout Enumerate
1579
1580 Set the environment
1581 \family typewriter
1582 PAGER
1583 \family default
1584 variable to
1585 \family typewriter
1586 less
1587 \family default
1588 .
1589 \layout Enumerate
1590
1591 Set the environment
1592 \family typewriter
1593 LESS
1594 \family default
1595 variable to
1596 \family typewriter
1597 -r
1598 \family default
1599 (plus any other options you always want to pass to
1600 \family typewriter
1601 less
1602 \family default
1603 by default).
1604 This tells
1605 \family typewriter
1606 less
1607 \family default
1608 to properly interpret control sequences, which is how color information
1609 is given to your terminal.
1610 \layout Standard
1611
1612 For the
1613 \family typewriter
1614 csh
1615 \family default
1616 or
1617 \family typewriter
1618 tcsh
1619 \family default
1620 shells, add to your
1621 \family typewriter
1622 ~/.cshrc
1623 \family default
1624 file the lines:
1625 \layout Standard
1626
1627
1628 \family typewriter
1629 setenv PAGER less
1630 \newline
1631 setenv LESS -r
1632 \layout Standard
1633
1634 There is similar syntax for other Unix shells, look at your system documentation
1635 for details.
1636 \layout Standard
1637
1638 If you are on a system which lacks proper data pagers (such as Windows),
1639 IPython will use a very limited builtin pager.
1640 \layout Subsection
1641
1642
1643 \begin_inset LatexCommand \label{sec:emacs}
1644
1645 \end_inset
1646
1647 (X)Emacs configuration
1648 \layout Standard
1649
1650 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1651 (X)Emacs and IPython get along very well.
1652
1653 \layout Standard
1654
1655
1656 \series bold
1657 Important note:
1658 \series default
1659 You will need to use a recent enough version of
1660 \family typewriter
1661 python-mode.el
1662 \family default
1663 , along with the file
1664 \family typewriter
1665 ipython.el
1666 \family default
1667 .
1668 You can check that the version you have of
1669 \family typewriter
1670 python-mode.el
1671 \family default
1672 is new enough by either looking at the revision number in the file itself,
1673 or asking for it in (X)Emacs via
1674 \family typewriter
1675 M-x py-version
1676 \family default
1677 .
1678 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1679 \layout Standard
1680
1681 The file
1682 \family typewriter
1683 ipython.el
1684 \family default
1685 is included with the IPython distribution, in the documentation directory
1686 (where this manual resides in PDF and HTML formats).
1687 \layout Standard
1688
1689 Once you put these files in your Emacs path, all you need in your
1690 \family typewriter
1691 .emacs
1692 \family default
1693 file is:
1694 \layout Standard
1695
1696
1697 \family typewriter
1698 (require 'ipython)
1699 \layout Standard
1700
1701 This should give you full support for executing code snippets via IPython,
1702 opening IPython as your Python shell via
1703 \family typewriter
1704 C-c\SpecialChar ~
1705 !
1706 \family default
1707 , etc.
1708
1709 \layout Subsubsection*
1710
1711 Notes
1712 \layout Itemize
1713
1714 There is one caveat you should be aware of: you must start the IPython shell
1715
1716 \emph on
1717 before
1718 \emph default
1719 attempting to execute any code regions via
1720 \family typewriter
1721 C-c\SpecialChar ~
1722 |
1723 \family default
1724 .
1725 Simply type
1726 \family typewriter
1727 C-c\SpecialChar ~
1728 !
1729 \family default
1730 to start IPython before passing any code regions to the interpreter, and
1731 you shouldn't experience any problems.
1732 \newline
1733 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1734 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1735 \layout Itemize
1736
1737 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1738 ts should be directed to him through the IPython mailing lists.
1739
1740 \layout Itemize
1741
1742 This code is still somewhat experimental so it's a bit rough around the
1743 edges (although in practice, it works quite well).
1744 \layout Itemize
1745
1746 Be aware that if you customize
1747 \family typewriter
1748 py-python-command
1749 \family default
1750 previously, this value will override what
1751 \family typewriter
1752 ipython.el
1753 \family default
1754 does (because loading the customization variables comes later).
1755 \layout Section
1756
1757
1758 \begin_inset LatexCommand \label{sec:quick_tips}
1759
1760 \end_inset
1761
1762 Quick tips
1763 \layout Standard
1764
1765 IPython can be used as an improved replacement for the Python prompt, and
1766 for that you don't really need to read any more of this manual.
1767 But in this section we'll try to summarize a few tips on how to make the
1768 most effective use of it for everyday Python development, highlighting
1769 things you might miss in the rest of the manual (which is getting long).
1770 We'll give references to parts in the manual which provide more detail
1771 when appropriate.
1772 \layout Standard
1773
1774 The following article by Jeremy Jones provides an introductory tutorial
1775 about IPython:
1776 \newline
1777
1778 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1779
1780 \end_inset
1781
1782
1783 \layout Itemize
1784
1785 The TAB key.
1786 TAB-completion, especially for attributes, is a convenient way to explore
1787 the structure of any object you're dealing with.
1788 Simply type
1789 \family typewriter
1790 object_name.<TAB>
1791 \family default
1792 and a list of the object's attributes will be printed (see sec.
1793
1794 \begin_inset LatexCommand \ref{sec:readline}
1795
1796 \end_inset
1797
1798 for more).
1799 Tab completion also works on file and directory names, which combined with
1800 IPython's alias system allows you to do from within IPython many of the
1801 things you normally would need the system shell for.
1802
1803 \layout Itemize
1804
1805 Explore your objects.
1806 Typing
1807 \family typewriter
1808 object_name?
1809 \family default
1810 will print all sorts of details about any object, including docstrings,
1811 function definition lines (for call arguments) and constructor details
1812 for classes.
1813 The magic commands
1814 \family typewriter
1815 %pdoc
1816 \family default
1817 ,
1818 \family typewriter
1819 %pdef
1820 \family default
1821 ,
1822 \family typewriter
1823 %psource
1824 \family default
1825 and
1826 \family typewriter
1827 %pfile
1828 \family default
1829 will respectively print the docstring, function definition line, full source
1830 code and the complete file for any object (when they can be found).
1831 If automagic is on (it is by default), you don't need to type the '
1832 \family typewriter
1833 %
1834 \family default
1835 ' explicitly.
1836 See sec.
1837
1838 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1839
1840 \end_inset
1841
1842 for more.
1843 \layout Itemize
1844
1845 The
1846 \family typewriter
1847 %run
1848 \family default
1849 magic command allows you to run any python script and load all of its data
1850 directly into the interactive namespace.
1851 Since the file is re-read from disk each time, changes you make to it are
1852 reflected immediately (in contrast to the behavior of
1853 \family typewriter
1854 import
1855 \family default
1856 ).
1857 I rarely use
1858 \family typewriter
1859 import
1860 \family default
1861 for code I am testing, relying on
1862 \family typewriter
1863 %run
1864 \family default
1865 instead.
1866 See sec.
1867
1868 \begin_inset LatexCommand \ref{sec:magic}
1869
1870 \end_inset
1871
1872 for more on this and other magic commands, or type the name of any magic
1873 command and ? to get details on it.
1874 See also sec.
1875
1876 \begin_inset LatexCommand \ref{sec:dreload}
1877
1878 \end_inset
1879
1880 for a recursive reload command.
1881 \newline
1882
1883 \family typewriter
1884 %run
1885 \family default
1886 also has special flags for timing the execution of your scripts (
1887 \family typewriter
1888 -t
1889 \family default
1890 ) and for executing them under the control of either Python's
1891 \family typewriter
1892 pdb
1893 \family default
1894 debugger (
1895 \family typewriter
1896 -d
1897 \family default
1898 ) or profiler (
1899 \family typewriter
1900 -p
1901 \family default
1902 ).
1903 With all of these,
1904 \family typewriter
1905 %run
1906 \family default
1907 can be used as the main tool for efficient interactive development of code
1908 which you write in your editor of choice.
1909 \layout Itemize
1910
1911 Use the Python debugger,
1912 \family typewriter
1913 pdb
1914 \family default
1915
1916 \begin_inset Foot
1917 collapsed true
1918
1919 \layout Standard
1920
1921 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
1922 to IPython's improved debugger and profiler support.
1923 \end_inset
1924
1925 .
1926 The
1927 \family typewriter
1928 %pdb
1929 \family default
1930 command allows you to toggle on and off the automatic invocation of the
1931 pdb debugger at any uncaught exception.
1932 The advantage of this is that pdb starts
1933 \emph on
1934 inside
1935 \emph default
1936 the function where the exception occurred, with all data still available.
1937 You can print variables, see code, execute statements and even walk up
1938 and down the call stack to track down the true source of the problem (which
1939 often is many layers in the stack above where the exception gets triggered).
1940 \newline
1941 Running programs with
1942 \family typewriter
1943 %run
1944 \family default
1945 and pdb active can be an efficient to develop and debug code, in many cases
1946 eliminating the need for
1947 \family typewriter
1948 print
1949 \family default
1950 statements or external debugging tools.
1951 I often simply put a
1952 \family typewriter
1953 1/0
1954 \family default
1955 in a place where I want to take a look so that pdb gets called, quickly
1956 view whatever variables I need to or test various pieces of code and then
1957 remove the
1958 \family typewriter
1959 1/0
1960 \family default
1961 .
1962 \newline
1963 Note also that `
1964 \family typewriter
1965 %run -d
1966 \family default
1967 ' activates
1968 \family typewriter
1969 pdb
1970 \family default
1971 and automatically sets initial breakpoints for you to step through your
1972 code, watch variables, etc.
1973 See Sec.\SpecialChar ~
1974
1975 \begin_inset LatexCommand \ref{sec:cache_output}
1976
1977 \end_inset
1978
1979 for details.
1980 \layout Itemize
1981
1982 Use the output cache.
1983 All output results are automatically stored in a global dictionary named
1984
1985 \family typewriter
1986 Out
1987 \family default
1988 and variables named
1989 \family typewriter
1990 _1
1991 \family default
1992 ,
1993 \family typewriter
1994 _2
1995 \family default
1996 , etc.
1997 alias them.
1998 For example, the result of input line 4 is available either as
1999 \family typewriter
2000 Out[4]
2001 \family default
2002 or as
2003 \family typewriter
2004 _4
2005 \family default
2006 .
2007 Additionally, three variables named
2008 \family typewriter
2009 _
2010 \family default
2011 ,
2012 \family typewriter
2013 __
2014 \family default
2015 and
2016 \family typewriter
2017 ___
2018 \family default
2019 are always kept updated with the for the last three results.
2020 This allows you to recall any previous result and further use it for new
2021 calculations.
2022 See Sec.\SpecialChar ~
2023
2024 \begin_inset LatexCommand \ref{sec:cache_output}
2025
2026 \end_inset
2027
2028 for more.
2029 \layout Itemize
2030
2031 Put a '
2032 \family typewriter
2033 ;
2034 \family default
2035 ' at the end of a line to supress the printing of output.
2036 This is useful when doing calculations which generate long output you are
2037 not interested in seeing.
2038 The
2039 \family typewriter
2040 _*
2041 \family default
2042 variables and the
2043 \family typewriter
2044 Out[]
2045 \family default
2046 list do get updated with the contents of the output, even if it is not
2047 printed.
2048 You can thus still access the generated results this way for further processing.
2049 \layout Itemize
2050
2051 A similar system exists for caching input.
2052 All input is stored in a global list called
2053 \family typewriter
2054 In
2055 \family default
2056 , so you can re-execute lines 22 through 28 plus line 34 by typing
2057 \family typewriter
2058 'exec In[22:29]+In[34]'
2059 \family default
2060 (using Python slicing notation).
2061 If you need to execute the same set of lines often, you can assign them
2062 to a macro with the
2063 \family typewriter
2064 %macro
2065 \family default
2066
2067 \family typewriter
2068 function.
2069
2070 \family default
2071 See sec.
2072
2073 \begin_inset LatexCommand \ref{sec:cache_input}
2074
2075 \end_inset
2076
2077 for more.
2078 \layout Itemize
2079
2080 Use your input history.
2081 The
2082 \family typewriter
2083 %hist
2084 \family default
2085 command can show you all previous input, without line numbers if desired
2086 (option
2087 \family typewriter
2088 -n
2089 \family default
2090 ) so you can directly copy and paste code either back in IPython or in a
2091 text editor.
2092 You can also save all your history by turning on logging via
2093 \family typewriter
2094 %logstart
2095 \family default
2096 ; these logs can later be either reloaded as IPython sessions or used as
2097 code for your programs.
2098 \layout Itemize
2099
2100 Define your own macros with
2101 \family typewriter
2102 %macro
2103 \family default
2104 .
2105 This can be useful for automating sequences of expressions when working
2106 interactively.
2107 \layout Itemize
2108
2109 Define your own system aliases.
2110 Even though IPython gives you access to your system shell via the
2111 \family typewriter
2112 !
2113 \family default
2114 prefix, it is convenient to have aliases to the system commands you use
2115 most often.
2116 This allows you to work seamlessly from inside IPython with the same commands
2117 you are used to in your system shell.
2118 \newline
2119 IPython comes with some pre-defined aliases and a complete system for changing
2120 directories, both via a stack (see
2121 \family typewriter
2122 %pushd
2123 \family default
2124 ,
2125 \family typewriter
2126 %popd
2127 \family default
2128 and
2129 \family typewriter
2130 %ds
2131 \family default
2132 ) and via direct
2133 \family typewriter
2134 %cd
2135 \family default
2136 .
2137 The latter keeps a history of visited directories and allows you to go
2138 to any previously visited one.
2139 \layout Itemize
2140
2141 Use Python to manipulate the results of system commands.
2142 The `
2143 \family typewriter
2144 !!
2145 \family default
2146 ' special syntax, and the
2147 \family typewriter
2148 %sc
2149 \family default
2150 and
2151 \family typewriter
2152 %sx
2153 \family default
2154 magic commands allow you to capture system output into Python variables.
2155 \layout Itemize
2156
2157 Expand python variables when calling the shell (either via
2158 \family typewriter
2159 `!'
2160 \family default
2161 and
2162 \family typewriter
2163 `!!'
2164 \family default
2165 or via aliases) by prepending a
2166 \family typewriter
2167 $
2168 \family default
2169 in front of them.
2170 You can also expand complete python expressions.
2171 See sec.\SpecialChar ~
2172
2173 \begin_inset LatexCommand \ref{sub:System-shell-access}
2174
2175 \end_inset
2176
2177 for more.
2178 \layout Itemize
2179
2180 Use profiles to maintain different configurations (modules to load, function
2181 definitions, option settings) for particular tasks.
2182 You can then have customized versions of IPython for specific purposes.
2183 See sec.\SpecialChar ~
2184
2185 \begin_inset LatexCommand \ref{sec:profiles}
2186
2187 \end_inset
2188
2189 for more.
2190 \layout Itemize
2191
2192 Embed IPython in your programs.
2193 A few lines of code are enough to load a complete IPython inside your own
2194 programs, giving you the ability to work with your data interactively after
2195 automatic processing has been completed.
2196 See sec.\SpecialChar ~
2197
2198 \begin_inset LatexCommand \ref{sec:embed}
2199
2200 \end_inset
2201
2202 for more.
2203 \layout Itemize
2204
2205 Use the Python profiler.
2206 When dealing with performance issues, the
2207 \family typewriter
2208 %run
2209 \family default
2210 command with a
2211 \family typewriter
2212 -p
2213 \family default
2214 option allows you to run complete programs under the control of the Python
2215 profiler.
2216 The
2217 \family typewriter
2218 %prun
2219 \family default
2220 command does a similar job for single Python expressions (like function
2221 calls).
2222 \layout Itemize
2223
2224 Use
2225 \family typewriter
2226 %edit
2227 \family default
2228 to have almost multiline editing.
2229 While IPython doesn't support true multiline editing, this command allows
2230 you to call an editor on the spot, and IPython will execute the code you
2231 type in there as if it were typed interactively.
2232 \layout Standard
2233
2234 If you have your own favorite tip on using IPython efficiently for a certain
2235 task (especially things which can't be done in the normal Python interpreter),
2236 don't hesitate to send it!
2237 \layout Section
2238
2239 Command-line use
2240 \layout Standard
2241
2242 You start IPython with the command:
2243 \layout Standard
2244
2245
2246 \family typewriter
2247 $ ipython [options] files
2248 \layout Standard
2249
2250 If invoked with no options, it executes all the files listed in sequence
2251 and drops you into the interpreter while still acknowledging any options
2252 you may have set in your ipythonrc file.
2253 This behavior is different from standard Python, which when called as
2254 \family typewriter
2255 python -i
2256 \family default
2257 will only execute one file and ignore your configuration setup.
2258 \layout Standard
2259
2260 Please note that some of the configuration options are not available at
2261 the command line, simply because they are not practical here.
2262 Look into your ipythonrc configuration file for details on those.
2263 This file typically installed in the
2264 \family typewriter
2265 $HOME/.ipython
2266 \family default
2267 directory.
2268 For Windows users,
2269 \family typewriter
2270 $HOME
2271 \family default
2272 resolves to
2273 \family typewriter
2274 C:
2275 \backslash
2276
2277 \backslash
2278 Documents and Settings
2279 \backslash
2280
2281 \backslash
2282 YourUserName
2283 \family default
2284 in most instances.
2285 In the rest of this text, we will refer to this directory as
2286 \family typewriter
2287 IPYTHONDIR
2288 \family default
2289 .
2290 \layout Subsection
2291
2292
2293 \begin_inset LatexCommand \label{sec:threading-opts}
2294
2295 \end_inset
2296
2297 Special Threading Options
2298 \layout Standard
2299
2300 The following special options are ONLY valid at the beginning of the command
2301 line, and not later.
2302 This is because they control the initial- ization of ipython itself, before
2303 the normal option-handling mechanism is active.
2304 \layout List
2305 \labelwidthstring 00.00.0000
2306
2307
2308 \family typewriter
2309 \series bold
2310 -gthread,\SpecialChar ~
2311 -wthread,\SpecialChar ~
2312 -pylab:
2313 \family default
2314 \series default
2315 Only
2316 \emph on
2317 one
2318 \emph default
2319 of these can be given, and it can only be given as the first option passed
2320 to IPython (it will have no effect in any other position).
2321 They provide threading support for the GTK and WXPython toolkits, and for
2322 the matplotlib library.
2323 \layout List
2324 \labelwidthstring 00.00.0000
2325
2326 \SpecialChar ~
2327 If
2328 \family typewriter
2329 -gthread
2330 \family default
2331 is given, IPython starts running a separate thread for GTK operation, so
2332 that pyGTK-based programs can open and control GUIs without blocking IPython.
2333
2334 \layout List
2335 \labelwidthstring 00.00.0000
2336
2337 \SpecialChar ~
2338 Similarly,
2339 \family typewriter
2340 -wthread
2341 \family default
2342 instantiates IPython with threading support for the WXPython toolkit.
2343 You can control WX application windows from within IPython.
2344 \layout List
2345 \labelwidthstring 00.00.0000
2346
2347 \SpecialChar ~
2348 If
2349 \family typewriter
2350 -pylab
2351 \family default
2352 is given, IPython loads special support for the mat- plotlib library (
2353 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2354
2355 \end_inset
2356
2357 ), allowing interactive usage of any of its backends as defined in the user's
2358 .matplotlibrc file.
2359 It automatically activates GTK or WX threading for IPyhton if the choice
2360 of matplotlib backend requires it.
2361 It also modifies the
2362 \family typewriter
2363 %run
2364 \family default
2365 command to correctly execute (without blocking) any matplotlib-based script
2366 which calls
2367 \family typewriter
2368 show()
2369 \family default
2370 at the end.
2371
2372 \layout List
2373 \labelwidthstring 00.00.0000
2374
2375
2376 \family typewriter
2377 \series bold
2378 -tk
2379 \family default
2380 \series default
2381 The
2382 \family typewriter
2383 -g/wthread
2384 \family default
2385 options, and
2386 \family typewriter
2387 -pylab
2388 \family default
2389 (if matplotlib is configured to use WX or GTK), will normally block Tk
2390 graphical interfaces.
2391 This means that when either GTK or WX threading is active, any attempt
2392 to open a Tk GUI will result in a dead window, and pos- sibly cause the
2393 Python interpreter to crash.
2394 An extra option,
2395 \family typewriter
2396 -tk
2397 \family default
2398 , is available to address this issue.
2399 It can
2400 \emph on
2401 only
2402 \emph default
2403 be given as a
2404 \emph on
2405 second
2406 \emph default
2407 option after any of the above (
2408 \family typewriter
2409 -gthread
2410 \family default
2411 ,
2412 \family typewriter
2413 -wthread
2414 \family default
2415 or
2416 \family typewriter
2417 -pylab
2418 \family default
2419 ).
2420 \layout List
2421 \labelwidthstring 00.00.0000
2422
2423 \SpecialChar ~
2424 If
2425 \family typewriter
2426 -tk
2427 \family default
2428 is given, IPython will try to coordinate Tk threading with WX or GTK.
2429 This is however potentially unreliable, and you will have to test on your
2430 platform and Python configuration to determine whether it works for you.
2431 Debian users have reported success, apparently due to the fact that Debian
2432 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2433 Under other Linux environments (such as Fedora Core 2), this option has
2434 caused random crashes and lockups of the Python interpreter.
2435 Under other operating systems (Mac OSX and Windows), you'll need to try
2436 it to find out, since currently no user reports are available.
2437 \layout List
2438 \labelwidthstring 00.00.0000
2439
2440 \SpecialChar ~
2441 There is unfortunately no way for IPython to determine at run time whether
2442
2443 \family typewriter
2444 -tk
2445 \family default
2446 will work reliably or not, so you will need to do some experiments before
2447 relying on it for regular work.
2448
2449 \layout Subsection
2450
2451
2452 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2453
2454 \end_inset
2455
2456 Regular Options
2457 \layout Standard
2458
2459 After the above threading options have been given, regular options can follow
2460 in any order.
2461 All options can be abbreviated to their shortest non-ambiguous form and
2462 are case-sensitive.
2463 One or two dashes can be used.
2464 Some options have an alternate short form, indicated after a
2465 \family typewriter
2466 |
2467 \family default
2468 .
2469 \layout Standard
2470
2471 Most options can also be set from your ipythonrc configuration file.
2472 See the provided example for more details on what the options do.
2473 Options given at the command line override the values set in the ipythonrc
2474 file.
2475 \layout Standard
2476
2477 All options with a
2478 \family typewriter
2479 no|
2480 \family default
2481 prepended can be specified in 'no' form (
2482 \family typewriter
2483 -nooption
2484 \family default
2485 instead of
2486 \family typewriter
2487 -option
2488 \family default
2489 ) to turn the feature off.
2490 \layout List
2491 \labelwidthstring 00.00.0000
2492
2493
2494 \family typewriter
2495 \series bold
2496 -help
2497 \family default
2498 \series default
2499 : print a help message and exit.
2500 \layout List
2501 \labelwidthstring 00.00.0000
2502
2503
2504 \family typewriter
2505 \series bold
2506 -pylab:
2507 \family default
2508 \series default
2509 this can
2510 \emph on
2511 only
2512 \emph default
2513 be given as the
2514 \emph on
2515 first
2516 \emph default
2517 option passed to IPython (it will have no effect in any other position).
2518 It adds special support for the matplotlib library (
2519 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2520
2521 \end_inset
2522
2523 ), allowing interactive usage of any of its backends as defined in the user's
2524
2525 \family typewriter
2526 .matplotlibrc
2527 \family default
2528 file.
2529 It automatically activates GTK or WX threading for IPyhton if the choice
2530 of matplotlib backend requires it.
2531 It also modifies the
2532 \family typewriter
2533 %run
2534 \family default
2535 command to correctly execute (without blocking) any matplotlib-based script
2536 which calls
2537 \family typewriter
2538 show()
2539 \family default
2540 at the end.
2541 See Sec.\SpecialChar ~
2542
2543 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2544
2545 \end_inset
2546
2547 for more details.
2548 \layout List
2549 \labelwidthstring 00.00.0000
2550
2551
2552 \family typewriter
2553 \series bold
2554 -no|automagic
2555 \series default
2556 :
2557 \family default
2558 make magic commands automatic (without needing their first character to
2559 be
2560 \family typewriter
2561 %
2562 \family default
2563 ).
2564 Type
2565 \family typewriter
2566 %magic
2567 \family default
2568 at the IPython prompt for more information.
2569 \layout List
2570 \labelwidthstring 00.00.0000
2571
2572
2573 \family typewriter
2574 \series bold
2575 -no|banner
2576 \series default
2577 :
2578 \family default
2579 Print the initial information banner (default on).
2580 \layout List
2581 \labelwidthstring 00.00.0000
2582
2583
2584 \family typewriter
2585 \series bold
2586 -c\SpecialChar ~
2587 <command>:
2588 \family default
2589 \series default
2590 execute the given command string, and set sys.argv to
2591 \family typewriter
2592 ['c']
2593 \family default
2594 .
2595 This is similar to the
2596 \family typewriter
2597 -c
2598 \family default
2599 option in the normal Python interpreter.
2600
2601 \layout List
2602 \labelwidthstring 00.00.0000
2603
2604
2605 \family typewriter
2606 \series bold
2607 -cache_size|cs\SpecialChar ~
2608 <n>
2609 \series default
2610 :
2611 \family default
2612 size of the output cache (maximum number of entries to hold in memory).
2613 The default is 1000, you can change it permanently in your config file.
2614 Setting it to 0 completely disables the caching system, and the minimum
2615 value accepted is 20 (if you provide a value less than 20, it is reset
2616 to 0 and a warning is issued) This limit is defined because otherwise you'll
2617 spend more time re-flushing a too small cache than working.
2618 \layout List
2619 \labelwidthstring 00.00.0000
2620
2621
2622 \family typewriter
2623 \series bold
2624 -classic|cl
2625 \series default
2626 :
2627 \family default
2628 Gives IPython a similar feel to the classic Python prompt.
2629 \layout List
2630 \labelwidthstring 00.00.0000
2631
2632
2633 \family typewriter
2634 \series bold
2635 -colors\SpecialChar ~
2636 <scheme>:
2637 \family default
2638 \series default
2639 Color scheme for prompts and exception reporting.
2640 Currently implemented: NoColor, Linux and LightBG.
2641 \layout List
2642 \labelwidthstring 00.00.0000
2643
2644
2645 \family typewriter
2646 \series bold
2647 -no|color_info:
2648 \family default
2649 \series default
2650 IPython can display information about objects via a set of functions, and
2651 optionally can use colors for this, syntax highlighting source code and
2652 various other elements.
2653 However, because this information is passed through a pager (like 'less')
2654 and many pagers get confused with color codes, this option is off by default.
2655 You can test it and turn it on permanently in your ipythonrc file if it
2656 works for you.
2657 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
2658 that in RedHat 7.2 doesn't.
2659 \layout List
2660 \labelwidthstring 00.00.0000
2661
2662 \SpecialChar ~
2663 Test it and turn it on permanently if it works with your system.
2664 The magic function
2665 \family typewriter
2666 %color_info
2667 \family default
2668 allows you to toggle this interactively for testing.
2669 \layout List
2670 \labelwidthstring 00.00.0000
2671
2672
2673 \family typewriter
2674 \series bold
2675 -no|debug
2676 \family default
2677 \series default
2678 : Show information about the loading process.
2679 Very useful to pin down problems with your configuration files or to get
2680 details about session restores.
2681 \layout List
2682 \labelwidthstring 00.00.0000
2683
2684
2685 \family typewriter
2686 \series bold
2687 -no|deep_reload
2688 \series default
2689 :
2690 \family default
2691 IPython can use the
2692 \family typewriter
2693 deep_reload
2694 \family default
2695 module which reloads changes in modules recursively (it replaces the
2696 \family typewriter
2697 reload()
2698 \family default
2699 function, so you don't need to change anything to use it).
2700
2701 \family typewriter
2702 deep_reload()
2703 \family default
2704 forces a full reload of modules whose code may have changed, which the
2705 default
2706 \family typewriter
2707 reload()
2708 \family default
2709 function does not.
2710 \layout List
2711 \labelwidthstring 00.00.0000
2712
2713 \SpecialChar ~
2714 When deep_reload is off, IPython will use the normal
2715 \family typewriter
2716 reload()
2717 \family default
2718 , but deep_reload will still be available as
2719 \family typewriter
2720 dreload()
2721 \family default
2722 .
2723 This feature is off by default [which means that you have both normal
2724 \family typewriter
2725 reload()
2726 \family default
2727 and
2728 \family typewriter
2729 dreload()
2730 \family default
2731 ].
2732 \layout List
2733 \labelwidthstring 00.00.0000
2734
2735
2736 \family typewriter
2737 \series bold
2738 -editor\SpecialChar ~
2739 <name>
2740 \family default
2741 \series default
2742 : Which editor to use with the
2743 \family typewriter
2744 %edit
2745 \family default
2746 command.
2747 By default, IPython will honor your
2748 \family typewriter
2749 EDITOR
2750 \family default
2751 environment variable (if not set, vi is the Unix default and notepad the
2752 Windows one).
2753 Since this editor is invoked on the fly by IPython and is meant for editing
2754 small code snippets, you may want to use a small, lightweight editor here
2755 (in case your default
2756 \family typewriter
2757 EDITOR
2758 \family default
2759 is something like Emacs).
2760 \layout List
2761 \labelwidthstring 00.00.0000
2762
2763
2764 \family typewriter
2765 \series bold
2766 -ipythondir\SpecialChar ~
2767 <name>
2768 \series default
2769 :
2770 \family default
2771 name of your IPython configuration directory
2772 \family typewriter
2773 IPYTHONDIR
2774 \family default
2775 .
2776 This can also be specified through the environment variable
2777 \family typewriter
2778 IPYTHONDIR
2779 \family default
2780 .
2781 \layout List
2782 \labelwidthstring 00.00.0000
2783
2784
2785 \family typewriter
2786 \series bold
2787 -log|l
2788 \family default
2789 \series default
2790 : generate a log file of all input.
2791 Defaults to
2792 \family typewriter
2793 $IPYTHONDIR/log
2794 \family default
2795 .
2796 You can use this to later restore a session by loading your logfile as
2797 a file to be executed with option
2798 \family typewriter
2799 -logplay
2800 \family default
2801 (see below).
2802 \layout List
2803 \labelwidthstring 00.00.0000
2804
2805
2806 \family typewriter
2807 \series bold
2808 -logfile|lf\SpecialChar ~
2809 <name>
2810 \series default
2811 :
2812 \family default
2813 specify the name of your logfile.
2814 \layout List
2815 \labelwidthstring 00.00.0000
2816
2817
2818 \family typewriter
2819 \series bold
2820 -logplay|lp\SpecialChar ~
2821 <name>
2822 \series default
2823 :
2824 \family default
2825 you can replay a previous log.
2826 For restoring a session as close as possible to the state you left it in,
2827 use this option (don't just run the logfile).
2828 With
2829 \family typewriter
2830 -logplay
2831 \family default
2832 , IPython will try to reconstruct the previous working environment in full,
2833 not just execute the commands in the logfile.
2834 \layout List
2835 \labelwidthstring 00.00.0000
2836
2837 \SpecialChar ~
2838 When a session is restored, logging is automatically turned on again with
2839 the name of the logfile it was invoked with (it is read from the log header).
2840 So once you've turned logging on for a session, you can quit IPython and
2841 reload it as many times as you want and it will continue to log its history
2842 and restore from the beginning every time.
2843 \layout List
2844 \labelwidthstring 00.00.0000
2845
2846 \SpecialChar ~
2847 Caveats: there are limitations in this option.
2848 The history variables
2849 \family typewriter
2850 _i*
2851 \family default
2852 ,
2853 \family typewriter
2854 _*
2855 \family default
2856 and
2857 \family typewriter
2858 _dh
2859 \family default
2860 don't get restored properly.
2861 In the future we will try to implement full session saving by writing and
2862 retrieving a 'snapshot' of the memory state of IPython.
2863 But our first attempts failed because of inherent limitations of Python's
2864 Pickle module, so this may have to wait.
2865 \layout List
2866 \labelwidthstring 00.00.0000
2867
2868
2869 \family typewriter
2870 \series bold
2871 -no|messages
2872 \series default
2873 :
2874 \family default
2875 Print messages which IPython collects about its startup process (default
2876 on).
2877 \layout List
2878 \labelwidthstring 00.00.0000
2879
2880
2881 \family typewriter
2882 \series bold
2883 -no|pdb
2884 \family default
2885 \series default
2886 : Automatically call the pdb debugger after every uncaught exception.
2887 If you are used to debugging using pdb, this puts you automatically inside
2888 of it after any call (either in IPython or in code called by it) which
2889 triggers an exception which goes uncaught.
2890 \layout List
2891 \labelwidthstring 00.00.0000
2892
2893
2894 \family typewriter
2895 \series bold
2896 -no|pprint
2897 \series default
2898 :
2899 \family default
2900 ipython can optionally use the pprint (pretty printer) module for displaying
2901 results.
2902 pprint tends to give a nicer display of nested data structures.
2903 If you like it, you can turn it on permanently in your config file (default
2904 off).
2905 \layout List
2906 \labelwidthstring 00.00.0000
2907
2908
2909 \family typewriter
2910 \series bold
2911 -profile|p <name>
2912 \series default
2913 :
2914 \family default
2915 assume that your config file is
2916 \family typewriter
2917 ipythonrc-<name>
2918 \family default
2919 (looks in current dir first, then in
2920 \family typewriter
2921 IPYTHONDIR
2922 \family default
2923 ).
2924 This is a quick way to keep and load multiple config files for different
2925 tasks, especially if you use the include option of config files.
2926 You can keep a basic
2927 \family typewriter
2928 IPYTHONDIR/ipythonrc
2929 \family default
2930 file and then have other 'profiles' which include this one and load extra
2931 things for particular tasks.
2932 For example:
2933 \layout List
2934 \labelwidthstring 00.00.0000
2935
2936
2937 \family typewriter
2938 \SpecialChar ~
2939
2940 \family default
2941 1.
2942
2943 \family typewriter
2944 $HOME/.ipython/ipythonrc
2945 \family default
2946 : load basic things you always want.
2947 \layout List
2948 \labelwidthstring 00.00.0000
2949
2950
2951 \family typewriter
2952 \SpecialChar ~
2953
2954 \family default
2955 2.
2956
2957 \family typewriter
2958 $HOME/.ipython/ipythonrc-math
2959 \family default
2960 : load (1) and basic math-related modules.
2961
2962 \layout List
2963 \labelwidthstring 00.00.0000
2964
2965
2966 \family typewriter
2967 \SpecialChar ~
2968
2969 \family default
2970 3.
2971
2972 \family typewriter
2973 $HOME/.ipython/ipythonrc-numeric
2974 \family default
2975 : load (1) and Numeric and plotting modules.
2976 \layout List
2977 \labelwidthstring 00.00.0000
2978
2979 \SpecialChar ~
2980 Since it is possible to create an endless loop by having circular file
2981 inclusions, IPython will stop if it reaches 15 recursive inclusions.
2982 \layout List
2983 \labelwidthstring 00.00.0000
2984
2985
2986 \family typewriter
2987 \series bold
2988 -prompt_in1|pi1\SpecialChar ~
2989 <string>:
2990 \family default
2991 \series default
2992 Specify the string used for input prompts.
2993 Note that if you are using numbered prompts, the number is represented
2994 with a '
2995 \backslash
2996 #' in the string.
2997 Don't forget to quote strings with spaces embedded in them.
2998 Default: '
2999 \family typewriter
3000 In\SpecialChar ~
3001 [
3002 \backslash
3003 #]:
3004 \family default
3005 '.
3006 Sec.\SpecialChar ~
3007
3008 \begin_inset LatexCommand \ref{sec:prompts}
3009
3010 \end_inset
3011
3012 discusses in detail all the available escapes to customize your prompts.
3013 \layout List
3014 \labelwidthstring 00.00.0000
3015
3016
3017 \family typewriter
3018 \series bold
3019 -prompt_in2|pi2\SpecialChar ~
3020 <string>:
3021 \family default
3022 \series default
3023 Similar to the previous option, but used for the continuation prompts.
3024 The special sequence '
3025 \family typewriter
3026
3027 \backslash
3028 D
3029 \family default
3030 ' is similar to '
3031 \family typewriter
3032
3033 \backslash
3034 #
3035 \family default
3036 ', but with all digits replaced dots (so you can have your continuation
3037 prompt aligned with your input prompt).
3038 Default: '
3039 \family typewriter
3040 \SpecialChar ~
3041 \SpecialChar ~
3042 \SpecialChar ~
3043 .
3044 \backslash
3045 D.:
3046 \family default
3047 ' (note three spaces at the start for alignment with '
3048 \family typewriter
3049 In\SpecialChar ~
3050 [
3051 \backslash
3052 #]
3053 \family default
3054 ').
3055 \layout List
3056 \labelwidthstring 00.00.0000
3057
3058
3059 \family typewriter
3060 \series bold
3061 -prompt_out|po\SpecialChar ~
3062 <string>:
3063 \family default
3064 \series default
3065 String used for output prompts, also uses numbers like
3066 \family typewriter
3067 prompt_in1
3068 \family default
3069 .
3070 Default: '
3071 \family typewriter
3072 Out[
3073 \backslash
3074 #]:
3075 \family default
3076 '
3077 \layout List
3078 \labelwidthstring 00.00.0000
3079
3080
3081 \family typewriter
3082 \series bold
3083 -quick
3084 \family default
3085 \series default
3086 : start in bare bones mode (no config file loaded).
3087 \layout List
3088 \labelwidthstring 00.00.0000
3089
3090
3091 \family typewriter
3092 \series bold
3093 -rcfile\SpecialChar ~
3094 <name>
3095 \series default
3096 :
3097 \family default
3098 name of your IPython resource configuration file.
3099 Normally IPython loads ipythonrc (from current directory) or
3100 \family typewriter
3101 IPYTHONDIR/ipythonrc
3102 \family default
3103 .
3104 \layout List
3105 \labelwidthstring 00.00.0000
3106
3107 \SpecialChar ~
3108 If the loading of your config file fails, IPython starts with a bare bones
3109 configuration (no modules loaded at all).
3110 \layout List
3111 \labelwidthstring 00.00.0000
3112
3113
3114 \family typewriter
3115 \series bold
3116 -no|readline
3117 \family default
3118 \series default
3119 : use the readline library, which is needed to support name completion and
3120 command history, among other things.
3121 It is enabled by default, but may cause problems for users of X/Emacs in
3122 Python comint or shell buffers.
3123 \layout List
3124 \labelwidthstring 00.00.0000
3125
3126 \SpecialChar ~
3127 Note that X/Emacs 'eterm' buffers (opened with
3128 \family typewriter
3129 M-x\SpecialChar ~
3130 term
3131 \family default
3132 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3133 \family typewriter
3134 M-x\SpecialChar ~
3135 shell
3136 \family default
3137 and
3138 \family typewriter
3139 C-c\SpecialChar ~
3140 !
3141 \family default
3142 ) buffers do not.
3143 \layout List
3144 \labelwidthstring 00.00.0000
3145
3146
3147 \family typewriter
3148 \series bold
3149 -screen_length|sl\SpecialChar ~
3150 <n>
3151 \series default
3152 :
3153 \family default
3154 number of lines of your screen.
3155 This is used to control printing of very long strings.
3156 Strings longer than this number of lines will be sent through a pager instead
3157 of directly printed.
3158 \layout List
3159 \labelwidthstring 00.00.0000
3160
3161 \SpecialChar ~
3162 The default value for this is 0, which means IPython will auto-detect your
3163 screen size every time it needs to print certain potentially long strings
3164 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3165 internally).
3166 If for some reason this isn't working well (it needs curses support), specify
3167 it yourself.
3168 Otherwise don't change the default.
3169 \layout List
3170 \labelwidthstring 00.00.0000
3171
3172
3173 \family typewriter
3174 \series bold
3175 -separate_in|si\SpecialChar ~
3176 <string>
3177 \series default
3178 :
3179 \family default
3180 separator before input prompts.
3181 Default: '
3182 \family typewriter
3183
3184 \backslash
3185 n
3186 \family default
3187 '
3188 \layout List
3189 \labelwidthstring 00.00.0000
3190
3191
3192 \family typewriter
3193 \series bold
3194 -separate_out|so\SpecialChar ~
3195 <string>
3196 \family default
3197 \series default
3198 : separator before output prompts.
3199 Default: nothing.
3200 \layout List
3201 \labelwidthstring 00.00.0000
3202
3203
3204 \family typewriter
3205 \series bold
3206 -separate_out2|so2\SpecialChar ~
3207 <string>
3208 \series default
3209 :
3210 \family default
3211 separator after output prompts.
3212 Default: nothing.
3213 \layout List
3214 \labelwidthstring 00.00.0000
3215
3216 \SpecialChar ~
3217 For these three options, use the value 0 to specify no separator.
3218 \layout List
3219 \labelwidthstring 00.00.0000
3220
3221
3222 \family typewriter
3223 \series bold
3224 -nosep
3225 \series default
3226 :
3227 \family default
3228 shorthand for
3229 \family typewriter
3230 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3231 \family default
3232 .
3233 Simply removes all input/output separators.
3234 \layout List
3235 \labelwidthstring 00.00.0000
3236
3237
3238 \family typewriter
3239 \series bold
3240 -upgrade
3241 \family default
3242 \series default
3243 : allows you to upgrade your
3244 \family typewriter
3245 IPYTHONDIR
3246 \family default
3247 configuration when you install a new version of IPython.
3248 Since new versions may include new command line options or example files,
3249 this copies updated ipythonrc-type files.
3250 However, it backs up (with a
3251 \family typewriter
3252 .old
3253 \family default
3254 extension) all files which it overwrites so that you can merge back any
3255 customizations you might have in your personal files.
3256 \layout List
3257 \labelwidthstring 00.00.0000
3258
3259
3260 \family typewriter
3261 \series bold
3262 -Version
3263 \series default
3264 :
3265 \family default
3266 print version information and exit.
3267 \layout List
3268 \labelwidthstring 00.00.0000
3269
3270
3271 \family typewriter
3272 \series bold
3273 -xmode <modename>
3274 \series default
3275 :
3276 \family default
3277 Mode for exception reporting.
3278 \layout List
3279 \labelwidthstring 00.00.0000
3280
3281 \SpecialChar ~
3282 Valid modes: Plain, Context and Verbose.
3283 \layout List
3284 \labelwidthstring 00.00.0000
3285
3286 \SpecialChar ~
3287 Plain: similar to python's normal traceback printing.
3288 \layout List
3289 \labelwidthstring 00.00.0000
3290
3291 \SpecialChar ~
3292 Context: prints 5 lines of context source code around each line in the
3293 traceback.
3294 \layout List
3295 \labelwidthstring 00.00.0000
3296
3297 \SpecialChar ~
3298 Verbose: similar to Context, but additionally prints the variables currently
3299 visible where the exception happened (shortening their strings if too long).
3300 This can potentially be very slow, if you happen to have a huge data structure
3301 whose string representation is complex to compute.
3302 Your computer may appear to freeze for a while with cpu usage at 100%.
3303 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3304 it more than once).
3305 \layout Section
3306
3307 Interactive use
3308 \layout Standard
3309
3310
3311 \series bold
3312 Warning
3313 \series default
3314 : IPython relies on the existence of a global variable called
3315 \family typewriter
3316 __IP
3317 \family default
3318 which controls the shell itself.
3319 If you redefine
3320 \family typewriter
3321 __IP
3322 \family default
3323 to anything, bizarre behavior will quickly occur.
3324 \layout Standard
3325
3326 Other than the above warning, IPython is meant to work as a drop-in replacement
3327 for the standard interactive interpreter.
3328 As such, any code which is valid python should execute normally under IPython
3329 (cases where this is not true should be reported as bugs).
3330 It does, however, offer many features which are not available at a standard
3331 python prompt.
3332 What follows is a list of these.
3333 \layout Subsection
3334
3335 Caution for Windows users
3336 \layout Standard
3337
3338 Windows, unfortunately, uses the `
3339 \family typewriter
3340
3341 \backslash
3342
3343 \family default
3344 ' character as a path separator.
3345 This is a terrible choice, because `
3346 \family typewriter
3347
3348 \backslash
3349
3350 \family default
3351 ' also represents the escape character in most modern programming languages,
3352 including Python.
3353 For this reason, issuing many of the commands discussed below (especially
3354 magics which affect the filesystem) with `
3355 \family typewriter
3356
3357 \backslash
3358
3359 \family default
3360 ' in them will cause strange errors.
3361 \layout Standard
3362
3363 A partial solution is to use instead the `
3364 \family typewriter
3365 /
3366 \family default
3367 ' character as a path separator, which Windows recognizes in
3368 \emph on
3369 most
3370 \emph default
3371 situations.
3372 However, in Windows commands `
3373 \family typewriter
3374 /
3375 \family default
3376 ' flags options, so you can not use it for the root directory.
3377 This means that paths beginning at the root must be typed in a contrived
3378 manner like:
3379 \newline
3380
3381 \family typewriter
3382 %copy
3383 \backslash
3384 opt/foo/bar.txt
3385 \backslash
3386 tmp
3387 \layout Standard
3388
3389 There is no sensible thing IPython can do to truly work around this flaw
3390 in Windows
3391 \begin_inset Foot
3392 collapsed true
3393
3394 \layout Standard
3395
3396 If anyone comes up with a
3397 \emph on
3398 clean
3399 \emph default
3400 solution which works consistently and does not negatively impact other
3401 platforms at all, I'll gladly accept a patch.
3402 \end_inset
3403
3404 .
3405 \layout Subsection
3406
3407
3408 \begin_inset LatexCommand \label{sec:magic}
3409
3410 \end_inset
3411
3412 Magic command system
3413 \layout Standard
3414
3415 IPython will treat any line whose first character is a
3416 \family typewriter
3417 %
3418 \family default
3419 as a special call to a 'magic' function.
3420 These allow you to control the behavior of IPython itself, plus a lot of
3421 system-type features.
3422 They are all prefixed with a
3423 \family typewriter
3424 %
3425 \family default
3426 character, but parameters are given without parentheses or quotes.
3427 \layout Standard
3428
3429 Example: typing
3430 \family typewriter
3431 '%cd mydir'
3432 \family default
3433 (without the quotes) changes you working directory to
3434 \family typewriter
3435 'mydir'
3436 \family default
3437 , if it exists.
3438 \layout Standard
3439
3440 If you have 'automagic' enabled (in your
3441 \family typewriter
3442 ipythonrc
3443 \family default
3444 file, via the command line option
3445 \family typewriter
3446 -automagic
3447 \family default
3448 or with the
3449 \family typewriter
3450 %automagic
3451 \family default
3452 function), you don't need to type in the
3453 \family typewriter
3454 %
3455 \family default
3456 explicitly.
3457 IPython will scan its internal list of magic functions and call one if
3458 it exists.
3459 With automagic on you can then just type '
3460 \family typewriter
3461 cd mydir
3462 \family default
3463 ' to go to directory '
3464 \family typewriter
3465 mydir
3466 \family default
3467 '.
3468 The automagic system has the lowest possible precedence in name searches,
3469 so defining an identifier with the same name as an existing magic function
3470 will shadow it for automagic use.
3471 You can still access the shadowed magic function by explicitly using the
3472
3473 \family typewriter
3474 %
3475 \family default
3476 character at the beginning of the line.
3477 \layout Standard
3478
3479 An example (with automagic on) should clarify all this:
3480 \layout LyX-Code
3481
3482 In [1]: cd ipython # %cd is called by automagic
3483 \layout LyX-Code
3484
3485 /home/fperez/ipython
3486 \layout LyX-Code
3487
3488 In [2]: cd=1 # now cd is just a variable
3489 \layout LyX-Code
3490
3491 In [3]: cd ..
3492 # and doesn't work as a function anymore
3493 \layout LyX-Code
3494
3495 ------------------------------------------------------------
3496 \layout LyX-Code
3497
3498 File "<console>", line 1
3499 \layout LyX-Code
3500
3501 cd ..
3502 \layout LyX-Code
3503
3504 ^
3505 \layout LyX-Code
3506
3507 SyntaxError: invalid syntax
3508 \layout LyX-Code
3509
3510 \layout LyX-Code
3511
3512 In [4]: %cd ..
3513 # but %cd always works
3514 \layout LyX-Code
3515
3516 /home/fperez
3517 \layout LyX-Code
3518
3519 In [5]: del cd # if you remove the cd variable
3520 \layout LyX-Code
3521
3522 In [6]: cd ipython # automagic can work again
3523 \layout LyX-Code
3524
3525 /home/fperez/ipython
3526 \layout Standard
3527
3528 You can define your own magic functions to extend the system.
3529 The following is a snippet of code which shows how to do it.
3530 It is provided as file
3531 \family typewriter
3532 example-magic.py
3533 \family default
3534 in the examples directory:
3535 \layout Standard
3536
3537
3538 \begin_inset Include \verbatiminput{examples/example-magic.py}
3539 preview false
3540
3541 \end_inset
3542
3543
3544 \layout Standard
3545
3546 You can also define your own aliased names for magic functions.
3547 In your
3548 \family typewriter
3549 ipythonrc
3550 \family default
3551 file, placing a line like:
3552 \layout Standard
3553
3554
3555 \family typewriter
3556 execute __IP.magic_cl = __IP.magic_clear
3557 \layout Standard
3558
3559 will define
3560 \family typewriter
3561 %cl
3562 \family default
3563 as a new name for
3564 \family typewriter
3565 %clear
3566 \family default
3567 .
3568 \layout Standard
3569
3570 Type
3571 \family typewriter
3572 %magic
3573 \family default
3574 for more information, including a list of all available magic functions
3575 at any time and their docstrings.
3576 You can also type
3577 \family typewriter
3578 %magic_function_name?
3579 \family default
3580 (see sec.
3581
3582 \begin_inset LatexCommand \ref{sec:dyn-object-info}
3583
3584 \end_inset
3585
3586 for information on the
3587 \family typewriter
3588 '?'
3589 \family default
3590 system) to get information about any particular magic function you are
3591 interested in.
3592 \layout Subsubsection
3593
3594 Magic commands
3595 \layout Standard
3596
3597 The rest of this section is automatically generated for each release from
3598 the docstrings in the IPython code.
3599 Therefore the formatting is somewhat minimal, but this method has the advantage
3600 of having information always in sync with the code.
3601 \layout Standard
3602
3603 A list of all the magic commands available in IPython's
3604 \emph on
3605 default
3606 \emph default
3607 installation follows.
3608 This is similar to what you'll see by simply typing
3609 \family typewriter
3610 %magic
3611 \family default
3612 at the prompt, but that will also give you information about magic commands
3613 you may have added as part of your personal customizations.
3614 \layout Standard
3615
3616
3617 \begin_inset Include \input{magic.tex}
3618 preview false
3619
3620 \end_inset
3621
3622
3623 \layout Subsection
3624
3625 Access to the standard Python help
3626 \layout Standard
3627
3628 As of Python 2.1, a help system is available with access to object docstrings
3629 and the Python manuals.
3630 Simply type
3631 \family typewriter
3632 'help'
3633 \family default
3634 (no quotes) to access it.
3635 You can also type
3636 \family typewriter
3637 help(object)
3638 \family default
3639 to obtain information about a given object, and
3640 \family typewriter
3641 help('keyword')
3642 \family default
3643 for information on a keyword.
3644 As noted in sec.
3645
3646 \begin_inset LatexCommand \ref{sec:help-access}
3647
3648 \end_inset
3649
3650 , you need to properly configure your environment variable
3651 \family typewriter
3652 PYTHONDOCS
3653 \family default
3654 for this feature to work correctly.
3655 \layout Subsection
3656
3657
3658 \begin_inset LatexCommand \label{sec:dyn-object-info}
3659
3660 \end_inset
3661
3662 Dynamic object information
3663 \layout Standard
3664
3665 Typing
3666 \family typewriter
3667 ?word
3668 \family default
3669 or
3670 \family typewriter
3671 word?
3672 \family default
3673 prints detailed information about an object.
3674 If certain strings in the object are too long (docstrings, code, etc.) they
3675 get snipped in the center for brevity.
3676 This system gives access variable types and values, full source code for
3677 any object (if available), function prototypes and other useful information.
3678 \layout Standard
3679
3680 Typing
3681 \family typewriter
3682 ??word
3683 \family default
3684 or
3685 \family typewriter
3686 word??
3687 \family default
3688 gives access to the full information without snipping long strings.
3689 Long strings are sent to the screen through the
3690 \family typewriter
3691 less
3692 \family default
3693 pager if longer than the screen and printed otherwise.
3694 On systems lacking the
3695 \family typewriter
3696 less
3697 \family default
3698 command, IPython uses a very basic internal pager.
3699 \layout Standard
3700
3701 The following magic functions are particularly useful for gathering information
3702 about your working environment.
3703 You can get more details by typing
3704 \family typewriter
3705 %magic
3706 \family default
3707 or querying them individually (use
3708 \family typewriter
3709 %function_name?
3710 \family default
3711 with or without the
3712 \family typewriter
3713 %
3714 \family default
3715 ), this is just a summary:
3716 \layout List
3717 \labelwidthstring 00.00.0000
3718
3719
3720 \family typewriter
3721 \series bold
3722 %pdoc\SpecialChar ~
3723 <object>
3724 \family default
3725 \series default
3726 : Print (or run through a pager if too long) the docstring for an object.
3727 If the given object is a class, it will print both the class and the constructo
3728 r docstrings.
3729 \layout List
3730 \labelwidthstring 00.00.0000
3731
3732
3733 \family typewriter
3734 \series bold
3735 %pdef\SpecialChar ~
3736 <object>
3737 \family default
3738 \series default
3739 : Print the definition header for any callable object.
3740 If the object is a class, print the constructor information.
3741 \layout List
3742 \labelwidthstring 00.00.0000
3743
3744
3745 \family typewriter
3746 \series bold
3747 %psource\SpecialChar ~
3748 <object>
3749 \family default
3750 \series default
3751 : Print (or run through a pager if too long) the source code for an object.
3752 \layout List
3753 \labelwidthstring 00.00.0000
3754
3755
3756 \family typewriter
3757 \series bold
3758 %pfile\SpecialChar ~
3759 <object>
3760 \family default
3761 \series default
3762 : Show the entire source file where an object was defined via a pager, opening
3763 it at the line where the object definition begins.
3764 \layout List
3765 \labelwidthstring 00.00.0000
3766
3767
3768 \family typewriter
3769 \series bold
3770 %who/%whos
3771 \family default
3772 \series default
3773 : These functions give information about identifiers you have defined interactiv
3774 ely (not things you loaded or defined in your configuration files).
3775
3776 \family typewriter
3777 %who
3778 \family default
3779 just prints a list of identifiers and
3780 \family typewriter
3781 %whos
3782 \family default
3783 prints a table with some basic details about each identifier.
3784 \layout Standard
3785
3786 Note that the dynamic object information functions (
3787 \family typewriter
3788 ?/??, %pdoc, %pfile, %pdef, %psource
3789 \family default
3790 ) give you access to documentation even on things which are not really defined
3791 as separate identifiers.
3792 Try for example typing
3793 \family typewriter
3794 {}.get?
3795 \family default
3796 or after doing
3797 \family typewriter
3798 import os
3799 \family default
3800 , type
3801 \family typewriter
3802 os.path.abspath??
3803 \family default
3804 .
3805 \layout Subsection
3806
3807
3808 \begin_inset LatexCommand \label{sec:readline}
3809
3810 \end_inset
3811
3812 Readline-based features
3813 \layout Standard
3814
3815 These features require the GNU readline library, so they won't work if your
3816 Python installation lacks readline support.
3817 We will first describe the default behavior IPython uses, and then how
3818 to change it to suit your preferences.
3819 \layout Subsubsection
3820
3821 Command line completion
3822 \layout Standard
3823
3824 At any time, hitting TAB will complete any available python commands or
3825 variable names, and show you a list of the possible completions if there's
3826 no unambiguous one.
3827 It will also complete filenames in the current directory if no python names
3828 match what you've typed so far.
3829 \layout Subsubsection
3830
3831 Search command history
3832 \layout Standard
3833
3834 IPython provides two ways for searching through previous input and thus
3835 reduce the need for repetitive typing:
3836 \layout Enumerate
3837
3838 Start typing, and then use
3839 \family typewriter
3840 Ctrl-p
3841 \family default
3842 (previous,up) and
3843 \family typewriter
3844 Ctrl-n
3845 \family default
3846 (next,down) to search through only the history items that match what you've
3847 typed so far.
3848 If you use
3849 \family typewriter
3850 Ctrl-p/Ctrl-n
3851 \family default
3852 at a blank prompt, they just behave like normal arrow keys.
3853 \layout Enumerate
3854
3855 Hit
3856 \family typewriter
3857 Ctrl-r
3858 \family default
3859 : opens a search prompt.
3860 Begin typing and the system searches your history for lines that contain
3861 what you've typed so far, completing as much as it can.
3862 \layout Subsubsection
3863
3864 Persistent command history across sessions
3865 \layout Standard
3866
3867 IPython will save your input history when it leaves and reload it next time
3868 you restart it.
3869 By default, the history file is named
3870 \family typewriter
3871 $IPYTHONDIR/history
3872 \family default
3873 , but if you've loaded a named profile, '
3874 \family typewriter
3875 -PROFILE_NAME
3876 \family default
3877 ' is appended to the name.
3878 This allows you to keep separate histories related to various tasks: commands
3879 related to numerical work will not be clobbered by a system shell history,
3880 for example.
3881 \layout Subsubsection
3882
3883 Autoindent
3884 \layout Standard
3885
3886 IPython can recognize lines ending in ':' and indent the next line, while
3887 also un-indenting automatically after 'raise' or 'return'.
3888
3889 \layout Standard
3890
3891 This feature uses the readline library, so it will honor your
3892 \family typewriter
3893 ~/.inputrc
3894 \family default
3895 configuration (or whatever file your
3896 \family typewriter
3897 INPUTRC
3898 \family default
3899 variable points to).
3900 Adding the following lines to your
3901 \family typewriter
3902 .inputrc
3903 \family default
3904 file can make indenting/unindenting more convenient (
3905 \family typewriter
3906 M-i
3907 \family default
3908 indents,
3909 \family typewriter
3910 M-u
3911 \family default
3912 unindents):
3913 \layout Standard
3914
3915
3916 \family typewriter
3917 $if Python
3918 \newline
3919 "
3920 \backslash
3921 M-i": "\SpecialChar ~
3922 \SpecialChar ~
3923 \SpecialChar ~
3924 \SpecialChar ~
3925 "
3926 \newline
3927 "
3928 \backslash
3929 M-u": "
3930 \backslash
3931 d
3932 \backslash
3933 d
3934 \backslash
3935 d
3936 \backslash
3937 d"
3938 \newline
3939 $endif
3940 \layout Standard
3941
3942 Note that there are 4 spaces between the quote marks after
3943 \family typewriter
3944 "M-i"
3945 \family default
3946 above.
3947 \layout Standard
3948
3949
3950 \series bold
3951 Warning:
3952 \series default
3953 this feature is ON by default, but it can cause problems with the pasting
3954 of multi-line indented code (the pasted code gets re-indented on each line).
3955 A magic function
3956 \family typewriter
3957 %autoindent
3958 \family default
3959 allows you to toggle it on/off at runtime.
3960 You can also disable it permanently on in your
3961 \family typewriter
3962 ipythonrc
3963 \family default
3964 file (set
3965 \family typewriter
3966 autoindent 0
3967 \family default
3968 ).
3969 \layout Subsubsection
3970
3971 Customizing readline behavior
3972 \layout Standard
3973
3974 All these features are based on the GNU readline library, which has an extremely
3975 customizable interface.
3976 Normally, readline is configured via a file which defines the behavior
3977 of the library; the details of the syntax for this can be found in the
3978 readline documentation available with your system or on the Internet.
3979 IPython doesn't read this file (if it exists) directly, but it does support
3980 passing to readline valid options via a simple interface.
3981 In brief, you can customize readline by setting the following options in
3982 your
3983 \family typewriter
3984 ipythonrc
3985 \family default
3986 configuration file (note that these options can
3987 \emph on
3988 not
3989 \emph default
3990 be specified at the command line):
3991 \layout List
3992 \labelwidthstring 00.00.0000
3993
3994
3995 \family typewriter
3996 \series bold
3997 readline_parse_and_bind:
3998 \family default
3999 \series default
4000 this option can appear as many times as you want, each time defining a
4001 string to be executed via a
4002 \family typewriter
4003 readline.parse_and_bind()
4004 \family default
4005 command.
4006 The syntax for valid commands of this kind can be found by reading the
4007 documentation for the GNU readline library, as these commands are of the
4008 kind which readline accepts in its configuration file.
4009 \layout List
4010 \labelwidthstring 00.00.0000
4011
4012
4013 \family typewriter
4014 \series bold
4015 readline_remove_delims:
4016 \family default
4017 \series default
4018 a string of characters to be removed from the default word-delimiters list
4019 used by readline, so that completions may be performed on strings which
4020 contain them.
4021 Do not change the default value unless you know what you're doing.
4022 \layout List
4023 \labelwidthstring 00.00.0000
4024
4025
4026 \family typewriter
4027 \series bold
4028 readline_omit__names
4029 \family default
4030 \series default
4031 : when tab-completion is enabled, hitting
4032 \family typewriter
4033 <tab>
4034 \family default
4035 after a '
4036 \family typewriter
4037 .
4038 \family default
4039 ' in a name will complete all attributes of an object, including all the
4040 special methods whose names include double underscores (like
4041 \family typewriter
4042 __getitem__
4043 \family default
4044 or
4045 \family typewriter
4046 __class__
4047 \family default
4048 ).
4049 If you'd rather not see these names by default, you can set this option
4050 to 1.
4051 Note that even when this option is set, you can still see those names by
4052 explicitly typing a
4053 \family typewriter
4054 _
4055 \family default
4056 after the period and hitting
4057 \family typewriter
4058 <tab>
4059 \family default
4060 : '
4061 \family typewriter
4062 name._<tab>
4063 \family default
4064 ' will always complete attribute names starting with '
4065 \family typewriter
4066 _
4067 \family default
4068 '.
4069 \layout List
4070 \labelwidthstring 00.00.0000
4071
4072 \SpecialChar ~
4073 This option is off by default so that new users see all attributes of any
4074 objects they are dealing with.
4075 \layout Standard
4076
4077 You will find the default values along with a corresponding detailed explanation
4078 in your
4079 \family typewriter
4080 ipythonrc
4081 \family default
4082 file.
4083 \layout Subsection
4084
4085 Session logging and restoring
4086 \layout Standard
4087
4088 You can log all input from a session either by starting IPython with the
4089 command line switches
4090 \family typewriter
4091 -log
4092 \family default
4093 or
4094 \family typewriter
4095 -logfile
4096 \family default
4097 (see sec.
4098
4099 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4100
4101 \end_inset
4102
4103 )or by activating the logging at any moment with the magic function
4104 \family typewriter
4105 %logstart
4106 \family default
4107 .
4108
4109 \layout Standard
4110
4111 Log files can later be reloaded with the
4112 \family typewriter
4113 -logplay
4114 \family default
4115 option and IPython will attempt to 'replay' the log by executing all the
4116 lines in it, thus restoring the state of a previous session.
4117 This feature is not quite perfect, but can still be useful in many cases.
4118 \layout Standard
4119
4120 The log files can also be used as a way to have a permanent record of any
4121 code you wrote while experimenting.
4122 Log files are regular text files which you can later open in your favorite
4123 text editor to extract code or to 'clean them up' before using them to
4124 replay a session.
4125 \layout Standard
4126
4127 The
4128 \family typewriter
4129 %logstart
4130 \family default
4131 function for activating logging in mid-session is used as follows:
4132 \layout Standard
4133
4134
4135 \family typewriter
4136 %logstart [log_name [log_mode]]
4137 \layout Standard
4138
4139 If no name is given, it defaults to a file named
4140 \family typewriter
4141 'log'
4142 \family default
4143 in your IPYTHONDIR directory, in
4144 \family typewriter
4145 'rotate'
4146 \family default
4147 mode (see below).
4148 \layout Standard
4149
4150 '
4151 \family typewriter
4152 %logstart name
4153 \family default
4154 ' saves to file
4155 \family typewriter
4156 'name'
4157 \family default
4158 in
4159 \family typewriter
4160 'backup'
4161 \family default
4162 mode.
4163 It saves your history up to that point and then continues logging.
4164 \layout Standard
4165
4166
4167 \family typewriter
4168 %logstart
4169 \family default
4170 takes a second optional parameter: logging mode.
4171 This can be one of (note that the modes are given unquoted):
4172 \layout List
4173 \labelwidthstring 00.00.0000
4174
4175
4176 \family typewriter
4177 over
4178 \family default
4179 : overwrite existing
4180 \family typewriter
4181 log_name
4182 \family default
4183 .
4184 \layout List
4185 \labelwidthstring 00.00.0000
4186
4187
4188 \family typewriter
4189 backup
4190 \family default
4191 : rename (if exists) to
4192 \family typewriter
4193 log_name~
4194 \family default
4195 and start
4196 \family typewriter
4197 log_name
4198 \family default
4199 .
4200 \layout List
4201 \labelwidthstring 00.00.0000
4202
4203
4204 \family typewriter
4205 append
4206 \family default
4207 : well, that says it.
4208 \layout List
4209 \labelwidthstring 00.00.0000
4210
4211
4212 \family typewriter
4213 rotate
4214 \family default
4215 : create rotating logs
4216 \family typewriter
4217 log_name
4218 \family default
4219 .
4220 \family typewriter
4221 1~
4222 \family default
4223 ,
4224 \family typewriter
4225 log_name.2~
4226 \family default
4227 , etc.
4228 \layout Standard
4229
4230 The
4231 \family typewriter
4232 %logoff
4233 \family default
4234 and
4235 \family typewriter
4236 %logon
4237 \family default
4238 functions allow you to temporarily stop and resume logging to a file which
4239 had previously been started with
4240 \family typewriter
4241 %logstart
4242 \family default
4243 .
4244 They will fail (with an explanation) if you try to use them before logging
4245 has been started.
4246 \layout Subsection
4247
4248
4249 \begin_inset LatexCommand \label{sub:System-shell-access}
4250
4251 \end_inset
4252
4253 System shell access
4254 \layout Standard
4255
4256 Any input line beginning with a
4257 \family typewriter
4258 !
4259 \family default
4260 character is passed verbatim (minus the
4261 \family typewriter
4262 !
4263 \family default
4264 , of course) to the underlying operating system.
4265 For example, typing
4266 \family typewriter
4267 !ls
4268 \family default
4269 will run
4270 \family typewriter
4271 'ls'
4272 \family default
4273 in the current directory.
4274 \layout Subsubsection
4275
4276 Manual capture of command output
4277 \layout Standard
4278
4279 If the input line begins with
4280 \emph on
4281 two
4282 \emph default
4283 exclamation marks,
4284 \family typewriter
4285 !!
4286 \family default
4287 , the command is executed but its output is captured and returned as a python
4288 list, split on newlines.
4289 Any output sent by the subprocess to standard error is printed separately,
4290 so that the resulting list only captures standard output.
4291 The
4292 \family typewriter
4293 !!
4294 \family default
4295 syntax is a shorthand for the
4296 \family typewriter
4297 %sx
4298 \family default
4299 magic command.
4300 \layout Standard
4301
4302 Finally, the
4303 \family typewriter
4304 %sc
4305 \family default
4306 magic (short for `shell capture') is similar to
4307 \family typewriter
4308 %sx
4309 \family default
4310 , but allowing more fine-grained control of the capture details, and storing
4311 the result directly into a named variable.
4312 \layout Standard
4313
4314 See Sec.\SpecialChar ~
4315
4316 \begin_inset LatexCommand \ref{sec:magic}
4317
4318 \end_inset
4319
4320 for details on the magics
4321 \family typewriter
4322 %sc
4323 \family default
4324 and
4325 \family typewriter
4326 %sx
4327 \family default
4328 , or use IPython's own help (
4329 \family typewriter
4330 sc?
4331 \family default
4332 and
4333 \family typewriter
4334 sx?
4335 \family default
4336 ) for further details.
4337 \layout Standard
4338
4339 IPython also allows you to expand the value of python variables when making
4340 system calls.
4341 Any python variable or expression which you prepend with
4342 \family typewriter
4343 $
4344 \family default
4345 will get expanded before the system call is made.
4346
4347 \layout Standard
4348
4349
4350 \family typewriter
4351 In [1]: pyvar='Hello world'
4352 \newline
4353 In [2]: !echo "A python variable: $pyvar"
4354 \newline
4355 A python variable: Hello world
4356 \layout Standard
4357
4358 If you want the shell to actually see a literal
4359 \family typewriter
4360 $
4361 \family default
4362 , you need to type it twice:
4363 \layout Standard
4364
4365
4366 \family typewriter
4367 In [3]: !echo "A system variable: $$HOME"
4368 \newline
4369 A system variable: /home/fperez
4370 \layout Standard
4371
4372 You can pass arbitrary expressions, though you'll need to delimit them with
4373
4374 \family typewriter
4375 {}
4376 \family default
4377 if there is ambiguity as to the extent of the expression:
4378 \layout Standard
4379
4380
4381 \family typewriter
4382 In [5]: x=10
4383 \newline
4384 In [6]: y=20
4385 \newline
4386 In [13]: !echo $x+y
4387 \newline
4388 10+y
4389 \newline
4390 In [7]: !echo ${x+y}
4391 \newline
4392 30
4393 \layout Standard
4394
4395 Even object attributes can be expanded:
4396 \layout Standard
4397
4398
4399 \family typewriter
4400 In [12]: !echo $sys.argv
4401 \newline
4402 [/home/fperez/usr/bin/ipython]
4403 \layout Subsection
4404
4405 System command aliases
4406 \layout Standard
4407
4408 The
4409 \family typewriter
4410 %alias
4411 \family default
4412 magic function and the
4413 \family typewriter
4414 alias
4415 \family default
4416 option in the
4417 \family typewriter
4418 ipythonrc
4419 \family default
4420 configuration file allow you to define magic functions which are in fact
4421 system shell commands.
4422 These aliases can have parameters.
4423
4424 \layout Standard
4425
4426 '
4427 \family typewriter
4428 %alias alias_name cmd
4429 \family default
4430 ' defines '
4431 \family typewriter
4432 alias_name
4433 \family default
4434 ' as an alias for '
4435 \family typewriter
4436 cmd
4437 \family default
4438 '
4439 \layout Standard
4440
4441 Then, typing '
4442 \family typewriter
4443 %alias_name params
4444 \family default
4445 ' will execute the system command '
4446 \family typewriter
4447 cmd params
4448 \family default
4449 ' (from your underlying operating system).
4450
4451 \layout Standard
4452
4453 You can also define aliases with parameters using
4454 \family typewriter
4455 %s
4456 \family default
4457 specifiers (one per parameter).
4458 The following example defines the
4459 \family typewriter
4460 %parts
4461 \family default
4462 function as an alias to the command '
4463 \family typewriter
4464 echo first %s second %s
4465 \family default
4466 ' where each
4467 \family typewriter
4468 %s
4469 \family default
4470 will be replaced by a positional parameter to the call to
4471 \family typewriter
4472 %parts:
4473 \layout Standard
4474
4475
4476 \family typewriter
4477 In [1]: alias parts echo first %s second %s
4478 \newline
4479 In [2]: %parts A B
4480 \newline
4481 first A second B
4482 \newline
4483 In [3]: %parts A
4484 \newline
4485 Incorrect number of arguments: 2 expected.
4486
4487 \newline
4488 parts is an alias to: 'echo first %s second %s'
4489 \layout Standard
4490
4491 If called with no parameters,
4492 \family typewriter
4493 %alias
4494 \family default
4495 prints the table of currently defined aliases.
4496 \layout Standard
4497
4498 The
4499 \family typewriter
4500 %rehash/rehashx
4501 \family default
4502 magics allow you to load your entire
4503 \family typewriter
4504 $PATH
4505 \family default
4506 as ipython aliases.
4507 See their respective docstrings (or sec.\SpecialChar ~
4508
4509 \begin_inset LatexCommand \ref{sec:magic}
4510
4511 \end_inset
4512
4513 for further details).
4514 \layout Subsection
4515
4516
4517 \begin_inset LatexCommand \label{sec:dreload}
4518
4519 \end_inset
4520
4521 Recursive reload
4522 \layout Standard
4523
4524 The
4525 \family typewriter
4526 %dreload
4527 \family default
4528 command does a recursive reload of a module: changes made to the module
4529 since you imported will actually be available without having to exit.
4530 \layout Subsection
4531
4532 Verbose and colored exception traceback printouts
4533 \layout Standard
4534
4535 IPython provides the option to see very detailed exception tracebacks, which
4536 can be especially useful when debugging large programs.
4537 You can run any Python file with the
4538 \family typewriter
4539 %run
4540 \family default
4541 function to benefit from these detailed tracebacks.
4542 Furthermore, both normal and verbose tracebacks can be colored (if your
4543 terminal supports it) which makes them much easier to parse visually.
4544 \layout Standard
4545
4546 See the magic
4547 \family typewriter
4548 xmode
4549 \family default
4550 and
4551 \family typewriter
4552 colors
4553 \family default
4554 functions for details (just type
4555 \family typewriter
4556 %magic
4557 \family default
4558 ).
4559 \layout Standard
4560
4561 These features are basically a terminal version of Ka-Ping Yee's
4562 \family typewriter
4563 cgitb
4564 \family default
4565 module, now part of the standard Python library.
4566 \layout Subsection
4567
4568
4569 \begin_inset LatexCommand \label{sec:cache_input}
4570
4571 \end_inset
4572
4573 Input caching system
4574 \layout Standard
4575
4576 IPython offers numbered prompts (In/Out) with input and output caching.
4577 All input is saved and can be retrieved as variables (besides the usual
4578 arrow key recall).
4579 \layout Standard
4580
4581 The following GLOBAL variables always exist (so don't overwrite them!):
4582
4583 \family typewriter
4584 _i
4585 \family default
4586 : stores previous input.
4587
4588 \family typewriter
4589 _ii
4590 \family default
4591 : next previous.
4592
4593 \family typewriter
4594 _iii
4595 \family default
4596 : next-next previous.
4597
4598 \family typewriter
4599 _ih
4600 \family default
4601 : a list of all input
4602 \family typewriter
4603 _ih[n]
4604 \family default
4605 is the input from line
4606 \family typewriter
4607 n
4608 \family default
4609 and this list is aliased to the global variable
4610 \family typewriter
4611 In
4612 \family default
4613 .
4614 If you overwrite
4615 \family typewriter
4616 In
4617 \family default
4618 with a variable of your own, you can remake the assignment to the internal
4619 list with a simple
4620 \family typewriter
4621 'In=_ih'
4622 \family default
4623 .
4624 \layout Standard
4625
4626 Additionally, global variables named
4627 \family typewriter
4628 _i<n>
4629 \family default
4630 are dynamically created (
4631 \family typewriter
4632 <n>
4633 \family default
4634 being the prompt counter), such that
4635 \newline
4636
4637 \family typewriter
4638 _i<n> == _ih[<n>] == In[<n>].
4639 \layout Standard
4640
4641 For example, what you typed at prompt 14 is available as
4642 \family typewriter
4643 _i14,
4644 \family default
4645
4646 \family typewriter
4647 _ih[14]
4648 \family default
4649 and
4650 \family typewriter
4651 In[14]
4652 \family default
4653 .
4654 \layout Standard
4655
4656 This allows you to easily cut and paste multi line interactive prompts by
4657 printing them out: they print like a clean string, without prompt characters.
4658 You can also manipulate them like regular variables (they are strings),
4659 modify or exec them (typing
4660 \family typewriter
4661 'exec _i9'
4662 \family default
4663 will re-execute the contents of input prompt 9, '
4664 \family typewriter
4665 exec In[9:14]+In[18]
4666 \family default
4667 ' will re-execute lines 9 through 13 and line 18).
4668 \layout Standard
4669
4670 You can also re-execute multiple lines of input easily by using the magic
4671
4672 \family typewriter
4673 %macro
4674 \family default
4675 function (which automates the process and allows re-execution without having
4676 to type '
4677 \family typewriter
4678 exec
4679 \family default
4680 ' every time).
4681 The macro system also allows you to re-execute previous lines which include
4682 magic function calls (which require special processing).
4683 Type
4684 \family typewriter
4685 %macro?
4686 \family default
4687 or see sec.
4688
4689 \begin_inset LatexCommand \ref{sec:magic}
4690
4691 \end_inset
4692
4693 for more details on the macro system.
4694 \layout Standard
4695
4696 A history function
4697 \family typewriter
4698 %hist
4699 \family default
4700 allows you to see any part of your input history by printing a range of
4701 the
4702 \family typewriter
4703 _i
4704 \family default
4705 variables.
4706 \layout Subsection
4707
4708
4709 \begin_inset LatexCommand \label{sec:cache_output}
4710
4711 \end_inset
4712
4713 Output caching system
4714 \layout Standard
4715
4716 For output that is returned from actions, a system similar to the input
4717 cache exists but using
4718 \family typewriter
4719 _
4720 \family default
4721 instead of
4722 \family typewriter
4723 _i
4724 \family default
4725 .
4726 Only actions that produce a result (NOT assignments, for example) are cached.
4727 If you are familiar with Mathematica, IPython's
4728 \family typewriter
4729 _
4730 \family default
4731 variables behave exactly like Mathematica's
4732 \family typewriter
4733 %
4734 \family default
4735 variables.
4736 \layout Standard
4737
4738 The following GLOBAL variables always exist (so don't overwrite them!):
4739
4740 \layout List
4741 \labelwidthstring 00.00.0000
4742
4743
4744 \family typewriter
4745 \series bold
4746 _
4747 \family default
4748 \series default
4749 (a
4750 \emph on
4751 single
4752 \emph default
4753 underscore) : stores previous output, like Python's default interpreter.
4754 \layout List
4755 \labelwidthstring 00.00.0000
4756
4757
4758 \family typewriter
4759 \series bold
4760 __
4761 \family default
4762 \series default
4763 (two underscores): next previous.
4764 \layout List
4765 \labelwidthstring 00.00.0000
4766
4767
4768 \family typewriter
4769 \series bold
4770 ___
4771 \family default
4772 \series default
4773 (three underscores): next-next previous.
4774 \layout Standard
4775
4776 Additionally, global variables named
4777 \family typewriter
4778 _<n>
4779 \family default
4780 are dynamically created (
4781 \family typewriter
4782 <n>
4783 \family default
4784 being the prompt counter), such that the result of output
4785 \family typewriter
4786 <n>
4787 \family default
4788 is always available as
4789 \family typewriter
4790 _<n>
4791 \family default
4792 (don't use the angle brackets, just the number, e.g.
4793
4794 \family typewriter
4795 _21
4796 \family default
4797 ).
4798 \layout Standard
4799
4800 These global variables are all stored in a global dictionary (not a list,
4801 since it only has entries for lines which returned a result) available
4802 under the names
4803 \family typewriter
4804 _oh
4805 \family default
4806 and
4807 \family typewriter
4808 Out
4809 \family default
4810 (similar to
4811 \family typewriter
4812 _ih
4813 \family default
4814 and
4815 \family typewriter
4816 In
4817 \family default
4818 ).
4819 So the output from line 12 can be obtained as
4820 \family typewriter
4821 _12
4822 \family default
4823 ,
4824 \family typewriter
4825 Out[12]
4826 \family default
4827 or
4828 \family typewriter
4829 _oh[12]
4830 \family default
4831 .
4832 If you accidentally overwrite the
4833 \family typewriter
4834 Out
4835 \family default
4836 variable you can recover it by typing
4837 \family typewriter
4838 'Out=_oh
4839 \family default
4840 ' at the prompt.
4841 \layout Standard
4842
4843 This system obviously can potentially put heavy memory demands on your system,
4844 since it prevents Python's garbage collector from removing any previously
4845 computed results.
4846 You can control how many results are kept in memory with the option (at
4847 the command line or in your
4848 \family typewriter
4849 ipythonrc
4850 \family default
4851 file)
4852 \family typewriter
4853 cache_size
4854 \family default
4855 .
4856 If you set it to 0, the whole system is completely disabled and the prompts
4857 revert to the classic
4858 \family typewriter
4859 '>>>'
4860 \family default
4861 of normal Python.
4862 \layout Subsection
4863
4864 Directory history
4865 \layout Standard
4866
4867 Your history of visited directories is kept in the global list
4868 \family typewriter
4869 _dh
4870 \family default
4871 , and the magic
4872 \family typewriter
4873 %cd
4874 \family default
4875 command can be used to go to any entry in that list.
4876 The
4877 \family typewriter
4878 %dhist
4879 \family default
4880 command allows you to view this history.
4881 \layout Subsection
4882
4883 Automatic parentheses and quotes
4884 \layout Standard
4885
4886 These features were adapted from Nathan Gray's LazyPython.
4887 They are meant to allow less typing for common situations.
4888 \layout Subsubsection
4889
4890 Automatic parentheses
4891 \layout Standard
4892
4893 Callable objects (i.e.
4894 functions, methods, etc) can be invoked like this (notice the commas between
4895 the arguments):
4896 \layout Standard
4897
4898
4899 \family typewriter
4900 >>> callable_ob arg1, arg2, arg3
4901 \layout Standard
4902
4903 and the input will be translated to this:
4904 \layout Standard
4905
4906
4907 \family typewriter
4908 --> callable_ob(arg1, arg2, arg3)
4909 \layout Standard
4910
4911 You can force automatic parentheses by using '/' as the first character
4912 of a line.
4913 For example:
4914 \layout Standard
4915
4916
4917 \family typewriter
4918 >>> /globals # becomes 'globals()'
4919 \layout Standard
4920
4921 Note that the '/' MUST be the first character on the line! This won't work:
4922
4923 \layout Standard
4924
4925
4926 \family typewriter
4927 >>> print /globals # syntax error
4928 \layout Standard
4929
4930 In most cases the automatic algorithm should work, so you should rarely
4931 need to explicitly invoke /.
4932 One notable exception is if you are trying to call a function with a list
4933 of tuples as arguments (the parenthesis will confuse IPython):
4934 \layout Standard
4935
4936
4937 \family typewriter
4938 In [1]: zip (1,2,3),(4,5,6) # won't work
4939 \layout Standard
4940
4941 but this will work:
4942 \layout Standard
4943
4944
4945 \family typewriter
4946 In [2]: /zip (1,2,3),(4,5,6)
4947 \newline
4948 ------> zip ((1,2,3),(4,5,6))
4949 \newline
4950 Out[2]= [(1, 4), (2, 5), (3, 6)]
4951 \layout Standard
4952
4953 IPython tells you that it has altered your command line by displaying the
4954 new command line preceded by
4955 \family typewriter
4956 -->
4957 \family default
4958 .
4959 e.g.:
4960 \layout Standard
4961
4962
4963 \family typewriter
4964 In [18]: callable list
4965 \newline
4966 -------> callable (list)
4967 \layout Subsubsection
4968
4969 Automatic quoting
4970 \layout Standard
4971
4972 You can force automatic quoting of a function's arguments by using
4973 \family typewriter
4974 `,'
4975 \family default
4976 or
4977 \family typewriter
4978 `;'
4979 \family default
4980 as the first character of a line.
4981 For example:
4982 \layout Standard
4983
4984
4985 \family typewriter
4986 >>> ,my_function /home/me # becomes my_function("/home/me")
4987 \layout Standard
4988
4989 If you use
4990 \family typewriter
4991 `;'
4992 \family default
4993 instead, the whole argument is quoted as a single string (while
4994 \family typewriter
4995 `,'
4996 \family default
4997 splits on whitespace):
4998 \layout Standard
4999
5000
5001 \family typewriter
5002 >>> ,my_function a b c # becomes my_function("a","b","c")
5003 \layout Standard
5004
5005
5006 \family typewriter
5007 >>> ;my_function a b c # becomes my_function("a b c")
5008 \layout Standard
5009
5010 Note that the `
5011 \family typewriter
5012 ,
5013 \family default
5014 ' or `
5015 \family typewriter
5016 ;
5017 \family default
5018 ' MUST be the first character on the line! This won't work:
5019 \layout Standard
5020
5021
5022 \family typewriter
5023 >>> x = ,my_function /home/me # syntax error
5024 \layout Section
5025
5026
5027 \begin_inset LatexCommand \label{sec:customization}
5028
5029 \end_inset
5030
5031 Customization
5032 \layout Standard
5033
5034 As we've already mentioned, IPython reads a configuration file which can
5035 be specified at the command line (
5036 \family typewriter
5037 -rcfile
5038 \family default
5039 ) or which by default is assumed to be called
5040 \family typewriter
5041 ipythonrc
5042 \family default
5043 .
5044 Such a file is looked for in the current directory where IPython is started
5045 and then in your
5046 \family typewriter
5047 IPYTHONDIR
5048 \family default
5049 , which allows you to have local configuration files for specific projects.
5050 In this section we will call these types of configuration files simply
5051 rcfiles (short for resource configuration file).
5052 \layout Standard
5053
5054 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5055 one per line.
5056 Lines beginning with a
5057 \family typewriter
5058 #
5059 \family default
5060 are ignored as comments, but comments can
5061 \series bold
5062 not
5063 \series default
5064 be put on lines with data (the parser is fairly primitive).
5065 Note that these are not python files, and this is deliberate, because it
5066 allows us to do some things which would be quite tricky to implement if
5067 they were normal python files.
5068 \layout Standard
5069
5070 First, an rcfile can contain permanent default values for almost all command
5071 line options (except things like
5072 \family typewriter
5073 -help
5074 \family default
5075 or
5076 \family typewriter
5077 -Version
5078 \family default
5079 ).
5080 Sec\SpecialChar ~
5081
5082 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5083
5084 \end_inset
5085
5086 contains a description of all command-line options.
5087 However, values you explicitly specify at the command line override the
5088 values defined in the rcfile.
5089 \layout Standard
5090
5091 Besides command line option values, the rcfile can specify values for certain
5092 extra special options which are not available at the command line.
5093 These options are briefly described below.
5094
5095 \layout Standard
5096
5097 Each of these options may appear as many times as you need it in the file.
5098 \layout List
5099 \labelwidthstring 00.00.0000
5100
5101
5102 \family typewriter
5103 \series bold
5104 include\SpecialChar ~
5105 <file1>\SpecialChar ~
5106 <file2>\SpecialChar ~
5107 ...
5108 \family default
5109 \series default
5110 : you can name
5111 \emph on
5112 other
5113 \emph default
5114 rcfiles you want to recursively load up to 15 levels (don't use the
5115 \family typewriter
5116 <>
5117 \family default
5118 brackets in your names!).
5119 This feature allows you to define a 'base' rcfile with general options
5120 and special-purpose files which can be loaded only when needed with particular
5121 configuration options.
5122 To make this more convenient, IPython accepts the
5123 \family typewriter
5124 -profile <name>
5125 \family default
5126 option (abbreviates to
5127 \family typewriter
5128 -p <name
5129 \family default
5130 >)
5131 \family typewriter
5132 which
5133 \family default
5134 tells it to look for an rcfile named
5135 \family typewriter
5136 ipythonrc-<name>
5137 \family default
5138 .
5139
5140 \layout List
5141 \labelwidthstring 00.00.0000
5142
5143
5144 \family typewriter
5145 \series bold
5146 import_mod\SpecialChar ~
5147 <mod1>\SpecialChar ~
5148 <mod2>\SpecialChar ~
5149 ...
5150 \family default
5151 \series default
5152 : import modules with '
5153 \family typewriter
5154 import
5155 \family default
5156
5157 \family typewriter
5158 <mod1>,<mod2>,...
5159 \family default
5160 '
5161 \layout List
5162 \labelwidthstring 00.00.0000
5163
5164
5165 \family typewriter
5166 \series bold
5167 import_some\SpecialChar ~
5168 <mod>\SpecialChar ~
5169 <f1>\SpecialChar ~
5170 <f2>\SpecialChar ~
5171 ...
5172 \family default
5173 \series default
5174 : import functions with '
5175 \family typewriter
5176 from <mod> import
5177 \family default
5178
5179 \family typewriter
5180 <f1>,<f2>,...
5181 \family default
5182 '
5183 \layout List
5184 \labelwidthstring 00.00.0000
5185
5186
5187 \family typewriter
5188 \series bold
5189 import_all\SpecialChar ~
5190 <mod1>\SpecialChar ~
5191 <mod2>\SpecialChar ~
5192 ...
5193 \family default
5194 \series default
5195 : for each module listed import functions with '
5196 \family typewriter
5197 from <mod> import *
5198 \family default
5199 '
5200 \layout List
5201 \labelwidthstring 00.00.0000
5202
5203
5204 \family typewriter
5205 \series bold
5206 execute\SpecialChar ~
5207 <python\SpecialChar ~
5208 code>
5209 \family default
5210 \series default
5211 : give any single-line python code to be executed.
5212 \layout List
5213 \labelwidthstring 00.00.0000
5214
5215
5216 \family typewriter
5217 \series bold
5218 execfile\SpecialChar ~
5219 <filename>
5220 \family default
5221 \series default
5222 : execute the python file given with an '
5223 \family typewriter
5224 execfile(filename)
5225 \family default
5226 ' command.
5227 Username expansion is performed on the given names.
5228 So if you need any amount of extra fancy customization that won't fit in
5229 any of the above 'canned' options, you can just put it in a separate python
5230 file and execute it.
5231 \layout List
5232 \labelwidthstring 00.00.0000
5233
5234
5235 \family typewriter
5236 \series bold
5237 alias\SpecialChar ~
5238 <alias_def>
5239 \family default
5240 \series default
5241 : this is equivalent to calling '
5242 \family typewriter
5243 %alias\SpecialChar ~
5244 <alias_def>
5245 \family default
5246 ' at the IPython command line.
5247 This way, from within IPython you can do common system tasks without having
5248 to exit it or use the
5249 \family typewriter
5250 !
5251 \family default
5252 escape.
5253 IPython isn't meant to be a shell replacement, but it is often very useful
5254 to be able to do things with files while testing code.
5255 This gives you the flexibility to have within IPython any aliases you may
5256 be used to under your normal system shell.
5257 \layout Subsection
5258
5259
5260 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5261
5262 \end_inset
5263
5264 Sample
5265 \family typewriter
5266 ipythonrc
5267 \family default
5268 file
5269 \layout Standard
5270
5271 The default rcfile, called
5272 \family typewriter
5273 ipythonrc
5274 \family default
5275 and supplied in your
5276 \family typewriter
5277 IPYTHONDIR
5278 \family default
5279 directory contains lots of comments on all of these options.
5280 We reproduce it here for reference:
5281 \layout Standard
5282
5283
5284 \begin_inset Include \verbatiminput{../IPython/UserConfig/ipythonrc}
5285 preview false
5286
5287 \end_inset
5288
5289
5290 \layout Subsection
5291
5292
5293 \begin_inset LatexCommand \label{sec:prompts}
5294
5295 \end_inset
5296
5297 Fine-tuning your prompt
5298 \layout Standard
5299
5300 IPython's prompts can be customized using a syntax similar to that of the
5301
5302 \family typewriter
5303 bash
5304 \family default
5305 shell.
5306 Many of
5307 \family typewriter
5308 bash
5309 \family default
5310 's escapes are supported, as well as a few additional ones.
5311 We list them below:
5312 \layout Description
5313
5314
5315 \backslash
5316 # the prompt/history count number
5317 \layout Description
5318
5319
5320 \backslash
5321 D the prompt/history count, with the actual digits replaced by dots.
5322 Used mainly in continuation prompts (prompt_in2)
5323 \layout Description
5324
5325
5326 \backslash
5327 w the current working directory
5328 \layout Description
5329
5330
5331 \backslash
5332 W the basename of current working directory
5333 \layout Description
5334
5335
5336 \backslash
5337 X
5338 \emph on
5339 n
5340 \emph default
5341 where
5342 \begin_inset Formula $n=0\ldots5.$
5343 \end_inset
5344
5345 The current working directory, with
5346 \family typewriter
5347 $HOME
5348 \family default
5349 replaced by
5350 \family typewriter
5351 ~
5352 \family default
5353 , and filtered out to contain only
5354 \begin_inset Formula $n$
5355 \end_inset
5356
5357 path elements
5358 \layout Description
5359
5360
5361 \backslash
5362 Y
5363 \emph on
5364 n
5365 \emph default
5366 Similar to
5367 \backslash
5368 X
5369 \emph on
5370 n
5371 \emph default
5372 , but with the
5373 \begin_inset Formula $n+1$
5374 \end_inset
5375
5376 element included if it is
5377 \family typewriter
5378 ~
5379 \family default
5380 (this is similar to the behavior of the %c
5381 \emph on
5382 n
5383 \emph default
5384 escapes in
5385 \family typewriter
5386 tcsh
5387 \family default
5388 )
5389 \layout Description
5390
5391
5392 \backslash
5393 u the username of the current user
5394 \layout Description
5395
5396
5397 \backslash
5398 $ if the effective UID is 0, a #, otherwise a $
5399 \layout Description
5400
5401
5402 \backslash
5403 h the hostname up to the first `.'
5404 \layout Description
5405
5406
5407 \backslash
5408 H the hostname
5409 \layout Description
5410
5411
5412 \backslash
5413 n a newline
5414 \layout Description
5415
5416
5417 \backslash
5418 r a carriage return
5419 \layout Description
5420
5421
5422 \backslash
5423 v IPython version string
5424 \layout Standard
5425
5426 In addition to these, ANSI color escapes can be insterted into the prompts,
5427 as
5428 \family typewriter
5429
5430 \backslash
5431 C_
5432 \emph on
5433 ColorName
5434 \family default
5435 \emph default
5436 .
5437 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5438 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5439 Normal, Purple, Red, White, Yellow.
5440 \layout Standard
5441
5442 Finally, IPython supports the evaluation of arbitrary expressions in your
5443 prompt string.
5444 The prompt strings are evaluated through the syntax of PEP 215, but basically
5445 you can use
5446 \family typewriter
5447 $x.y
5448 \family default
5449 to expand the value of
5450 \family typewriter
5451 x.y
5452 \family default
5453 , and for more complicated expressions you can use braces:
5454 \family typewriter
5455 ${foo()+x}
5456 \family default
5457 will call function
5458 \family typewriter
5459 foo
5460 \family default
5461 and add to it the value of
5462 \family typewriter
5463 x
5464 \family default
5465 , before putting the result into your prompt.
5466 For example, using
5467 \newline
5468
5469 \family typewriter
5470 prompt_in1 '${commands.getoutput("uptime")}
5471 \backslash
5472 nIn [
5473 \backslash
5474 #]: '
5475 \newline
5476
5477 \family default
5478 will print the result of the uptime command on each prompt (assuming the
5479
5480 \family typewriter
5481 commands
5482 \family default
5483 module has been imported in your
5484 \family typewriter
5485 ipythonrc
5486 \family default
5487 file).
5488 \layout Subsubsection
5489
5490 Prompt examples
5491 \layout Standard
5492
5493 The following options in an ipythonrc file will give you IPython's default
5494 prompts:
5495 \layout Standard
5496
5497
5498 \family typewriter
5499 prompt_in1 'In [
5500 \backslash
5501 #]:'
5502 \newline
5503 prompt_in2 '\SpecialChar ~
5504 \SpecialChar ~
5505 \SpecialChar ~
5506 .
5507 \backslash
5508 D.:'
5509 \newline
5510 prompt_out 'Out[
5511 \backslash
5512 #]:'
5513 \layout Standard
5514
5515 which look like this:
5516 \layout Standard
5517
5518
5519 \family typewriter
5520 In [1]: 1+2
5521 \newline
5522 Out[1]: 3
5523 \layout Standard
5524
5525
5526 \family typewriter
5527 In [2]: for i in (1,2,3):
5528 \newline
5529
5530 \begin_inset ERT
5531 status Collapsed
5532
5533 \layout Standard
5534
5535 \backslash
5536 hspace*{0mm}
5537 \end_inset
5538
5539 \SpecialChar ~
5540 \SpecialChar ~
5541 \SpecialChar ~
5542 ...: \SpecialChar ~
5543 \SpecialChar ~
5544 \SpecialChar ~
5545 \SpecialChar ~
5546 print i,
5547 \newline
5548
5549 \begin_inset ERT
5550 status Collapsed
5551
5552 \layout Standard
5553
5554 \backslash
5555 hspace*{0mm}
5556 \end_inset
5557
5558 \SpecialChar ~
5559 \SpecialChar ~
5560 \SpecialChar ~
5561 ...:
5562 \newline
5563 1 2 3
5564 \layout Standard
5565
5566 These will give you a very colorful prompt with path information:
5567 \layout Standard
5568
5569
5570 \family typewriter
5571 #prompt_in1 '
5572 \backslash
5573 C_Red
5574 \backslash
5575 u
5576 \backslash
5577 C_Blue[
5578 \backslash
5579 C_Cyan
5580 \backslash
5581 Y1
5582 \backslash
5583 C_Blue]
5584 \backslash
5585 C_LightGreen
5586 \backslash
5587 #>'
5588 \newline
5589 prompt_in2 ' ..
5590 \backslash
5591 D>'
5592 \newline
5593 prompt_out '<
5594 \backslash
5595 #>'
5596 \layout Standard
5597
5598 which look like this:
5599 \layout Standard
5600
5601
5602 \family typewriter
5603 \color red
5604 fperez
5605 \color blue
5606 [
5607 \color cyan
5608 ~/ipython
5609 \color blue
5610 ]
5611 \color green
5612 1>
5613 \color default
5614 1+2
5615 \newline
5616
5617 \begin_inset ERT
5618 status Collapsed
5619
5620 \layout Standard
5621
5622 \backslash
5623 hspace*{0mm}
5624 \end_inset
5625
5626 \SpecialChar ~
5627 \SpecialChar ~
5628 \SpecialChar ~
5629 \SpecialChar ~
5630 \SpecialChar ~
5631 \SpecialChar ~
5632 \SpecialChar ~
5633 \SpecialChar ~
5634 \SpecialChar ~
5635 \SpecialChar ~
5636 \SpecialChar ~
5637 \SpecialChar ~
5638 \SpecialChar ~
5639 \SpecialChar ~
5640 \SpecialChar ~
5641 \SpecialChar ~
5642
5643 \color red
5644 <1>
5645 \color default
5646 3
5647 \newline
5648
5649 \color red
5650 fperez
5651 \color blue
5652 [
5653 \color cyan
5654 ~/ipython
5655 \color blue
5656 ]
5657 \color green
5658 2>
5659 \color default
5660 for i in (1,2,3):
5661 \newline
5662
5663 \begin_inset ERT
5664 status Collapsed
5665
5666 \layout Standard
5667
5668 \backslash
5669 hspace*{0mm}
5670 \end_inset
5671
5672 \SpecialChar ~
5673 \SpecialChar ~
5674 \SpecialChar ~
5675 \SpecialChar ~
5676 \SpecialChar ~
5677 \SpecialChar ~
5678 \SpecialChar ~
5679 \SpecialChar ~
5680 \SpecialChar ~
5681 \SpecialChar ~
5682 \SpecialChar ~
5683 \SpecialChar ~
5684 \SpecialChar ~
5685 \SpecialChar ~
5686 \SpecialChar ~
5687
5688 \color green
5689 ...>
5690 \color default
5691 \SpecialChar ~
5692 \SpecialChar ~
5693 \SpecialChar ~
5694 \SpecialChar ~
5695 print i,
5696 \newline
5697
5698 \begin_inset ERT
5699 status Collapsed
5700
5701 \layout Standard
5702
5703 \backslash
5704 hspace*{0mm}
5705 \end_inset
5706
5707 \SpecialChar ~
5708 \SpecialChar ~
5709 \SpecialChar ~
5710 \SpecialChar ~
5711 \SpecialChar ~
5712 \SpecialChar ~
5713 \SpecialChar ~
5714 \SpecialChar ~
5715 \SpecialChar ~
5716 \SpecialChar ~
5717 \SpecialChar ~
5718 \SpecialChar ~
5719 \SpecialChar ~
5720 \SpecialChar ~
5721 \SpecialChar ~
5722
5723 \color green
5724 ...>
5725 \color default
5726
5727 \newline
5728 1 2 3
5729 \layout Standard
5730
5731 The following shows the usage of dynamic expression evaluation:
5732 \layout Subsection
5733
5734
5735 \begin_inset LatexCommand \label{sec:profiles}
5736
5737 \end_inset
5738
5739 IPython profiles
5740 \layout Standard
5741
5742 As we already mentioned, IPython supports the
5743 \family typewriter
5744 -profile
5745 \family default
5746 command-line option (see sec.
5747
5748 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5749
5750 \end_inset
5751
5752 ).
5753 A profile is nothing more than a particular configuration file like your
5754 basic
5755 \family typewriter
5756 ipythonrc
5757 \family default
5758 one, but with particular customizations for a specific purpose.
5759 When you start IPython with '
5760 \family typewriter
5761 ipython -profile <name>
5762 \family default
5763 ', it assumes that in your
5764 \family typewriter
5765 IPYTHONDIR
5766 \family default
5767 there is a file called
5768 \family typewriter
5769 ipythonrc-<name>
5770 \family default
5771 , and loads it instead of the normal
5772 \family typewriter
5773 ipythonrc
5774 \family default
5775 .
5776 \layout Standard
5777
5778 This system allows you to maintain multiple configurations which load modules,
5779 set options, define functions, etc.
5780 suitable for different tasks and activate them in a very simple manner.
5781 In order to avoid having to repeat all of your basic options (common things
5782 that don't change such as your color preferences, for example), any profile
5783 can include another configuration file.
5784 The most common way to use profiles is then to have each one include your
5785 basic
5786 \family typewriter
5787 ipythonrc
5788 \family default
5789 file as a starting point, and then add further customizations.
5790 \layout Standard
5791
5792 In sections
5793 \begin_inset LatexCommand \ref{sec:syntax-extensions}
5794
5795 \end_inset
5796
5797 and
5798 \begin_inset LatexCommand \ref{sec:Gnuplot}
5799
5800 \end_inset
5801
5802 we discuss some particular profiles which come as part of the standard
5803 IPython distribution.
5804 You may also look in your
5805 \family typewriter
5806 IPYTHONDIR
5807 \family default
5808 directory, any file whose name begins with
5809 \family typewriter
5810 ipythonrc-
5811 \family default
5812 is a profile.
5813 You can use those as examples for further customizations to suit your own
5814 needs.
5815 \layout Section
5816
5817
5818 \begin_inset OptArg
5819 collapsed false
5820
5821 \layout Standard
5822
5823 IPython as default...
5824 \end_inset
5825
5826 IPython as your default Python environment
5827 \layout Standard
5828
5829 Python honors the environment variable
5830 \family typewriter
5831 PYTHONSTARTUP
5832 \family default
5833 and will execute at startup the file referenced by this variable.
5834 If you put at the end of this file the following two lines of code:
5835 \layout Standard
5836
5837
5838 \family typewriter
5839 import IPython
5840 \newline
5841 IPython.Shell.IPShell().mainloop(sys_exit=1)
5842 \layout Standard
5843
5844 then IPython will be your working environment anytime you start Python.
5845 The
5846 \family typewriter
5847 sys_exit=1
5848 \family default
5849 is needed to have IPython issue a call to
5850 \family typewriter
5851 sys.exit()
5852 \family default
5853 when it finishes, otherwise you'll be back at the normal Python '
5854 \family typewriter
5855 >>>
5856 \family default
5857 ' prompt
5858 \begin_inset Foot
5859 collapsed true
5860
5861 \layout Standard
5862
5863 Based on an idea by Holger Krekel.
5864 \end_inset
5865
5866 .
5867 \layout Standard
5868
5869 This is probably useful to developers who manage multiple Python versions
5870 and don't want to have correspondingly multiple IPython versions.
5871 Note that in this mode, there is no way to pass IPython any command-line
5872 options, as those are trapped first by Python itself.
5873 \layout Section
5874
5875
5876 \begin_inset LatexCommand \label{sec:embed}
5877
5878 \end_inset
5879
5880 Embedding IPython
5881 \layout Standard
5882
5883 It is possible to start an IPython instance
5884 \emph on
5885 inside
5886 \emph default
5887 your own Python programs.
5888 This allows you to evaluate dynamically the state of your code, operate
5889 with your variables, analyze them, etc.
5890 Note however that any changes you make to values while in the shell do
5891
5892 \emph on
5893 not
5894 \emph default
5895 propagate back to the running code, so it is safe to modify your values
5896 because you won't break your code in bizarre ways by doing so.
5897 \layout Standard
5898
5899 This feature allows you to easily have a fully functional python environment
5900 for doing object introspection anywhere in your code with a simple function
5901 call.
5902 In some cases a simple print statement is enough, but if you need to do
5903 more detailed analysis of a code fragment this feature can be very valuable.
5904 \layout Standard
5905
5906 It can also be useful in scientific computing situations where it is common
5907 to need to do some automatic, computationally intensive part and then stop
5908 to look at data, plots, etc
5909 \begin_inset Foot
5910 collapsed true
5911
5912 \layout Standard
5913
5914 This functionality was inspired by IDL's combination of the
5915 \family typewriter
5916 stop
5917 \family default
5918 keyword and the
5919 \family typewriter
5920 .continue
5921 \family default
5922 executive command, which I have found very useful in the past, and by a
5923 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
5924 06/01 concerning similar uses of pyrepl.
5925 \end_inset
5926
5927 .
5928 Opening an IPython instance will give you full access to your data and
5929 functions, and you can resume program execution once you are done with
5930 the interactive part (perhaps to stop again later, as many times as needed).
5931 \layout Standard
5932
5933 The following code snippet is the bare minimum you need to include in your
5934 Python programs for this to work (detailed examples follow later):
5935 \layout LyX-Code
5936
5937 from IPython.Shell import IPShellEmbed
5938 \layout LyX-Code
5939
5940 ipshell = IPShellEmbed()
5941 \layout LyX-Code
5942
5943 ipshell() # this call anywhere in your program will start IPython
5944 \layout Standard
5945
5946 You can run embedded instances even in code which is itself being run at
5947 the IPython interactive prompt with '
5948 \family typewriter
5949 %run\SpecialChar ~
5950 <filename>
5951 \family default
5952 '.
5953 Since it's easy to get lost as to where you are (in your top-level IPython
5954 or in your embedded one), it's a good idea in such cases to set the in/out
5955 prompts to something different for the embedded instances.
5956 The code examples below illustrate this.
5957 \layout Standard
5958
5959 You can also have multiple IPython instances in your program and open them
5960 separately, for example with different options for data presentation.
5961 If you close and open the same instance multiple times, its prompt counters
5962 simply continue from each execution to the next.
5963 \layout Standard
5964
5965 Please look at the docstrings in the
5966 \family typewriter
5967 Shell.py
5968 \family default
5969 module for more details on the use of this system.
5970 \layout Standard
5971
5972 The following sample file illustrating how to use the embedding functionality
5973 is provided in the examples directory as
5974 \family typewriter
5975 example-embed.py
5976 \family default
5977 .
5978 It should be fairly self-explanatory:
5979 \layout Standard
5980
5981
5982 \begin_inset Include \verbatiminput{examples/example-embed.py}
5983 preview false
5984
5985 \end_inset
5986
5987
5988 \layout Standard
5989
5990 Once you understand how the system functions, you can use the following
5991 code fragments in your programs which are ready for cut and paste:
5992 \layout Standard
5993
5994
5995 \begin_inset Include \verbatiminput{examples/example-embed-short.py}
5996 preview false
5997
5998 \end_inset
5999
6000
6001 \layout Section
6002
6003
6004 \begin_inset LatexCommand \label{sec:using-pdb}
6005
6006 \end_inset
6007
6008 Using the Python debugger (
6009 \family typewriter
6010 pdb
6011 \family default
6012 )
6013 \layout Subsection
6014
6015 Running entire programs via
6016 \family typewriter
6017 pdb
6018 \layout Standard
6019
6020
6021 \family typewriter
6022 pdb
6023 \family default
6024 , the Python debugger, is a powerful interactive debugger which allows you
6025 to step through code, set breakpoints, watch variables, etc.
6026 IPython makes it very easy to start any script under the control of
6027 \family typewriter
6028 pdb
6029 \family default
6030 , regardless of whether you have wrapped it into a
6031 \family typewriter
6032 `main()'
6033 \family default
6034 function or not.
6035 For this, simply type
6036 \family typewriter
6037 `%run -d myscript'
6038 \family default
6039 at an IPython prompt.
6040 See the
6041 \family typewriter
6042 %run
6043 \family default
6044 command's documentation (via
6045 \family typewriter
6046 `%run?'
6047 \family default
6048 or in Sec.\SpecialChar ~
6049
6050 \begin_inset LatexCommand \ref{sec:magic}
6051
6052 \end_inset
6053
6054 ) for more details, including how to control where
6055 \family typewriter
6056 pdb
6057 \family default
6058 will stop execution first.
6059 \layout Standard
6060
6061 For more information on the use of the
6062 \family typewriter
6063 pdb
6064 \family default
6065 debugger, read the included
6066 \family typewriter
6067 pdb.doc
6068 \family default
6069 file (part of the standard Python distribution).
6070 On a stock Linux system it is located at
6071 \family typewriter
6072 /usr/lib/python2.3/pdb.doc
6073 \family default
6074 , but the easiest way to read it is by using the
6075 \family typewriter
6076 help()
6077 \family default
6078 function of the
6079 \family typewriter
6080 pdb
6081 \family default
6082 module as follows (in an IPython prompt):
6083 \layout Standard
6084
6085
6086 \family typewriter
6087 In [1]: import pdb
6088 \newline
6089 In [2]: pdb.help()
6090 \layout Standard
6091
6092 This will load the
6093 \family typewriter
6094 pdb.doc
6095 \family default
6096 document in a file viewer for you automatically.
6097 \layout Subsection
6098
6099 Automatic invocation of
6100 \family typewriter
6101 pdb
6102 \family default
6103 on exceptions
6104 \layout Standard
6105
6106 IPython, if started with the
6107 \family typewriter
6108 -pdb
6109 \family default
6110 option (or if the option is set in your rc file) can call the Python
6111 \family typewriter
6112 pdb
6113 \family default
6114 debugger every time your code triggers an uncaught exception
6115 \begin_inset Foot
6116 collapsed true
6117
6118 \layout Standard
6119
6120 Many thanks to Christopher Hart for the request which prompted adding this
6121 feature to IPython.
6122 \end_inset
6123
6124 .
6125 This feature can also be toggled at any time with the
6126 \family typewriter
6127 %pdb
6128 \family default
6129 magic command.
6130 This can be extremely useful in order to find the origin of subtle bugs,
6131 because
6132 \family typewriter
6133 pdb
6134 \family default
6135 opens up at the point in your code which triggered the exception, and while
6136 your program is at this point `dead', all the data is still available and
6137 you can walk up and down the stack frame and understand the origin of the
6138 problem.
6139 \layout Standard
6140
6141 Furthermore, you can use these debugging facilities both with the embedded
6142 IPython mode and without IPython at all.
6143 For an embedded shell (see sec.
6144
6145 \begin_inset LatexCommand \ref{sec:embed}
6146
6147 \end_inset
6148
6149 ), simply call the constructor with
6150 \family typewriter
6151 `-pdb'
6152 \family default
6153 in the argument string and automatically
6154 \family typewriter
6155 pdb
6156 \family default
6157 will be called if an uncaught exception is triggered by your code.
6158
6159 \layout Standard
6160
6161 For stand-alone use of the feature in your programs which do not use IPython
6162 at all, put the following lines toward the top of your `main' routine:
6163 \layout Standard
6164 \align left
6165
6166 \family typewriter
6167 import sys,IPython.ultraTB
6168 \newline
6169 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6170 call_pdb=1)
6171 \layout Standard
6172
6173 The
6174 \family typewriter
6175 mode
6176 \family default
6177 keyword can be either
6178 \family typewriter
6179 `Verbose'
6180 \family default
6181 or
6182 \family typewriter
6183 `Plain'
6184 \family default
6185 , giving either very detailed or normal tracebacks respectively.
6186 The
6187 \family typewriter
6188 color_scheme
6189 \family default
6190 keyword can be one of
6191 \family typewriter
6192 `NoColor'
6193 \family default
6194 ,
6195 \family typewriter
6196 `Linux'
6197 \family default
6198 (default) or
6199 \family typewriter
6200 `LightBG'
6201 \family default
6202 .
6203 These are the same options which can be set in IPython with
6204 \family typewriter
6205 -colors
6206 \family default
6207 and
6208 \family typewriter
6209 -xmode
6210 \family default
6211 .
6212 \layout Standard
6213
6214 This will give any of your programs detailed, colored tracebacks with automatic
6215 invocation of
6216 \family typewriter
6217 pdb
6218 \family default
6219 .
6220 \layout Section
6221
6222
6223 \begin_inset LatexCommand \label{sec:syntax-extensions}
6224
6225 \end_inset
6226
6227 Extensions for syntax processing
6228 \layout Standard
6229
6230 This isn't for the faint of heart, because the potential for breaking things
6231 is quite high.
6232 But it can be a very powerful and useful feature.
6233 In a nutshell, you can redefine the way IPython processes the user input
6234 line to accept new, special extensions to the syntax without needing to
6235 change any of IPython's own code.
6236 \layout Standard
6237
6238 In the
6239 \family typewriter
6240 IPython/Extensions
6241 \family default
6242 directory you will find some examples supplied, which we will briefly describe
6243 now.
6244 These can be used `as is' (and both provide very useful functionality),
6245 or you can use them as a starting point for writing your own extensions.
6246 \layout Subsection
6247
6248 Pasting of code starting with
6249 \family typewriter
6250 `>>>
6251 \family default
6252 ' or
6253 \family typewriter
6254 `...
6255
6256 \family default
6257 '
6258 \layout Standard
6259
6260 In the python tutorial it is common to find code examples which have been
6261 taken from real python sessions.
6262 The problem with those is that all the lines begin with either
6263 \family typewriter
6264 `>>>
6265 \family default
6266 ' or
6267 \family typewriter
6268 `...
6269
6270 \family default
6271 ', which makes it impossible to paste them all at once.
6272 One must instead do a line by line manual copying, carefully removing the
6273 leading extraneous characters.
6274 \layout Standard
6275
6276 This extension identifies those starting characters and removes them from
6277 the input automatically, so that one can paste multi-line examples directly
6278 into IPython, saving a lot of time.
6279 Please look at the file
6280 \family typewriter
6281 InterpreterPasteInput.py
6282 \family default
6283 in the
6284 \family typewriter
6285 IPython/Extensions
6286 \family default
6287 directory for details on how this is done.
6288 \layout Standard
6289
6290 IPython comes with a special profile enabling this feature, called
6291 \family typewriter
6292 tutorial
6293 \family default
6294 \emph on
6295 .
6296
6297 \emph default
6298 Simply start IPython via
6299 \family typewriter
6300 `ipython\SpecialChar ~
6301 -p\SpecialChar ~
6302 tutorial'
6303 \family default
6304 and the feature will be available.
6305 In a normal IPython session you can activate the feature by importing the
6306 corresponding module with:
6307 \newline
6308
6309 \family typewriter
6310 In [1]: import IPython.Extensions.InterpreterPasteInput
6311 \layout Standard
6312
6313 The following is a 'screenshot' of how things work when this extension is
6314 on, copying an example from the standard tutorial:
6315 \layout Standard
6316
6317
6318 \family typewriter
6319 IPython profile: tutorial
6320 \newline
6321 \SpecialChar ~
6322
6323 \newline
6324 *** Pasting of code with ">>>" or "..." has been enabled.
6325 \newline
6326 \SpecialChar ~
6327
6328 \newline
6329 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6330 \newline
6331
6332 \begin_inset ERT
6333 status Collapsed
6334
6335 \layout Standard
6336
6337 \backslash
6338 hspace*{0mm}
6339 \end_inset
6340
6341 \SpecialChar ~
6342 \SpecialChar ~
6343 ...: ...\SpecialChar ~
6344 \SpecialChar ~
6345 \SpecialChar ~
6346 \SpecialChar ~
6347 """Return a list containing the Fibonacci series up to n."""
6348 \newline
6349
6350 \begin_inset ERT
6351 status Collapsed
6352
6353 \layout Standard
6354
6355 \backslash
6356 hspace*{0mm}
6357 \end_inset
6358
6359 \SpecialChar ~
6360 \SpecialChar ~
6361 ...: ...\SpecialChar ~
6362 \SpecialChar ~
6363 \SpecialChar ~
6364 \SpecialChar ~
6365 result = []
6366 \newline
6367
6368 \begin_inset ERT
6369 status Collapsed
6370
6371 \layout Standard
6372
6373 \backslash
6374 hspace*{0mm}
6375 \end_inset
6376
6377 \SpecialChar ~
6378 \SpecialChar ~
6379 ...: ...\SpecialChar ~
6380 \SpecialChar ~
6381 \SpecialChar ~
6382 \SpecialChar ~
6383 a, b = 0, 1
6384 \newline
6385
6386 \begin_inset ERT
6387 status Collapsed
6388
6389 \layout Standard
6390
6391 \backslash
6392 hspace*{0mm}
6393 \end_inset
6394
6395 \SpecialChar ~
6396 \SpecialChar ~
6397 ...: ...\SpecialChar ~
6398 \SpecialChar ~
6399 \SpecialChar ~
6400 \SpecialChar ~
6401 while b < n:
6402 \newline
6403
6404 \begin_inset ERT
6405 status Collapsed
6406
6407 \layout Standard
6408
6409 \backslash
6410 hspace*{0mm}
6411 \end_inset
6412
6413 \SpecialChar ~
6414 \SpecialChar ~
6415 ...: ...\SpecialChar ~
6416 \SpecialChar ~
6417 \SpecialChar ~
6418 \SpecialChar ~
6419 \SpecialChar ~
6420 \SpecialChar ~
6421 \SpecialChar ~
6422 \SpecialChar ~
6423 result.append(b)\SpecialChar ~
6424 \SpecialChar ~
6425 \SpecialChar ~
6426 # see below
6427 \newline
6428
6429 \begin_inset ERT
6430 status Collapsed
6431
6432 \layout Standard
6433
6434 \backslash
6435 hspace*{0mm}
6436 \end_inset
6437
6438 \SpecialChar ~
6439 \SpecialChar ~
6440 ...: ...\SpecialChar ~
6441 \SpecialChar ~
6442 \SpecialChar ~
6443 \SpecialChar ~
6444 \SpecialChar ~
6445 \SpecialChar ~
6446 \SpecialChar ~
6447 \SpecialChar ~
6448 a, b = b, a+b
6449 \newline
6450
6451 \begin_inset ERT
6452 status Collapsed
6453
6454 \layout Standard
6455
6456 \backslash
6457 hspace*{0mm}
6458 \end_inset
6459
6460 \SpecialChar ~
6461 \SpecialChar ~
6462 ...: ...\SpecialChar ~
6463 \SpecialChar ~
6464 \SpecialChar ~
6465 \SpecialChar ~
6466 return result
6467 \newline
6468
6469 \begin_inset ERT
6470 status Collapsed
6471
6472 \layout Standard
6473
6474 \backslash
6475 hspace*{0mm}
6476 \end_inset
6477
6478 \SpecialChar ~
6479 \SpecialChar ~
6480 ...:
6481 \newline
6482 \SpecialChar ~
6483
6484 \newline
6485 In [2]: fib2(10)
6486 \newline
6487 Out[2]: [1, 1, 2, 3, 5, 8]
6488 \layout Standard
6489
6490 Note that as currently written, this extension does
6491 \emph on
6492 not
6493 \emph default
6494 recognize IPython's prompts for pasting.
6495 Those are more complicated, since the user can change them very easily,
6496 they involve numbers and can vary in length.
6497 One could however extract all the relevant information from the IPython
6498 instance and build an appropriate regular expression.
6499 This is left as an exercise for the reader.
6500 \layout Subsection
6501
6502 Input of physical quantities with units
6503 \layout Standard
6504
6505 The module
6506 \family typewriter
6507 PhysicalQInput
6508 \family default
6509 allows a simplified form of input for physical quantities with units.
6510 This file is meant to be used in conjunction with the
6511 \family typewriter
6512 PhysicalQInteractive
6513 \family default
6514 module (in the same directory) and
6515 \family typewriter
6516 Physics.PhysicalQuantities
6517 \family default
6518 from Konrad Hinsen's ScientificPython (
6519 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
6520
6521 \end_inset
6522
6523 ).
6524 \layout Standard
6525
6526 The
6527 \family typewriter
6528 Physics.PhysicalQuantities
6529 \family default
6530 module defines
6531 \family typewriter
6532 PhysicalQuantity
6533 \family default
6534 objects, but these must be declared as instances of a class.
6535 For example, to define
6536 \family typewriter
6537 v
6538 \family default
6539 as a velocity of 3\SpecialChar ~
6540 m/s, normally you would write:
6541 \family typewriter
6542
6543 \newline
6544 In [1]: v = PhysicalQuantity(3,'m/s')
6545 \layout Standard
6546
6547 Using the
6548 \family typewriter
6549 PhysicalQ_Input
6550 \family default
6551 extension this can be input instead as:
6552 \family typewriter
6553
6554 \newline
6555 In [1]: v = 3 m/s
6556 \family default
6557
6558 \newline
6559 which is much more convenient for interactive use (even though it is blatantly
6560 invalid Python syntax).
6561 \layout Standard
6562
6563 The
6564 \family typewriter
6565 physics
6566 \family default
6567 profile supplied with IPython (enabled via
6568 \family typewriter
6569 'ipython -p physics'
6570 \family default
6571 ) uses these extensions, which you can also activate with:
6572 \layout Standard
6573
6574
6575 \family typewriter
6576 from math import * # math MUST be imported BEFORE PhysicalQInteractive
6577 \newline
6578 from IPython.Extensions.PhysicalQInteractive import *
6579 \newline
6580 import IPython.Extensions.PhysicalQInput
6581 \layout Section
6582
6583 IPython as a system shell
6584 \layout Standard
6585
6586 IPython ships with a special profile called
6587 \family typewriter
6588 pysh
6589 \family default
6590 , which you can activate at the command line as
6591 \family typewriter
6592 `ipython -p pysh'
6593 \family default
6594 .
6595 This loads
6596 \family typewriter
6597 InterpreterExec
6598 \family default
6599 , along with some additional facilities and a prompt customized for filesystem
6600 navigation.
6601 \layout Standard
6602
6603 Note that this does
6604 \emph on
6605 not
6606 \emph default
6607 make IPython a full-fledged system shell.
6608 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
6609 you'll suspend pysh itself, not the process you just started.
6610
6611 \layout Standard
6612
6613 What the shell profile allows you to do is to use the convenient and powerful
6614 syntax of Python to do quick scripting at the command line.
6615 Below we describe some of its features.
6616 \layout Subsection
6617
6618 Aliases
6619 \layout Standard
6620
6621 All of your
6622 \family typewriter
6623 $PATH
6624 \family default
6625 has been loaded as IPython aliases, so you should be able to type any normal
6626 system command and have it executed.
6627 See
6628 \family typewriter
6629 %alias?
6630 \family default
6631 and
6632 \family typewriter
6633 %unalias?
6634 \family default
6635 for details on the alias facilities.
6636 See also
6637 \family typewriter
6638 %rehash?
6639 \family default
6640 and
6641 \family typewriter
6642 %rehashx?
6643 \family default
6644 for details on the mechanism used to load
6645 \family typewriter
6646 $PATH
6647 \family default
6648 .
6649 \layout Subsection
6650
6651 Special syntax
6652 \layout Standard
6653
6654 Any lines which begin with
6655 \family typewriter
6656 `~'
6657 \family default
6658 ,
6659 \family typewriter
6660 `/'
6661 \family default
6662 and
6663 \family typewriter
6664 `.'
6665 \family default
6666 will be executed as shell commands instead of as Python code.
6667 The special escapes below are also recognized.
6668
6669 \family typewriter
6670 !cmd
6671 \family default
6672 is valid in single or multi-line input, all others are only valid in single-lin
6673 e input:
6674 \layout Description
6675
6676
6677 \family typewriter
6678 !cmd
6679 \family default
6680 pass `cmd' directly to the shell
6681 \layout Description
6682
6683
6684 \family typewriter
6685 !!cmd
6686 \family default
6687 execute `cmd' and return output as a list (split on `
6688 \backslash
6689 n')
6690 \layout Description
6691
6692
6693 \family typewriter
6694 $var=cmd
6695 \family default
6696 capture output of cmd into var, as a string
6697 \layout Description
6698
6699
6700 \family typewriter
6701 $$var=cmd
6702 \family default
6703 capture output of cmd into var, as a list (split on `
6704 \backslash
6705 n')
6706 \layout Standard
6707
6708 The
6709 \family typewriter
6710 $
6711 \family default
6712 /
6713 \family typewriter
6714 $$
6715 \family default
6716 syntaxes make Python variables from system output, which you can later
6717 use for further scripting.
6718 The converse is also possible: when executing an alias or calling to the
6719 system via
6720 \family typewriter
6721 !
6722 \family default
6723 /
6724 \family typewriter
6725 !!
6726 \family default
6727 , you can expand any python variable or expression by prepending it with
6728
6729 \family typewriter
6730 $
6731 \family default
6732 .
6733 Full details of the allowed syntax can be found in Python's PEP 215.
6734 \layout Standard
6735
6736 A few brief examples will illustrate these (note that the indentation below
6737 may be incorrectly displayed):
6738 \layout Standard
6739
6740
6741 \family typewriter
6742 fperez[~/test]|3> !ls *s.py
6743 \newline
6744 scopes.py strings.py
6745 \layout Standard
6746
6747 ls is an internal alias, so there's no need to use
6748 \family typewriter
6749 !
6750 \family default
6751 :
6752 \layout Standard
6753
6754
6755 \family typewriter
6756 fperez[~/test]|4> ls *s.py
6757 \newline
6758 scopes.py* strings.py
6759 \layout Standard
6760
6761 !!ls will return the output into a Python variable:
6762 \layout Standard
6763
6764
6765 \family typewriter
6766 fperez[~/test]|5> !!ls *s.py
6767 \newline
6768
6769 \begin_inset ERT
6770 status Collapsed
6771
6772 \layout Standard
6773
6774 \backslash
6775 hspace*{0mm}
6776 \end_inset
6777
6778 \SpecialChar ~
6779 \SpecialChar ~
6780 \SpecialChar ~
6781 \SpecialChar ~
6782 \SpecialChar ~
6783 \SpecialChar ~
6784 \SpecialChar ~
6785 \SpecialChar ~
6786 \SpecialChar ~
6787 \SpecialChar ~
6788 \SpecialChar ~
6789 \SpecialChar ~
6790 \SpecialChar ~
6791 \SpecialChar ~
6792 <5> ['scopes.py', 'strings.py']
6793 \newline
6794 fperez[~/test]|6> print _5
6795 \newline
6796 ['scopes.py', 'strings.py']
6797 \layout Standard
6798
6799
6800 \family typewriter
6801 $
6802 \family default
6803 and
6804 \family typewriter
6805 $$
6806 \family default
6807 allow direct capture to named variables:
6808 \layout Standard
6809
6810
6811 \family typewriter
6812 fperez[~/test]|7> $astr = ls *s.py
6813 \newline
6814 fperez[~/test]|8> astr
6815 \newline
6816
6817 \begin_inset ERT
6818 status Collapsed
6819
6820 \layout Standard
6821
6822 \backslash
6823 hspace*{0mm}
6824 \end_inset
6825
6826 \SpecialChar ~
6827 \SpecialChar ~
6828 \SpecialChar ~
6829 \SpecialChar ~
6830 \SpecialChar ~
6831 \SpecialChar ~
6832 \SpecialChar ~
6833 \SpecialChar ~
6834 \SpecialChar ~
6835 \SpecialChar ~
6836 \SpecialChar ~
6837 \SpecialChar ~
6838 \SpecialChar ~
6839 \SpecialChar ~
6840 <8> 'scopes.py
6841 \backslash
6842 nstrings.py'
6843 \layout Standard
6844
6845
6846 \family typewriter
6847 fperez[~/test]|9> $$alist = ls *s.py
6848 \newline
6849 fperez[~/test]|10> alist
6850 \newline
6851
6852 \begin_inset ERT
6853 status Collapsed
6854
6855 \layout Standard
6856
6857 \backslash
6858 hspace*{0mm}
6859 \end_inset
6860
6861 \SpecialChar ~
6862 \SpecialChar ~
6863 \SpecialChar ~
6864 \SpecialChar ~
6865 \SpecialChar ~
6866 \SpecialChar ~
6867 \SpecialChar ~
6868 \SpecialChar ~
6869 \SpecialChar ~
6870 \SpecialChar ~
6871 \SpecialChar ~
6872 \SpecialChar ~
6873 \SpecialChar ~
6874 \SpecialChar ~
6875 <10> ['scopes.py', 'strings.py']
6876 \layout Standard
6877
6878 alist is now a normal python list you can loop over.
6879 Using
6880 \family typewriter
6881 $
6882 \family default
6883 will expand back the python values when alias calls are made:
6884 \layout Standard
6885
6886
6887 \family typewriter
6888 fperez[~/test]|11> for f in alist:
6889 \newline
6890
6891 \begin_inset ERT
6892 status Collapsed
6893
6894 \layout Standard
6895
6896 \backslash
6897 hspace*{0mm}
6898 \end_inset
6899
6900 \SpecialChar ~
6901 \SpecialChar ~
6902 \SpecialChar ~
6903 \SpecialChar ~
6904 \SpecialChar ~
6905 \SpecialChar ~
6906 \SpecialChar ~
6907 \SpecialChar ~
6908 \SpecialChar ~
6909 \SpecialChar ~
6910 \SpecialChar ~
6911 \SpecialChar ~
6912 \SpecialChar ~
6913 \SpecialChar ~
6914 |..> \SpecialChar ~
6915 \SpecialChar ~
6916 \SpecialChar ~
6917 \SpecialChar ~
6918 print 'file',f,
6919 \newline
6920
6921 \begin_inset ERT
6922 status Collapsed
6923
6924 \layout Standard
6925
6926 \backslash
6927 hspace*{0mm}
6928 \end_inset
6929
6930 \SpecialChar ~
6931 \SpecialChar ~
6932 \SpecialChar ~
6933 \SpecialChar ~
6934 \SpecialChar ~
6935 \SpecialChar ~
6936 \SpecialChar ~
6937 \SpecialChar ~
6938 \SpecialChar ~
6939 \SpecialChar ~
6940 \SpecialChar ~
6941 \SpecialChar ~
6942 \SpecialChar ~
6943 \SpecialChar ~
6944 |..> \SpecialChar ~
6945 \SpecialChar ~
6946 \SpecialChar ~
6947 \SpecialChar ~
6948 wc -l $f
6949 \newline
6950
6951 \begin_inset ERT
6952 status Collapsed
6953
6954 \layout Standard
6955
6956 \backslash
6957 hspace*{0mm}
6958 \end_inset
6959
6960 \SpecialChar ~
6961 \SpecialChar ~
6962 \SpecialChar ~
6963 \SpecialChar ~
6964 \SpecialChar ~
6965 \SpecialChar ~
6966 \SpecialChar ~
6967 \SpecialChar ~
6968 \SpecialChar ~
6969 \SpecialChar ~
6970 \SpecialChar ~
6971 \SpecialChar ~
6972 \SpecialChar ~
6973 \SpecialChar ~
6974 |..>
6975 \newline
6976 file scopes.py 13 scopes.py
6977 \newline
6978 file strings.py 4 strings.py
6979 \layout Standard
6980
6981 Note that you may need to protect your variables with braces if you want
6982 to append strings to their names.
6983 To copy all files in alist to
6984 \family typewriter
6985 .bak
6986 \family default
6987 extensions, you must use:
6988 \layout Standard
6989
6990
6991 \family typewriter
6992 fperez[~/test]|12> for f in alist:
6993 \newline
6994
6995 \begin_inset ERT
6996 status Collapsed
6997
6998 \layout Standard
6999
7000 \backslash
7001 hspace*{0mm}
7002 \end_inset
7003
7004 \SpecialChar ~
7005 \SpecialChar ~
7006 \SpecialChar ~
7007 \SpecialChar ~
7008 \SpecialChar ~
7009 \SpecialChar ~
7010 \SpecialChar ~
7011 \SpecialChar ~
7012 \SpecialChar ~
7013 \SpecialChar ~
7014 \SpecialChar ~
7015 \SpecialChar ~
7016 \SpecialChar ~
7017 \SpecialChar ~
7018 |..> \SpecialChar ~
7019 \SpecialChar ~
7020 \SpecialChar ~
7021 \SpecialChar ~
7022 cp $f ${f}.bak
7023 \layout Standard
7024
7025 If you try using
7026 \family typewriter
7027 $f.bak
7028 \family default
7029 , you'll get an AttributeError exception saying that your string object
7030 doesn't have a
7031 \family typewriter
7032 .bak
7033 \family default
7034 attribute.
7035 This is because the
7036 \family typewriter
7037 $
7038 \family default
7039 expansion mechanism allows you to expand full Python expressions:
7040 \layout Standard
7041
7042
7043 \family typewriter
7044 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7045 \newline
7046 sys.platform is: linux2
7047 \layout Standard
7048
7049 IPython's input history handling is still active, which allows you to rerun
7050 a single block of multi-line input by simply using exec:
7051 \newline
7052
7053 \family typewriter
7054 fperez[~/test]|14> $$alist = ls *.eps
7055 \newline
7056 fperez[~/test]|15> exec _i11
7057 \newline
7058 file image2.eps 921 image2.eps
7059 \newline
7060 file image.eps 921 image.eps
7061 \layout Standard
7062
7063 While these are new special-case syntaxes, they are designed to allow very
7064 efficient use of the shell with minimal typing.
7065 At an interactive shell prompt, conciseness of expression wins over readability.
7066 \layout Subsection
7067
7068 Useful functions and modules
7069 \layout Standard
7070
7071 The os, sys and shutil modules from the Python standard library are automaticall
7072 y loaded.
7073 Some additional functions, useful for shell usage, are listed below.
7074 You can request more help about them with `
7075 \family typewriter
7076 ?
7077 \family default
7078 '.
7079 \layout Description
7080
7081
7082 \family typewriter
7083 shell
7084 \family default
7085 - execute a command in the underlying system shell
7086 \layout Description
7087
7088
7089 \family typewriter
7090 system
7091 \family default
7092 - like
7093 \family typewriter
7094 shell()
7095 \family default
7096 , but return the exit status of the command
7097 \layout Description
7098
7099
7100 \family typewriter
7101 sout
7102 \family default
7103 - capture the output of a command as a string
7104 \layout Description
7105
7106
7107 \family typewriter
7108 lout
7109 \family default
7110 - capture the output of a command as a list (split on `
7111 \backslash
7112 n')
7113 \layout Description
7114
7115
7116 \family typewriter
7117 getoutputerror
7118 \family default
7119 - capture (output,error) of a shell commandss
7120 \layout Standard
7121
7122
7123 \family typewriter
7124 sout
7125 \family default
7126 /
7127 \family typewriter
7128 lout
7129 \family default
7130 are the functional equivalents of
7131 \family typewriter
7132 $
7133 \family default
7134 /
7135 \family typewriter
7136 $$
7137 \family default
7138 .
7139 They are provided to allow you to capture system output in the middle of
7140 true python code, function definitions, etc (where
7141 \family typewriter
7142 $
7143 \family default
7144 and
7145 \family typewriter
7146 $$
7147 \family default
7148 are invalid).
7149 \layout Subsection
7150
7151 Directory management
7152 \layout Standard
7153
7154 Since each command passed by pysh to the underlying system is executed in
7155 a subshell which exits immediately, you can NOT use !cd to navigate the
7156 filesystem.
7157 \layout Standard
7158
7159 Pysh provides its own builtin
7160 \family typewriter
7161 `%cd
7162 \family default
7163 ' magic command to move in the filesystem (the
7164 \family typewriter
7165 %
7166 \family default
7167 is not required with automagic on).
7168 It also maintains a list of visited directories (use
7169 \family typewriter
7170 %dhist
7171 \family default
7172 to see it) and allows direct switching to any of them.
7173 Type
7174 \family typewriter
7175 `cd?
7176 \family default
7177 ' for more details.
7178 \layout Standard
7179
7180
7181 \family typewriter
7182 %pushd
7183 \family default
7184 ,
7185 \family typewriter
7186 %popd
7187 \family default
7188 and
7189 \family typewriter
7190 %dirs
7191 \family default
7192 are provided for directory stack handling.
7193 \layout Subsection
7194
7195 Prompt customization
7196 \layout Standard
7197
7198 The supplied
7199 \family typewriter
7200 ipythonrc-pysh
7201 \family default
7202 profile comes with an example of a very colored and detailed prompt, mainly
7203 to serve as an illustration.
7204 The valid escape sequences, besides color names, are:
7205 \layout Description
7206
7207
7208 \backslash
7209 # - Prompt number.
7210 \layout Description
7211
7212
7213 \backslash
7214 D - Dots, as many as there are digits in
7215 \backslash
7216 # (so they align).
7217 \layout Description
7218
7219
7220 \backslash
7221 w - Current working directory (cwd).
7222 \layout Description
7223
7224
7225 \backslash
7226 W - Basename of current working directory.
7227 \layout Description
7228
7229
7230 \backslash
7231 X
7232 \emph on
7233 N
7234 \emph default
7235 - Where
7236 \emph on
7237 N
7238 \emph default
7239 =0..5.
7240 N terms of the cwd, with $HOME written as ~.
7241 \layout Description
7242
7243
7244 \backslash
7245 Y
7246 \emph on
7247 N
7248 \emph default
7249 - Where
7250 \emph on
7251 N
7252 \emph default
7253 =0..5.
7254 Like X
7255 \emph on
7256 N
7257 \emph default
7258 , but if ~ is term
7259 \emph on
7260 N
7261 \emph default
7262 +1 it's also shown.
7263 \layout Description
7264
7265
7266 \backslash
7267 u - Username.
7268 \layout Description
7269
7270
7271 \backslash
7272 H - Full hostname.
7273 \layout Description
7274
7275
7276 \backslash
7277 h - Hostname up to first '.'
7278 \layout Description
7279
7280
7281 \backslash
7282 $ - Root symbol ($ or #).
7283
7284 \layout Description
7285
7286
7287 \backslash
7288 t - Current time, in H:M:S format.
7289 \layout Description
7290
7291
7292 \backslash
7293 v - IPython release version.
7294
7295 \layout Description
7296
7297
7298 \backslash
7299 n - Newline.
7300
7301 \layout Description
7302
7303
7304 \backslash
7305 r - Carriage return.
7306
7307 \layout Description
7308
7309
7310 \backslash
7311
7312 \backslash
7313 - An explicitly escaped '
7314 \backslash
7315 '.
7316 \layout Standard
7317
7318 You can configure your prompt colors using any ANSI color escape.
7319 Each color escape sets the color for any subsequent text, until another
7320 escape comes in and changes things.
7321 The valid color escapes are:
7322 \layout Description
7323
7324
7325 \backslash
7326 C_Black
7327 \layout Description
7328
7329
7330 \backslash
7331 C_Blue
7332 \layout Description
7333
7334
7335 \backslash
7336 C_Brown
7337 \layout Description
7338
7339
7340 \backslash
7341 C_Cyan
7342 \layout Description
7343
7344
7345 \backslash
7346 C_DarkGray
7347 \layout Description
7348
7349
7350 \backslash
7351 C_Green
7352 \layout Description
7353
7354
7355 \backslash
7356 C_LightBlue
7357 \layout Description
7358
7359
7360 \backslash
7361 C_LightCyan
7362 \layout Description
7363
7364
7365 \backslash
7366 C_LightGray
7367 \layout Description
7368
7369
7370 \backslash
7371 C_LightGreen
7372 \layout Description
7373
7374
7375 \backslash
7376 C_LightPurple
7377 \layout Description
7378
7379
7380 \backslash
7381 C_LightRed
7382 \layout Description
7383
7384
7385 \backslash
7386 C_Purple
7387 \layout Description
7388
7389
7390 \backslash
7391 C_Red
7392 \layout Description
7393
7394
7395 \backslash
7396 C_White
7397 \layout Description
7398
7399
7400 \backslash
7401 C_Yellow
7402 \layout Description
7403
7404
7405 \backslash
7406 C_Normal Stop coloring, defaults to your terminal settings.
7407 \layout Section
7408
7409
7410 \begin_inset LatexCommand \label{sec:Threading-support}
7411
7412 \end_inset
7413
7414 Threading support
7415 \layout Standard
7416
7417
7418 \series bold
7419 WARNING:
7420 \series default
7421 The threading support is still somewhat experimental, and it has only seen
7422 reasonable testing under Linux.
7423 Threaded code is particularly tricky to debug, and it tends to show extremely
7424 platform-dependent behavior.
7425 Since I only have access to Linux machines, I will have to rely on user's
7426 experiences and assistance for this area of IPython to improve under other
7427 platforms.
7428 \layout Standard
7429
7430 IPython, via the
7431 \family typewriter
7432 -gthread
7433 \family default
7434 and
7435 \family typewriter
7436 -wthread
7437 \family default
7438 options (described in Sec.\SpecialChar ~
7439
7440 \begin_inset LatexCommand \ref{sec:threading-opts}
7441
7442 \end_inset
7443
7444 ), can run in multithreaded mode to support pyGTK and WXPython applications
7445 respectively.
7446 Both of these GUI toolkits need to control the python main loop of execution,
7447 so under a normal Python interpreter, starting a pyGTK (or WXPython) applicatio
7448 n will immediately freeze the shell.
7449
7450 \layout Standard
7451
7452 IPython, with one of these options (you can only use one at a time), separates
7453 the graphical loop and IPython's code execution run into different threads.
7454 This allows you to test interactively (with
7455 \family typewriter
7456 %run
7457 \family default
7458 , for example) your GUI code without blocking.
7459 \layout Subsection
7460
7461 Tk issues
7462 \layout Standard
7463
7464 As indicated in Sec.\SpecialChar ~
7465
7466 \begin_inset LatexCommand \ref{sec:threading-opts}
7467
7468 \end_inset
7469
7470 , a special
7471 \family typewriter
7472 -tk
7473 \family default
7474 option is provided to try and allow Tk graphical applications to coexist
7475 interactively with WX or GTK ones.
7476 Whether this works at all, however, is very platform and configuration
7477 dependent.
7478 Please experiment with simple test cases before committing to using this
7479 combination of Tk and WX/GTK threading in a production environment.
7480 \layout Subsection
7481
7482 Signals and Threads
7483 \layout Standard
7484
7485 When any of the thread systems (WX or GTK) are active, either directly or
7486 via
7487 \family typewriter
7488 -pylab
7489 \family default
7490 with a threaded backend, it is impossible to interrupt long-running Python
7491 code via
7492 \family typewriter
7493 Ctrl-C
7494 \family default
7495 .
7496 IPython can not pass the KeyboardInterrupt exception (or the underlying
7497
7498 \family typewriter
7499 SIGINT
7500 \family default
7501 ) across threads, so any long-running process started from IPython will
7502 run to completion, or will have to be killed via an external (OS-based)
7503 mechanism.
7504 \layout Standard
7505
7506 To the best of my knowledge, this limitation is imposed by the Python interprete
7507 r itself, and it comes from the difficulty of writing portable signal/threaded
7508 code.
7509 If any user is an expert on this topic and can suggest a better solution,
7510 I would love to hear about it.
7511 In the IPython sources, look at the
7512 \family typewriter
7513 Shell.py
7514 \family default
7515 module, and in particular at the
7516 \family typewriter
7517 runcode()
7518 \family default
7519 method.
7520
7521 \layout Subsection
7522
7523 I/O pitfalls
7524 \layout Standard
7525
7526 Be mindful that the Python interpreter switches between threads every
7527 \begin_inset Formula $N$
7528 \end_inset
7529
7530 bytecodes, where the default value as of Python\SpecialChar ~
7531 2.3 is
7532 \begin_inset Formula $N=100.$
7533 \end_inset
7534
7535 This value can be read by using the
7536 \family typewriter
7537 sys.getcheckinterval()
7538 \family default
7539 function, and it can be reset via
7540 \family typewriter
7541 sys.setcheckinterval(
7542 \emph on
7543 N
7544 \emph default
7545 )
7546 \family default
7547 .
7548 This switching of threads can cause subtly confusing effects if one of
7549 your threads is doing file I/O.
7550 In text mode, most systems only flush file buffers when they encounter
7551 a
7552 \family typewriter
7553 `
7554 \backslash
7555 n'
7556 \family default
7557 .
7558 An instruction as simple as
7559 \family typewriter
7560
7561 \newline
7562 \SpecialChar ~
7563 \SpecialChar ~
7564 print >> filehandle,
7565 \begin_inset Quotes eld
7566 \end_inset
7567
7568 hello world
7569 \begin_inset Quotes erd
7570 \end_inset
7571
7572
7573 \family default
7574
7575 \newline
7576 actually consists of several bytecodes, so it is possible that the newline
7577 does not reach your file before the next thread switch.
7578 Similarly, if you are writing to a file in binary mode, the file won't
7579 be flushed until the buffer fills, and your other thread may see apparently
7580 truncated files.
7581
7582 \layout Standard
7583
7584 For this reason, if you are using IPython's thread support and have (for
7585 example) a GUI application which will read data generated by files written
7586 to from the IPython thread, the safest approach is to open all of your
7587 files in unbuffered mode (the third argument to the
7588 \family typewriter
7589 file/open
7590 \family default
7591 function is the buffering value):
7592 \newline
7593
7594 \family typewriter
7595 \SpecialChar ~
7596 \SpecialChar ~
7597 filehandle = open(filename,mode,0)
7598 \layout Standard
7599
7600 This is obviously a brute force way of avoiding race conditions with the
7601 file buffering.
7602 If you want to do it cleanly, and you have a resource which is being shared
7603 by the interactive IPython loop and your GUI thread, you should really
7604 handle it with thread locking and syncrhonization properties.
7605 The Python documentation discusses these.
7606 \layout Section
7607
7608
7609 \begin_inset LatexCommand \label{sec:matplotlib-support}
7610
7611 \end_inset
7612
7613 Plotting with
7614 \family typewriter
7615 matplotlib
7616 \family default
7617
7618 \layout Standard
7619
7620 The matplotlib library (
7621 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
7622
7623 \end_inset
7624
7625 ) provides high quality 2D plotting for Python.
7626 Matplotlib can produce plots on screen using a variety of GUI toolkits,
7627 including Tk, GTK and WXPython.
7628 It also provides a number of commands useful for scientific computing,
7629 all with a syntax compatible with that of the popular Matlab program.
7630 \layout Standard
7631
7632 IPython accepts the special option
7633 \family typewriter
7634 -pylab
7635 \family default
7636 (Sec.\SpecialChar ~
7637
7638 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
7639
7640 \end_inset
7641
7642 ).
7643 This configures it to support matplotlib, honoring the settings in the
7644
7645 \family typewriter
7646 .matplotlibrc
7647 \family default
7648 file.
7649 IPython will detect the user's choice of matplotlib GUI backend, and automatica
7650 lly select the proper threading model to prevent blocking.
7651 It also sets matplotlib in interactive mode and modifies
7652 \family typewriter
7653 %run
7654 \family default
7655 slightly, so that any matplotlib-based script can be executed using
7656 \family typewriter
7657 %run
7658 \family default
7659 and the final
7660 \family typewriter
7661 show()
7662 \family default
7663 command does not block the interactive shell.
7664 \layout Standard
7665
7666 The
7667 \family typewriter
7668 -pylab
7669 \family default
7670 option must be given first in order for IPython to configure its threading
7671 mode.
7672 However, you can still issue other options afterwards.
7673 This allows you to have a matplotlib-based environment customized with
7674 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
7675
7676 \begin_inset LatexCommand \ref{sec:profiles}
7677
7678 \end_inset
7679
7680 ): ``
7681 \family typewriter
7682 ipython -pylab -p myprofile
7683 \family default
7684 '' will load the profile defined in
7685 \family typewriter
7686 ipythonrc-myprofile
7687 \family default
7688 after configuring matplotlib.
7689 \layout Section
7690
7691
7692 \begin_inset LatexCommand \label{sec:Gnuplot}
7693
7694 \end_inset
7695
7696 Plotting with
7697 \family typewriter
7698 Gnuplot
7699 \layout Standard
7700
7701 Through the magic extension system described in sec.
7702
7703 \begin_inset LatexCommand \ref{sec:magic}
7704
7705 \end_inset
7706
7707 , IPython incorporates a mechanism for conveniently interfacing with the
7708 Gnuplot system (
7709 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
7710
7711 \end_inset
7712
7713 ).
7714 Gnuplot is a very complete 2D and 3D plotting package available for many
7715 operating systems and commonly included in modern Linux distributions.
7716
7717 \layout Standard
7718
7719 Besides having Gnuplot installed, this functionality requires the
7720 \family typewriter
7721 Gnuplot.py
7722 \family default
7723 module for interfacing python with Gnuplot.
7724 It can be downloaded from:
7725 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
7726
7727 \end_inset
7728
7729 .
7730 \layout Subsection
7731
7732 Proper Gnuplot configuration
7733 \layout Standard
7734
7735 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
7736 However, as of
7737 \family typewriter
7738 Gnuplot.py
7739 \family default
7740 version 1.7, a new option was added to communicate between Python and Gnuplot
7741 via FIFOs (pipes).
7742 This mechanism, while fast, also breaks the mouse system.
7743 You must therefore set the variable
7744 \family typewriter
7745 prefer_fifo_data
7746 \family default
7747 to
7748 \family typewriter
7749 0
7750 \family default
7751 in file
7752 \family typewriter
7753 gp_unix.py
7754 \family default
7755 if you wish to keep the interactive mouse and keyboard features working
7756 properly (
7757 \family typewriter
7758 prefer_inline_data
7759 \family default
7760 also must be
7761 \family typewriter
7762 0
7763 \family default
7764 , but this is the default so unless you've changed it manually you should
7765 be fine).
7766 \layout Standard
7767
7768 'Out of the box', Gnuplot is configured with a rather poor set of size,
7769 color and linewidth choices which make the graphs fairly hard to read on
7770 modern high-resolution displays (although they work fine on old 640x480
7771 ones).
7772 Below is a section of my
7773 \family typewriter
7774 .Xdefaults
7775 \family default
7776 file which I use for having a more convenient Gnuplot setup.
7777 Remember to load it by running
7778 \family typewriter
7779 `xrdb .Xdefaults`
7780 \family default
7781 :
7782 \layout Standard
7783
7784
7785 \family typewriter
7786 !******************************************************************
7787 \newline
7788 ! gnuplot options
7789 \newline
7790 ! modify this for a convenient window size
7791 \newline
7792 gnuplot*geometry: 780x580
7793 \layout Standard
7794
7795
7796 \family typewriter
7797 ! on-screen font (not for PostScript)
7798 \newline
7799 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
7800 \layout Standard
7801
7802
7803 \family typewriter
7804 ! color options
7805 \newline
7806 gnuplot*background: black
7807 \newline
7808 gnuplot*textColor: white
7809 \newline
7810 gnuplot*borderColor: white
7811 \newline
7812 gnuplot*axisColor: white
7813 \newline
7814 gnuplot*line1Color: red
7815 \newline
7816 gnuplot*line2Color: green
7817 \newline
7818 gnuplot*line3Color: blue
7819 \newline
7820 gnuplot*line4Color: magenta
7821 \newline
7822 gnuplot*line5Color: cyan
7823 \newline
7824 gnuplot*line6Color: sienna
7825 \newline
7826 gnuplot*line7Color: orange
7827 \newline
7828 gnuplot*line8Color: coral
7829 \layout Standard
7830
7831
7832 \family typewriter
7833 ! multiplicative factor for point styles
7834 \newline
7835 gnuplot*pointsize: 2
7836 \layout Standard
7837
7838
7839 \family typewriter
7840 ! line width options (in pixels)
7841 \newline
7842 gnuplot*borderWidth: 2
7843 \newline
7844 gnuplot*axisWidth: 2
7845 \newline
7846 gnuplot*line1Width: 2
7847 \newline
7848 gnuplot*line2Width: 2
7849 \newline
7850 gnuplot*line3Width: 2
7851 \newline
7852 gnuplot*line4Width: 2
7853 \newline
7854 gnuplot*line5Width: 2
7855 \newline
7856 gnuplot*line6Width: 2
7857 \newline
7858 gnuplot*line7Width: 2
7859 \newline
7860 gnuplot*line8Width: 2
7861 \layout Subsection
7862
7863 The
7864 \family typewriter
7865 IPython.GnuplotRuntime
7866 \family default
7867 module
7868 \layout Standard
7869
7870 IPython includes a module called
7871 \family typewriter
7872 Gnuplot2.py
7873 \family default
7874 which extends and improves the default
7875 \family typewriter
7876 Gnuplot
7877 \family default
7878 .
7879 \family typewriter
7880 py
7881 \family default
7882 (which it still relies upon).
7883 For example, the new
7884 \family typewriter
7885 plot
7886 \family default
7887 function adds several improvements to the original making it more convenient
7888 for interactive use, and
7889 \family typewriter
7890 hardcopy
7891 \family default
7892 fixes a bug in the original which under some circumstances blocks the creation
7893 of PostScript output.
7894 \layout Standard
7895
7896 For scripting use,
7897 \family typewriter
7898 GnuplotRuntime.py
7899 \family default
7900 is provided, which wraps
7901 \family typewriter
7902 Gnuplot2.py
7903 \family default
7904 and creates a series of global aliases.
7905 These make it easy to control Gnuplot plotting jobs through the Python
7906 language.
7907 \layout Standard
7908
7909 Below is some example code which illustrates how to configure Gnuplot inside
7910 your own programs but have it available for further interactive use through
7911 an embedded IPython instance.
7912 Simply run this file at a system prompt.
7913 This file is provided as
7914 \family typewriter
7915 example-gnuplot.py
7916 \family default
7917 in the examples directory:
7918 \layout Standard
7919
7920
7921 \begin_inset Include \verbatiminput{examples/example-gnuplot.py}
7922 preview false
7923
7924 \end_inset
7925
7926
7927 \layout Subsection
7928
7929 The
7930 \family typewriter
7931 numeric
7932 \family default
7933 profile: a scientific computing environment
7934 \layout Standard
7935
7936 The
7937 \family typewriter
7938 numeric
7939 \family default
7940 IPython profile, which you can activate with
7941 \family typewriter
7942 `ipython -p numeric
7943 \family default
7944 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
7945 other useful things for numerical computing), contained in the
7946 \family typewriter
7947 IPython.GnuplotInteractive
7948 \family default
7949 module.
7950 This will create the globals
7951 \family typewriter
7952 Gnuplot
7953 \family default
7954 (an alias to the improved Gnuplot2 module),
7955 \family typewriter
7956 gp
7957 \family default
7958 (a Gnuplot active instance), the new magic commands
7959 \family typewriter
7960 %gpc
7961 \family default
7962 and
7963 \family typewriter
7964 %gp_set_instance
7965 \family default
7966 and several other convenient globals.
7967 Type
7968 \family typewriter
7969 gphelp()
7970 \family default
7971 for further details.
7972 \layout Standard
7973
7974 This should turn IPython into a convenient environment for numerical computing,
7975 with all the functions in the NumPy library and the Gnuplot facilities
7976 for plotting.
7977 Further improvements can be obtained by loading the SciPy libraries for
7978 scientific computing, available at
7979 \begin_inset LatexCommand \htmlurl{http://scipy.org}
7980
7981 \end_inset
7982
7983 .
7984 \layout Standard
7985
7986 If you are in the middle of a working session with numerical objects and
7987 need to plot them but you didn't start the
7988 \family typewriter
7989 numeric
7990 \family default
7991 profile, you can load these extensions at any time by typing
7992 \newline
7993
7994 \family typewriter
7995 from IPython.GnuplotInteractive import *
7996 \newline
7997
7998 \family default
7999 at the IPython prompt.
8000 This will allow you to keep your objects intact and start using Gnuplot
8001 to view them.
8002 \layout Section
8003
8004 Reporting bugs
8005 \layout Subsection*
8006
8007 Automatic crash reports
8008 \layout Standard
8009
8010 Ideally, IPython itself shouldn't crash.
8011 It will catch exceptions produced by you, but bugs in its internals will
8012 still crash it.
8013 \layout Standard
8014
8015 In such a situation, IPython will leave a file named
8016 \family typewriter
8017 IPython_crash_report.txt
8018 \family default
8019 in your IPYTHONDIR directory (that way if crashes happen several times
8020 it won't litter many directories, the post-mortem file is always located
8021 in the same place and new occurrences just overwrite the previous one).
8022 If you can mail this file to the developers (see sec.
8023
8024 \begin_inset LatexCommand \ref{sec:credits}
8025
8026 \end_inset
8027
8028 for names and addresses), it will help us
8029 \emph on
8030 a lot
8031 \emph default
8032 in understanding the cause of the problem and fixing it sooner.
8033 \layout Subsection*
8034
8035 The bug tracker
8036 \layout Standard
8037
8038 IPython also has an online bug-tracker, located at
8039 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8040
8041 \end_inset
8042
8043 .
8044 In addition to mailing the developers, it would be a good idea to file
8045 a bug report here.
8046 This will ensure that the issue is properly followed to conclusion.
8047 \layout Standard
8048
8049 You can also use this bug tracker to file feature requests.
8050 \layout Section
8051
8052 Brief history
8053 \layout Subsection
8054
8055 Origins
8056 \layout Standard
8057
8058 The current IPython system grew out of the following three projects:
8059 \layout List
8060 \labelwidthstring 00.00.0000
8061
8062 ipython by Fernando P�rez.
8063 I was working on adding Mathematica-type prompts and a flexible configuration
8064 system (something better than
8065 \family typewriter
8066 $PYTHONSTARTUP
8067 \family default
8068 ) to the standard Python interactive interpreter.
8069 \layout List
8070 \labelwidthstring 00.00.0000
8071
8072 IPP by Janko Hauser.
8073 Very well organized, great usability.
8074 Had an old help system.
8075 IPP was used as the `container' code into which I added the functionality
8076 from ipython and LazyPython.
8077 \layout List
8078 \labelwidthstring 00.00.0000
8079
8080 LazyPython by Nathan Gray.
8081 Simple but
8082 \emph on
8083 very
8084 \emph default
8085 powerful.
8086 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8087 were all taken from here.
8088 \layout Standard
8089
8090 When I found out (see sec.
8091
8092 \begin_inset LatexCommand \ref{figgins}
8093
8094 \end_inset
8095
8096 ) about IPP and LazyPython I tried to join all three into a unified system.
8097 I thought this could provide a very nice working environment, both for
8098 regular programming and scientific computing: shell-like features, IDL/Matlab
8099 numerics, Mathematica-type prompt history and great object introspection
8100 and help facilities.
8101 I think it worked reasonably well, though it was a lot more work than I
8102 had initially planned.
8103 \layout Subsection
8104
8105 Current status
8106 \layout Standard
8107
8108 The above listed features work, and quite well for the most part.
8109 But until a major internal restructuring is done (see below), only bug
8110 fixing will be done, no other features will be added (unless very minor
8111 and well localized in the cleaner parts of the code).
8112 \layout Standard
8113
8114 IPython consists of some 12000 lines of pure python code, of which roughly
8115 50% are fairly clean.
8116 The other 50% are fragile, messy code which needs a massive restructuring
8117 before any further major work is done.
8118 Even the messy code is fairly well documented though, and most of the problems
8119 in the (non-existent) class design are well pointed to by a PyChecker run.
8120 So the rewriting work isn't that bad, it will just be time-consuming.
8121 \layout Subsection
8122
8123 Future
8124 \layout Standard
8125
8126 See the separate
8127 \family typewriter
8128 new_design
8129 \family default
8130 document for details.
8131 Ultimately, I would like to see IPython become part of the standard Python
8132 distribution as a `big brother with batteries' to the standard Python interacti
8133 ve interpreter.
8134 But that will never happen with the current state of the code, so all contribut
8135 ions are welcome.
8136 \layout Section
8137
8138 License
8139 \layout Standard
8140
8141 IPython is released under the terms of the BSD license, whose general form
8142 can be found at:
8143 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8144
8145 \end_inset
8146
8147 .
8148 The full text of the IPython license is reproduced below:
8149 \layout Quote
8150
8151
8152 \family typewriter
8153 \size small
8154 IPython is released under a BSD-type license.
8155 \layout Quote
8156
8157
8158 \family typewriter
8159 \size small
8160 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8161 \layout Quote
8162
8163
8164 \family typewriter
8165 \size small
8166 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8167 \newline
8168 Nathaniel Gray <n8gray@caltech.edu>.
8169 \layout Quote
8170
8171
8172 \family typewriter
8173 \size small
8174 All rights reserved.
8175 \layout Quote
8176
8177
8178 \family typewriter
8179 \size small
8180 Redistribution and use in source and binary forms, with or without modification,
8181 are permitted provided that the following conditions are met:
8182 \layout Quote
8183
8184
8185 \family typewriter
8186 \size small
8187 a.
8188 Redistributions of source code must retain the above copyright notice,
8189 this list of conditions and the following disclaimer.
8190 \layout Quote
8191
8192
8193 \family typewriter
8194 \size small
8195 b.
8196 Redistributions in binary form must reproduce the above copyright notice,
8197 this list of conditions and the following disclaimer in the documentation
8198 and/or other materials provided with the distribution.
8199 \layout Quote
8200
8201
8202 \family typewriter
8203 \size small
8204 c.
8205 Neither the name of the copyright holders nor the names of any contributors
8206 to this software may be used to endorse or promote products derived from
8207 this software without specific prior written permission.
8208 \layout Quote
8209
8210
8211 \family typewriter
8212 \size small
8213 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8214 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8215 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8216 PURPOSE ARE DISCLAIMED.
8217 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8218 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8219 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8220 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8221 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8222 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8223 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8224
8225 \layout Standard
8226
8227 Individual authors are the holders of the copyright for their code and are
8228 listed in each file.
8229 \layout Standard
8230
8231 Some files (
8232 \family typewriter
8233 DPyGetOpt.py
8234 \family default
8235 , for example) may be licensed under different conditions.
8236 Ultimately each file indicates clearly the conditions under which its author/au
8237 thors have decided to publish the code.
8238 \layout Standard
8239
8240 Versions of IPython up to and including 0.6.3 were released under the GNU
8241 Lesser General Public License (LGPL), available at
8242 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8243
8244 \end_inset
8245
8246 .
8247 \layout Section
8248
8249
8250 \begin_inset LatexCommand \label{sec:credits}
8251
8252 \end_inset
8253
8254 Credits
8255 \layout Standard
8256
8257 IPython is mainly developed by Fernando P�rez
8258 \family typewriter
8259 <fperez@colorado.edu>
8260 \family default
8261 , but the project was born from mixing in Fernando's code with the IPP project
8262 by Janko Hauser
8263 \family typewriter
8264 <jhauser-AT-zscout.de>
8265 \family default
8266 and LazyPython by Nathan Gray
8267 \family typewriter
8268 <n8gray-AT-caltech.edu>
8269 \family default
8270 .
8271 For all IPython-related requests, please contact Fernando.
8272 User or development help should be requested via the IPython mailing lists:
8273 \layout Description
8274
8275 User\SpecialChar ~
8276 list:
8277 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8278
8279 \end_inset
8280
8281
8282 \layout Description
8283
8284 Developer's\SpecialChar ~
8285 list:
8286 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8287
8288 \end_inset
8289
8290
8291 \layout Standard
8292
8293 The IPython project is also very grateful to
8294 \begin_inset Foot
8295 collapsed true
8296
8297 \layout Standard
8298
8299 I've mangled email addresses to reduce spam, since the IPython manuals can
8300 be accessed online.
8301 \end_inset
8302
8303 :
8304 \layout Standard
8305
8306 Bill Bumgarner
8307 \family typewriter
8308 <bbum-AT-friday.com>
8309 \family default
8310 : for providing the DPyGetOpt module which gives very powerful and convenient
8311 handling of command-line options (light years ahead of what Python 2.1.1's
8312 getopt module does).
8313 \layout Standard
8314
8315 Ka-Ping Yee
8316 \family typewriter
8317 <ping-AT-lfw.org>
8318 \family default
8319 : for providing the Itpl module for convenient and powerful string interpolation
8320 with a much nicer syntax than formatting through the '%' operator.
8321 \layout Standard
8322
8323 Arnd B�cker
8324 \family typewriter
8325 <baecker-AT-physik.tu-dresden.de>
8326 \family default
8327 : for his many very useful suggestions and comments, and lots of help with
8328 testing and documentation checking.
8329 Many of IPython's newer features are a result of discussions with him (bugs
8330 are still my fault, not his).
8331 \layout Standard
8332
8333 Obviously Guido van\SpecialChar ~
8334 Rossum and the whole Python development team, that goes
8335 without saying.
8336 \layout Standard
8337
8338 IPython's website is generously hosted at
8339 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
8340
8341 \end_inset
8342
8343 by Enthought (
8344 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
8345
8346 \end_inset
8347
8348 ).
8349 I am very grateful to them and all of the SciPy team for their contribution.
8350 \layout Standard
8351
8352
8353 \begin_inset LatexCommand \label{figgins}
8354
8355 \end_inset
8356
8357 Fernando would also like to thank Stephen Figgins
8358 \family typewriter
8359 <fig-AT-monitor.net>
8360 \family default
8361 , an O'Reilly Python editor.
8362 His Oct/11/2001 article about IPP and LazyPython, was what got this project
8363 started.
8364 You can read it at:
8365 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
8366
8367 \end_inset
8368
8369 .
8370 \layout Standard
8371
8372 And last but not least, all the kind IPython users who have emailed new
8373 code, bug reports, fixes, comments and ideas.
8374 A brief list follows, please let me know if I have ommitted your name by
8375 accident:
8376 \layout List
8377 \labelwidthstring 00.00.0000
8378
8379 Jack\SpecialChar ~
8380 Moffit
8381 \family typewriter
8382 <jack-AT-xiph.org>
8383 \family default
8384 Bug fixes, including the infamous color problem.
8385 This bug alone caused many lost hours and frustration, many thanks to him
8386 for the fix.
8387 I've always been a fan of Ogg & friends, now I have one more reason to
8388 like these folks.
8389 \newline
8390 Jack is also contributing with Debian packaging and many other things.
8391 \layout List
8392 \labelwidthstring 00.00.0000
8393
8394 Alexander\SpecialChar ~
8395 Schmolck
8396 \family typewriter
8397 <a.schmolck-AT-gmx.net>
8398 \family default
8399 Emacs work, bug reports, bug fixes, ideas, lots more.
8400 The ipython.el mode for (X)Emacs is Alex's code, providing full support
8401 for IPython under (X)Emacs.
8402 \layout List
8403 \labelwidthstring 00.00.0000
8404
8405 Andrea\SpecialChar ~
8406 Riciputi
8407 \family typewriter
8408 <andrea.riciputi-AT-libero.it>
8409 \family default
8410 Mac OSX information, Fink package management.
8411 \layout List
8412 \labelwidthstring 00.00.0000
8413
8414 Gary\SpecialChar ~
8415 Bishop
8416 \family typewriter
8417 <gb-AT-cs.unc.edu>
8418 \family default
8419 Bug reports, and patches to work around the exception handling idiosyncracies
8420 of WxPython.
8421 Readline and color support for Windows.
8422 \layout List
8423 \labelwidthstring 00.00.0000
8424
8425 Jeffrey\SpecialChar ~
8426 Collins
8427 \family typewriter
8428 <Jeff.Collins-AT-vexcel.com>
8429 \family default
8430 Bug reports.
8431 Much improved readline support, including fixes for Python 2.3.
8432 \layout List
8433 \labelwidthstring 00.00.0000
8434
8435 Dryice\SpecialChar ~
8436 Liu
8437 \family typewriter
8438 <dryice-AT-liu.com.cn>
8439 \family default
8440 FreeBSD port.
8441 \layout List
8442 \labelwidthstring 00.00.0000
8443
8444 Mike\SpecialChar ~
8445 Heeter
8446 \family typewriter
8447 <korora-AT-SDF.LONESTAR.ORG>
8448 \layout List
8449 \labelwidthstring 00.00.0000
8450
8451 Christopher\SpecialChar ~
8452 Hart
8453 \family typewriter
8454 <hart-AT-caltech.edu>
8455 \family default
8456 PDB integration.
8457 \layout List
8458 \labelwidthstring 00.00.0000
8459
8460 Milan\SpecialChar ~
8461 Zamazal
8462 \family typewriter
8463 <pdm-AT-zamazal.org>
8464 \family default
8465 Emacs info.
8466 \layout List
8467 \labelwidthstring 00.00.0000
8468
8469 Philip\SpecialChar ~
8470 Hisley
8471 \family typewriter
8472 <compsys-AT-starpower.net>
8473 \layout List
8474 \labelwidthstring 00.00.0000
8475
8476 Holger\SpecialChar ~
8477 Krekel
8478 \family typewriter
8479 <pyth-AT-devel.trillke.net>
8480 \family default
8481 Tab completion, lots more.
8482 \layout List
8483 \labelwidthstring 00.00.0000
8484
8485 Robin\SpecialChar ~
8486 Siebler
8487 \family typewriter
8488 <robinsiebler-AT-starband.net>
8489 \layout List
8490 \labelwidthstring 00.00.0000
8491
8492 Ralf\SpecialChar ~
8493 Ahlbrink
8494 \family typewriter
8495 <ralf_ahlbrink-AT-web.de>
8496 \layout List
8497 \labelwidthstring 00.00.0000
8498
8499 Thorsten\SpecialChar ~
8500 Kampe
8501 \family typewriter
8502 <thorsten-AT-thorstenkampe.de>
8503 \layout List
8504 \labelwidthstring 00.00.0000
8505
8506 Fredrik\SpecialChar ~
8507 Kant
8508 \family typewriter
8509 <fredrik.kant-AT-front.com>
8510 \family default
8511 Windows setup.
8512 \layout List
8513 \labelwidthstring 00.00.0000
8514
8515 Syver\SpecialChar ~
8516 Enstad
8517 \family typewriter
8518 <syver-en-AT-online.no>
8519 \family default
8520 Windows setup.
8521 \layout List
8522 \labelwidthstring 00.00.0000
8523
8524 Richard
8525 \family typewriter
8526 <rxe-AT-renre-europe.com>
8527 \family default
8528 Global embedding.
8529 \layout List
8530 \labelwidthstring 00.00.0000
8531
8532 Hayden\SpecialChar ~
8533 Callow
8534 \family typewriter
8535 <h.callow-AT-elec.canterbury.ac.nz>
8536 \family default
8537 Gnuplot.py 1.6 compatibility.
8538 \layout List
8539 \labelwidthstring 00.00.0000
8540
8541 Leonardo\SpecialChar ~
8542 Santagada
8543 \family typewriter
8544 <retype-AT-terra.com.br>
8545 \family default
8546 Fixes for Windows installation.
8547 \layout List
8548 \labelwidthstring 00.00.0000
8549
8550 Christopher\SpecialChar ~
8551 Armstrong
8552 \family typewriter
8553 <radix-AT-twistedmatrix.com>
8554 \family default
8555 Bugfixes.
8556 \layout List
8557 \labelwidthstring 00.00.0000
8558
8559 Francois\SpecialChar ~
8560 Pinard
8561 \family typewriter
8562 <pinard-AT-iro.umontreal.ca>
8563 \family default
8564 Code and documentation fixes.
8565 \layout List
8566 \labelwidthstring 00.00.0000
8567
8568 Cory\SpecialChar ~
8569 Dodt
8570 \family typewriter
8571 <cdodt-AT-fcoe.k12.ca.us>
8572 \family default
8573 Bug reports and Windows ideas.
8574 Patches for Windows installer.
8575 \layout List
8576 \labelwidthstring 00.00.0000
8577
8578 Olivier\SpecialChar ~
8579 Aubert
8580 \family typewriter
8581 <oaubert-AT-bat710.univ-lyon1.fr>
8582 \family default
8583 New magics.
8584 \layout List
8585 \labelwidthstring 00.00.0000
8586
8587 King\SpecialChar ~
8588 C.\SpecialChar ~
8589 Shu
8590 \family typewriter
8591 <kingshu-AT-myrealbox.com>
8592 \family default
8593 Autoindent patch.
8594 \layout List
8595 \labelwidthstring 00.00.0000
8596
8597 Chris\SpecialChar ~
8598 Drexler
8599 \family typewriter
8600 <chris-AT-ac-drexler.de>
8601 \family default
8602 Readline packages for Win32/CygWin.
8603 \layout List
8604 \labelwidthstring 00.00.0000
8605
8606 Gustavo\SpecialChar ~
8607 C�rdova\SpecialChar ~
8608 Avila
8609 \family typewriter
8610 <gcordova-AT-sismex.com>
8611 \family default
8612 EvalDict code for nice, lightweight string interpolation.
8613 \layout List
8614 \labelwidthstring 00.00.0000
8615
8616 Kasper\SpecialChar ~
8617 Souren
8618 \family typewriter
8619 <Kasper.Souren-AT-ircam.fr>
8620 \family default
8621 Bug reports, ideas.
8622 \layout List
8623 \labelwidthstring 00.00.0000
8624
8625 Gever\SpecialChar ~
8626 Tulley
8627 \family typewriter
8628 <gever-AT-helium.com>
8629 \family default
8630 Code contributions.
8631 \layout List
8632 \labelwidthstring 00.00.0000
8633
8634 Ralf\SpecialChar ~
8635 Schmitt
8636 \family typewriter
8637 <ralf-AT-brainbot.com>
8638 \family default
8639 Bug reports & fixes.
8640 \layout List
8641 \labelwidthstring 00.00.0000
8642
8643 Oliver\SpecialChar ~
8644 Sander
8645 \family typewriter
8646 <osander-AT-gmx.de>
8647 \family default
8648 Bug reports.
8649 \layout List
8650 \labelwidthstring 00.00.0000
8651
8652 Rod\SpecialChar ~
8653 Holland
8654 \family typewriter
8655 <rhh-AT-structurelabs.com>
8656 \family default
8657 Bug reports and fixes to logging module.
8658 \layout List
8659 \labelwidthstring 00.00.0000
8660
8661 Daniel\SpecialChar ~
8662 'Dang'\SpecialChar ~
8663 Griffith
8664 \family typewriter
8665 <pythondev-dang-AT-lazytwinacres.net>
8666 \family default
8667 Fixes, enhancement suggestions for system shell use.
8668 \layout List
8669 \labelwidthstring 00.00.0000
8670
8671 Viktor\SpecialChar ~
8672 Ransmayr
8673 \family typewriter
8674 <viktor.ransmayr-AT-t-online.de>
8675 \family default
8676 Tests and reports on Windows installation issues.
8677 Contributed a true Windows binary installer.
8678 \layout List
8679 \labelwidthstring 00.00.0000
8680
8681 Mike\SpecialChar ~
8682 Salib
8683 \family typewriter
8684 <msalib-AT-mit.edu>
8685 \family default
8686 Help fixing a subtle bug related to traceback printing.
8687 \layout List
8688 \labelwidthstring 00.00.0000
8689
8690 W.J.\SpecialChar ~
8691 van\SpecialChar ~
8692 der\SpecialChar ~
8693 Laan
8694 \family typewriter
8695 <gnufnork-AT-hetdigitalegat.nl>
8696 \family default
8697 Bash-like prompt specials.
8698 \layout List
8699 \labelwidthstring 00.00.0000
8700
8701 Ville\SpecialChar ~
8702 Vainio
8703 \family typewriter
8704 <vivainio-AT-kolumbus.fi>
8705 \family default
8706 Bugfixes and suggestions.
8707 Excellent patches for many new features.
8708 \layout List
8709 \labelwidthstring 00.00.0000
8710
8711 Antoon\SpecialChar ~
8712 Pardon
8713 \family typewriter
8714 <Antoon.Pardon-AT-rece.vub.ac.be>
8715 \family default
8716 Critical fix for the multithreaded IPython.
8717 \layout List
8718 \labelwidthstring 00.00.0000
8719
8720 John\SpecialChar ~
8721 Hunter
8722 \family typewriter
8723 <jdhunter-AT-nitace.bsd.uchicago.edu>
8724 \family default
8725 Matplotlib author, helped with all the development of support for matplotlib
8726 in IPyhton, including making necessary changes to matplotlib itself.
8727 \layout List
8728 \labelwidthstring 00.00.0000
8729
8730 Matthew\SpecialChar ~
8731 Arnison
8732 \family typewriter
8733 <maffew-AT-cat.org.au>
8734 \family default
8735 Bug reports, `
8736 \family typewriter
8737 %run -d
8738 \family default
8739 ' idea.
8740 \layout List
8741 \labelwidthstring 00.00.0000
8742
8743 Prabhu\SpecialChar ~
8744 Ramachandran
8745 \family typewriter
8746 <prabhu_r-AT-users.sourceforge.net>
8747 \family default
8748 Help with (X)Emacs support, threading patches, ideas...
8749 \layout List
8750 \labelwidthstring 00.00.0000
8751
8752 Norbert\SpecialChar ~
8753 Tretkowski
8754 \family typewriter
8755 <tretkowski-AT-inittab.de>
8756 \family default
8757 help with Debian packaging and distribution.
8758 \layout List
8759 \labelwidthstring 00.00.0000
8760
8761 Robert\SpecialChar ~
8762 Kern
8763 \family typewriter
8764 <rkern-AT-ucsd.edu>
8765 \family default
8766 help with OSX issues, much help in general with various Python topics,
8767 especially related to scientific computing.
8768 \layout List
8769 \labelwidthstring 00.00.0000
8770
8771 George\SpecialChar ~
8772 Sakkis <
8773 \family typewriter
8774 gsakkis-AT-eden.rutgers.edu>
8775 \family default
8776 New matcher for tab-completing named arguments of user-defined functions.
8777 \the_end
@@ -0,0 +1,11 b''
1 from notebook.markup import rest
2
3 rest.title('This is a Python Notebook')
4 rest.heading(1,'A first-level heading')
5 rest.text("""\
6 Some plain text, without any special formatting.
7
8 Below, we define a simple function to add two numbers.""")
9
10 def add(x,y):
11 return x+y
@@ -0,0 +1,25 b''
1 from notebook.markup import latex
2
3 latex.document_class('article')
4 latex.title('This is a Python Notebook')
5
6 latex.section('A section title',label='sec:intro')
7
8 latex.text(r"""Below, we define a simple function
9 \begin{equation}
10 f: (x,y) \rightarrow x+y^2
11 \end{equation}""")
12
13 def f(x,y):
14 return x+y**2
15
16 # since the .text method passes directly to latex, all markup could be input
17 # in that way if so desired
18 latex.text(r"""
19 \section{Another section}
20
21 More text...
22
23 And now a picture showing our important results...""")
24
25 latex.include_graphic('foo.png')
@@ -0,0 +1,20 b''
1 from notebook.markup import rest
2
3 rest.title('This is a Python Notebook')
4 rest.text("""\
5 Some plain text, without any special formatting.
6
7 Below, we define a simple function to add two numbers.""")
8
9 def add(x,y):
10 return x+y
11
12 rest.text("Let's use it with x=2,y=3:")
13 # This simply means that all code until the next markup call is to be executed
14 # as a single call. The editing screen should mark the whole group of lines
15 # with a single In[NN] tag (like IPython does, but with multi-line capabilities)
16 rest.input()
17 add(2,3)
18 # This output would appear on-screen (in the editing window) simply marked
19 # with an Out[NN] tag
20 rest.output("5")
This diff has been collapsed as it changes many lines, (1345 lines changed) Show them Hide them
@@ -0,0 +1,1345 b''
1 #LyX 1.3 created this file. For more info see http://www.lyx.org/
2 \lyxformat 221
3 \textclass article
4 \begin_preamble
5 \usepackage{ae,aecompl}
6 \usepackage{hyperref}
7 \usepackage{html}
8 \end_preamble
9 \language english
10 \inputencoding auto
11 \fontscheme default
12 \graphics default
13 \paperfontsize default
14 \spacing single
15 \papersize Default
16 \paperpackage a4
17 \use_geometry 1
18 \use_amsmath 0
19 \use_natbib 0
20 \use_numerical_citations 0
21 \paperorientation portrait
22 \leftmargin 1.25in
23 \topmargin 1in
24 \rightmargin 1.25in
25 \bottommargin 1in
26 \secnumdepth 3
27 \tocdepth 3
28 \paragraph_separation skip
29 \defskip medskip
30 \quotes_language english
31 \quotes_times 2
32 \papercolumns 1
33 \papersides 1
34 \paperpagestyle default
35
36 \layout Title
37
38 IPython
39 \newline
40
41 \size larger
42 New design notes
43 \layout Author
44
45 Fernando P�rez
46 \layout Section
47
48 Introduction
49 \layout Standard
50
51 This is a draft document with notes and ideas for the IPython rewrite.
52 The section order and structure of this document roughly reflects in which
53 order things should be done and what the dependencies are.
54 This document is mainly a draft for developers, a pdf version is provided
55 with the standard distribution in case regular users are interested and
56 wish to contribute ideas.
57 \layout Standard
58
59 A tentative plan for the future:
60 \layout Itemize
61
62 0.6.x series: in practice, enough people are using IPython for real work that
63 I think it warrants a higher number.
64 This series will continue to evolve with bugfixes and incremental improvements.
65 \layout Itemize
66
67 0.7.x series: (maybe) If resources allow, there may be a branch for 'unstable'
68 development, where the architectural rewrite may take place.
69 \layout Standard
70
71 However, I am starting to doubt it is feasible to keep two separate branches.
72 I am leaning more towards a
73 \begin_inset ERT
74 status Collapsed
75
76 \layout Standard
77
78 \backslash
79 LyX
80 \end_inset
81
82 -like approach, where the main branch slowly transforms and evolves.
83 Having CVS support now makes this a reasonable alternative, as I don't
84 have to make pre-releases as often.
85 The active branch can remain the mainline of development, and users interested
86 in the bleeding-edge stuff can always grab the CVS code.
87 \layout Standard
88
89 Ideally, IPython should have a clean class setup that would allow further
90 extensions for special-purpose systems.
91 I view IPython as a base system that provides a great interactive environment
92 with full access to the Python language, and which could be used in many
93 different contexts.
94 The basic hooks are there: the magic extension syntax and the flexible
95 system of recursive configuration files and profiles.
96 But with a code as messy as the current one, nobody is going to touch it.
97 \layout Section
98
99 Immediate TODO and bug list
100 \layout Standard
101
102 Things that should be done for the current series, before starting major
103 changes.
104 \layout Itemize
105
106 Fix any bugs reported at the online bug tracker.
107 \layout Itemize
108
109
110 \series bold
111 Redesign the output traps.
112
113 \series default
114 They cause problems when users try to execute code which relies on sys.stdout
115 being the 'true' sys.stdout.
116 They also prevent scripts which use raw_input() to work as command-line
117 arguments.
118 \newline
119 The best solution is probably to print the banner first, and then just execute
120 all the user code straight with no output traps at all.
121 Whatever comes out comes out.
122 This makes the ipython code actually simpler, and eliminates the problem
123 altogether.
124 \newline
125 These things need to be ripped out, they cause no end of problems.
126 For example, if user code requires acces to stdin during startup, the process
127 just hangs indefinitely.
128 For now I've just disabled them, and I'll live with the ugly error messages.
129 \layout Itemize
130
131 The prompt specials dictionary should be turned into a class which does
132 proper namespace management, since the prompt specials need to be evaluated
133 in a certain namespace.
134 Currently it's just globals, which need to be managed manually by code
135 below.
136
137 \layout Itemize
138
139 Fix coloring of prompts: the pysh color strings don't have any effect on
140 prompt numbers, b/c these are controlled by the global scheme.
141 Make the prompts fully user-definable, colors and all.
142 This is what I said to a user:
143 \newline
144 As far as the green
145 \backslash
146 #, this is a minor bug of the coloring code due to the vagaries of history.
147 While the color strings allow you to control the coloring of most elements,
148 there are a few which are still controlled by the old ipython internal
149 coloring code, which only accepts a global 'color scheme' choice.
150 So basically the input/output numbers are hardwired to the choice in the
151 color scheme, and there are only 'Linux', 'LightBG' and 'NoColor' schemes
152 to choose from.
153
154 \layout Itemize
155
156 Clean up FakeModule issues.
157 Currently, unittesting with embedded ipython breaks because a FakeModule
158 instance overwrites __main__.
159 Maybe ipython should revert back to using __main__ directly as the user
160 namespace? Handling a separate namespace is proving
161 \emph on
162 very
163 \emph default
164 tricky in all corner cases.
165 \layout Itemize
166
167 Make the output cache depth independent of the input one.
168 This way one can have say only the last 10 results stored and still have
169 a long input history/cache.
170 \layout Itemize
171
172 Fix the fact that importing a shell for embedding screws up the command-line
173 history.
174 This can be done by not importing the history file when the shell is already
175 inside ipython.
176 \layout Itemize
177
178 Lay out the class structure so that embedding into a gtk/wx/qt app is trivial,
179 much like the multithreaded gui shells now provide command-line coexistence
180 with the gui toolkits.
181 See
182 \begin_inset LatexCommand \url{http://www.livejournal.com/users/glyf/32396.html}
183
184 \end_inset
185
186
187 \layout Itemize
188
189 Get Holger's completer in, once he adds filename completion.
190 \layout Standard
191
192 Lower priority stuff:
193 \layout Itemize
194
195 Add @showopt/@setopt (decide name) for viewing/setting all options.
196 The existing option-setting magics should become aliases for setopt calls.
197 \layout Itemize
198
199 It would be nice to be able to continue with python stuff after an @ command.
200 For instance "@run something; test_stuff()" in order to test stuff even
201 faster.
202 Suggestion by Kasper Souren <Kasper.Souren@ircam.fr>
203 \layout Itemize
204
205 Run a 'first time wizard' which configures a few things for the user, such
206 as color_info, editor and the like.
207 \layout Itemize
208
209 Logging: @logstart and -log should start logfiles in ~.ipython, but with
210 unique names in case of collisions.
211 This would prevent ipython.log files all over while also allowing multiple
212 sessions.
213 Also the -log option should take an optional filename, instead of having
214 a separate -logfile option.
215 \newline
216 In general the logging system needs a serious cleanup.
217 Many functions now in Magic should be moved to Logger, and the magic @s
218 should be very simple wrappers to the Logger methods.
219 \layout Section
220
221 Lighten the code
222 \layout Standard
223
224 If we decide to base future versions of IPython on Python 2.3, which has
225 the new Optik module (called optparse), it should be possible to drop DPyGetOpt.
226 We should also remove the need for Itpl.
227 Another area for trimming is the Gnuplot stuff: much of that could be merged
228 into the mainline project.
229 \layout Standard
230
231 Double check whether we really need FlexCompleter.
232 This was written as an enhanced rlcompleter, but my patches went in for
233 python 2.2 (or 2.3, can't remember).
234 \layout Standard
235
236 With these changes we could shed a fair bit of code from the main trunk.
237 \layout Section
238
239 Unit testing
240 \layout Standard
241
242 All new code should use a testing framework.
243 Python seems to have very good testing facilities, I just need to learn
244 how to use them.
245 I should also check out QMTest at
246 \begin_inset LatexCommand \htmlurl{http://www.codesourcery.com/qm/qmtest}
247
248 \end_inset
249
250 , it sounds interesting (it's Python-based too).
251 \layout Section
252
253 Configuration system
254 \layout Standard
255
256 Move away from the current ipythonrc format to using standard python files
257 for configuration.
258 This will require users to be slightly more careful in their syntax, but
259 reduces code in IPython, is more in line with Python's normal form (using
260 the $PYTHONSTARTUP file) and allows much more flexibility.
261 I also think it's more 'pythonic', in using a single language for everything.
262 \layout Standard
263
264 Options can be set up with a function call which takes keywords and updates
265 the options Struct.
266 \layout Standard
267
268 In order to maintain the recursive inclusion system, write an 'include'
269 function which is basically a wrapper around safe_execfile().
270 Also for alias definitions an alias() function will do.
271 All functionality which we want to have at startup time for the users can
272 be wrapped in a small module so that config files look like:
273 \layout Standard
274
275
276 \family typewriter
277 from IPython.Startup import *
278 \newline
279 ...
280 \newline
281 set_options(automagic=1,colors='NoColor',...)
282 \newline
283 ...
284 \newline
285 include('mysetup.py')
286 \newline
287 ...
288 \newline
289 alias('ls ls --color -l')
290 \newline
291 ...
292 etc.
293 \layout Standard
294
295 Also, put
296 \series bold
297 all
298 \series default
299 aliases in here, out of the core code.
300 \layout Standard
301
302 The new system should allow for more seamless upgrading, so that:
303 \layout Itemize
304
305 It automatically recognizes when the config files need updating and does
306 the upgrade.
307 \layout Itemize
308
309 It simply adds the new options to the user's config file without overwriting
310 it.
311 The current system is annoying since users need to manually re-sync their
312 configuration after every update.
313 \layout Itemize
314
315 It detects obsolete options and informs the user to remove them from his
316 config file.
317 \layout Standard
318
319 Here's a copy of Arnd Baecker suggestions on the matter:
320 \layout Standard
321
322 1.) upgrade: it might be nice to have an "auto" upgrade procedure: i.e.
323 imagine that IPython is installed system-wide and gets upgraded, how does
324 a user know, that an upgrade of the stuff in ~/.ipython is necessary ? So
325 maybe one has to a keep a version number in ~/.ipython and if there is a
326 mismatch with the started ipython, then invoke the upgrade procedure.
327 \layout Standard
328
329 2.) upgrade: I find that replacing the old files in ~/.ipython (after copying
330 them to .old not optimal (for example, after every update, I have to change
331 my color settings (and some others) in ~/.ipython/ipthonrc).
332 So somehow keeping the old files and merging the new features would be
333 nice.
334 (but how to distinguish changes from version to version with changes made
335 by the user ?) For, example, I would have to change in GnuplotMagic.py gnuplot_m
336 ouse to 1 after every upgrade ...
337 \layout Standard
338
339 This is surely a minor point - also things will change during the "BIG"
340 rewrite, but maybe this is a point to keep in mind for this ?
341 \layout Standard
342
343 3.) upgrade: old, sometimes obsolete files stay in the ~/.ipython subdirectory.
344 (hmm, maybe one could move all these into some subdirectory, but which
345 name for that (via version-number ?) ?)
346 \layout Subsection
347
348 Command line options
349 \layout Standard
350
351 It would be great to design the command-line processing system so that it
352 can be dynamically modified in some easy way.
353 This would allow systems based on IPython to include their own command-line
354 processing to either extend or fully replace IPython's.
355 Probably moving to the new optparse library (also known as optik) will
356 make this a lot easier.
357 \layout Section
358
359 OS-dependent code
360 \layout Standard
361
362 Options which are OS-dependent (such as colors and aliases) should be loaded
363 via include files.
364 That is, the general file will have:
365 \layout Standard
366
367
368 \family typewriter
369 if os.name == 'posix':
370 \newline
371 include('ipythonrc-posix.py')
372 \newline
373 elif os.name == 'nt':
374 \newline
375 include('ipythonrc-nt.py')...
376 \layout Standard
377
378 In the
379 \family typewriter
380 -posix
381 \family default
382 ,
383 \family typewriter
384 -nt
385 \family default
386 , etc.
387 files we'll set all os-specific options.
388 \layout Section
389
390 Merging with other shell systems
391 \layout Standard
392
393 This is listed before the big design issues, as it is something which should
394 be kept in mind when that design is made.
395 \layout Standard
396
397 The following shell systems are out there and I think the whole design of
398 IPython should try to be modular enough to make it possible to integrate
399 its features into these.
400 In all cases IPython should exist as a stand-alone, terminal based program.
401 But it would be great if users of these other shells (some of them which
402 have very nice features of their own, especially the graphical ones) could
403 keep their environment but gain IPython's features.
404 \layout List
405 \labelwidthstring 00.00.0000
406
407 IDLE This is the standard, distributed as part of Python.
408
409 \layout List
410 \labelwidthstring 00.00.0000
411
412 pyrepl
413 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mwh/hacks/pyrepl.html}
414
415 \end_inset
416
417 .
418 This is a text (curses-based) shell-like replacement which doesn't have
419 some of IPython's features, but has a crucially useful (and hard to implement)
420 one: full multi-line editing.
421 This turns the interactive interpreter into a true code testing and development
422 environment.
423
424 \layout List
425 \labelwidthstring 00.00.0000
426
427 PyCrust
428 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/pycrust}
429
430 \end_inset
431
432 .
433 Very nice, wxWindows based system.
434 \layout List
435 \labelwidthstring 00.00.0000
436
437 PythonWin
438 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
439
440 \end_inset
441
442 .
443 Similar to PyCrust in some respects, a very good and free Python development
444 environment for Windows systems.
445 \layout Section
446
447 Class design
448 \layout Standard
449
450 This is the big one.
451 Currently classes use each other in a very messy way, poking inside one
452 another for data and methods.
453 ipmaker() adds tons of stuff to the main __IP instance by hand, and the
454 mix-ins used (Logger, Magic, etc) mean the final __IP instance has a million
455 things in it.
456 All that needs to be cleanly broken down with well defined interfaces amongst
457 the different classes, and probably no mix-ins.
458 \layout Standard
459
460 The best approach is probably to have all the sub-systems which are currently
461 mixins be fully independent classes which talk back only to the main instance
462 (and
463 \series bold
464 not
465 \series default
466 to each other).
467 In the main instance there should be an object whose job is to handle communica
468 tion with the sub-systems.
469 \layout Standard
470
471 I should probably learn a little UML and diagram this whole thing before
472 I start coding.
473 \layout Subsection
474
475 Magic
476 \layout Standard
477
478 Now all methods which will become publicly available are called Magic.magic_name,
479 the magic_ should go away.
480 Then, Magic instead of being a mix-in should simply be an attribute of
481 __IP:
482 \layout Standard
483
484 __IP.Magic = Magic()
485 \layout Standard
486
487 This will then give all the magic functions as __IP.Magic.name(), which is
488 much cleaner.
489 This will also force a better separation so that Magic doesn't poke inside
490 __IP so much.
491 In the constructor, Magic should get whatever information it needs to know
492 about __IP (even if it means a pointer to __IP itself, but at least we'll
493 know where it is.
494 Right now since it's a mix-in, there's no way to know which variables belong
495 to whom).
496 \layout Standard
497
498 Build a class MagicFunction so that adding new functions is a matter of:
499 \layout Standard
500
501
502 \family typewriter
503 my_magic = MagicFunction(category = 'System utilities')
504 \newline
505 my_magic.__call__ = ...
506 \layout Standard
507
508 Features:
509 \layout Itemize
510
511 The class constructor should automatically register the functions and keep
512 a table with category sections for easy sorting/viewing.
513 \layout Itemize
514
515 The object interface must allow automatic building of a GUI for them.
516 This requires registering the options the command takes, the number of
517 arguments, etc, in a formal way.
518 The advantage of this approach is that it allows not only to add GUIs to
519 the magics, but also for a much more intelligent building of docstrings,
520 and better parsing of options and arguments.
521 \layout Standard
522
523 Also think through better an alias system for magics.
524 Since the magic system is like a command shell inside ipython, the relation
525 between these aliases and system aliases should be cleanly thought out.
526 \layout Subsection
527
528 Color schemes
529 \layout Standard
530
531 These should be loaded from some kind of resource file so they are easier
532 to modify by the user.
533 \layout Section
534
535 Hooks
536 \layout Standard
537
538 IPython should have a modular system where functions can register themselves
539 for certain tasks.
540 Currently changing functionality requires overriding certain specific methods,
541 there should be a clean API for this to be done.
542 \layout Subsection
543
544 whos hook
545 \layout Standard
546
547 This was a very nice suggestion from Alexander Schmolck <a.schmolck@gmx.net>:
548 \layout Standard
549
550 2.
551 I think it would also be very helpful if there where some sort of hook
552 for ``whos`` that let one customize display formaters depending on the
553 object type.
554 \layout Standard
555
556 For example I'd rather have a whos that formats an array like:
557 \layout Standard
558
559
560 \family typewriter
561 Variable Type Data/Length
562 \newline
563 ------------------------------
564 \newline
565 a array size: 4x3 type: 'Float'
566 \layout Standard
567
568 than
569 \layout Standard
570
571
572 \family typewriter
573 Variable Type Data/Length
574 \newline
575 ------------------------------
576 \newline
577 a array [[ 0.
578 1.
579 2.
580 3<...> 8.
581 9.
582 10.
583 11.]]
584 \layout Section
585
586 Parallel support
587 \layout Standard
588
589 For integration with graphical shells and other systems, it will be best
590 if ipython is split into a kernel/client model, much like Mathematica works.
591 This simultaneously opens the door for support of interactive parallel
592 computing.
593 Currenlty %bg provides a threads-based proof of concept, and Brian Granger's
594 XGrid project is a much more realistic such system.
595 The new design should integrates ideas as core elements.
596 Some notes from Brian on this topic:
597 \layout Standard
598
599 1.
600 How should the remote python server/kernel be designed? Multithreaded?
601 Blocking? Connected/disconnected modes? Load balancing?
602 \layout Standard
603
604 2.
605 What APi/protocol should the server/kernel expose to clients?
606 \layout Standard
607
608 3.
609 How should the client classes (which the user uses to interact with the
610 cluster) be designed?
611 \layout Standard
612
613 4.
614 What API should the client classes expose?
615 \layout Standard
616
617 5.
618 How should the client API be wrapped in a few simple magic functions?
619 \layout Standard
620
621 6.
622 How should security be handled?
623 \layout Standard
624
625 7.
626 How to work around the issues of the GIL and threads?
627 \layout Standard
628
629 I think the most important things to work out are the client API (#4) the
630 server/kernel API/protocol (#2) and the magic function API (#5).
631 We should let these determine the design and architecture of the components.
632 \layout Standard
633
634 One other thing.
635 What is your impression of twisted? I have been looking at it and it looks
636 like a _very_ powerful set of tools for this type of stuff.
637 I am wondering if it might make sense to think about using twisted for
638 this project.
639 \layout Section
640
641 Manuals
642 \layout Standard
643
644 The documentation should be generated from docstrings for the command line
645 args and all the magic commands.
646 Look into one of the simple text markup systems to see if we can get latex
647 (for reLyXing later) out of this.
648 Part of the build command would then be to make an update of the docs based
649 on this, thus giving more complete manual (and guaranteed to be in sync
650 with the code docstrings).
651 \layout Standard
652
653 [PARTLY DONE] At least now all magics are auto-documented, works farily
654 well.
655 Limited Latex formatting yet.
656 \layout Subsection
657
658 Integration with pydoc-help
659 \layout Standard
660
661 It should be possible to have access to the manual via the pydoc help system
662 somehow.
663 This might require subclassing the pydoc help, or figuring out how to add
664 the IPython docs in the right form so that help() finds them.
665 \layout Standard
666
667 Some comments from Arnd and my reply on this topic:
668 \layout Standard
669
670 > ((Generally I would like to have the nice documentation > more easily
671 accessable from within ipython ...
672 > Many people just don't read documentation, even if it is > as good as
673 the one of IPython ))
674 \layout Standard
675
676 That's an excellent point.
677 I've added a note to this effect in new_design.
678 Basically I'd like help() to naturally access the IPython docs.
679 Since they are already there in html for the user, it's probably a matter
680 of playing a bit with pydoc to tell it where to find them.
681 It would definitely make for a much cleaner system.
682 Right now the information on IPython is:
683 \layout Standard
684
685 -ipython --help at the command line: info on command line switches
686 \layout Standard
687
688 -? at the ipython prompt: overview of IPython
689 \layout Standard
690
691 -magic at the ipython prompt: overview of the magic system
692 \layout Standard
693
694 -external docs (html/pdf)
695 \layout Standard
696
697 All that should be better integrated seamlessly in the help() system, so
698 that you can simply say:
699 \layout Standard
700
701 help ipython -> full documentation access
702 \layout Standard
703
704 help magic -> magic overview
705 \layout Standard
706
707 help profile -> help on current profile
708 \layout Standard
709
710 help -> normal python help access.
711 \layout Section
712
713 Graphical object browsers
714 \layout Standard
715
716 I'd like a system for graphically browsing through objects.
717
718 \family typewriter
719 @obrowse
720 \family default
721 should open a widged with all the things which
722 \family typewriter
723 @who
724 \family default
725 lists, but cliking on each object would open a dedicated object viewer
726 (also accessible as
727 \family typewriter
728 @oview <object>
729 \family default
730 ).
731 This object viewer could show a summary of what
732 \family typewriter
733 <object>?
734 \family default
735 currently shows, but also colorize source code and show it via an html
736 browser, show all attributes and methods of a given object (themselves
737 openable in their own viewers, since in Python everything is an object),
738 links to the parent classes, etc.
739 \layout Standard
740
741 The object viewer widget should be extensible, so that one can add methods
742 to view certain types of objects in a special way (for example, plotting
743 Numeric arrays via grace or gnuplot).
744 This would be very useful when using IPython as part of an interactive
745 complex system for working with certain types of data.
746 \layout Standard
747
748 I should look at what PyCrust has to offer along these lines, at least as
749 a starting point.
750 \layout Section
751
752 Miscellaneous small things
753 \layout Itemize
754
755 Collect whatever variables matter from the environment in some globals for
756 __IP, so we're not testing for them constantly (like $HOME, $TERM, etc.)
757 \layout Section
758
759 Session restoring
760 \layout Standard
761
762 I've convinced myself that session restore by log replay is too fragile
763 and tricky to ever work reliably.
764 Plus it can be dog slow.
765 I'd rather have a way of saving/restoring the *current* memory state of
766 IPython.
767 I tried with pickle but failed (can't pickle modules).
768 This seems the right way to do it to me, but it will have to wait until
769 someone tells me of a robust way of dumping/reloading *all* of the user
770 namespace in a file.
771 \layout Standard
772
773 Probably the best approach will be to pickle as much as possible and record
774 what can not be pickled for manual reload (such as modules).
775 This is not trivial to get to work reliably, so it's best left for after
776 the code restructuring.
777 \layout Standard
778
779 The following issues exist (old notes, see above paragraph for my current
780 take on the issue):
781 \layout Itemize
782
783 magic lines aren't properly re-executed when a log file is reloaded (and
784 some of them, like clear or run, may change the environment).
785 So session restore isn't 100% perfect.
786 \layout Itemize
787
788 auto-quote/parens lines aren't replayed either.
789 All this could be done, but it needs some work.
790 Basically it requires re-running the log through IPython itself, not through
791 python.
792 \layout Itemize
793
794 _p variables aren't restored with a session.
795 Fix: same as above.
796 \layout Section
797
798 Tips system
799 \layout Standard
800
801 It would be nice to have a tip() function which gives tips to users in some
802 situations, but keeps track of already-given tips so they aren't given
803 every time.
804 This could be done by pickling a dict of given tips to IPYTHONDIR.
805 \layout Section
806
807 TAB completer
808 \layout Standard
809
810 Some suggestions from Arnd Baecker:
811 \layout Standard
812
813 a) For file related commands (ls, cat, ...) it would be nice to be able to
814 TAB complete the files in the current directory.
815 (once you started typing something which is uniquely a file, this leads
816 to this effect, apart from going through the list of possible completions
817 ...).
818 (I know that this point is in your documentation.)
819 \layout Standard
820
821 More general, this might lead to something like command specific completion
822 ?
823 \layout Standard
824
825 Here's John Hunter's suggestion:
826 \layout Standard
827
828 The *right way to do it* would be to make intelligent or customizable choices
829 about which namespace to add to the completion list depending on the string
830 match up to the prompt, eg programmed completions.
831 In the simplest implementation, one would only complete on files and directorie
832 s if the line preceding the tab press matched 'cd ' or 'run ' (eg you don't
833 want callable showing up in 'cd ca<TAB>')
834 \layout Standard
835
836 In a more advanced scenario, you might imaging that functions supplied the
837 TAB namespace, and the user could configure a dictionary that mapped regular
838 expressions to namespace providing functions (with sensible defaults).
839 Something like
840 \layout Standard
841
842 completed = {
843 \newline
844 '^cd
845 \backslash
846 s+(.*)' : complete_files_and_dirs,
847 \newline
848 '^run
849 \backslash
850 s+(.*)' : complete_files_and_dirs,
851 \newline
852 '^run
853 \backslash
854 s+(-.*)' : complete_run_options,
855 \newline
856 }
857 \layout Standard
858
859 I don't know if this is feasible, but I really like programmed completions,
860 which I use extensively in tcsh.
861 My feeling is that something like this is eminently doable in ipython.
862 \layout Standard
863
864 /JDH
865 \layout Standard
866
867 For something like this to work cleanly, the magic command system needs
868 also a clean options framework, so all valid options for a given magic
869 can be extracted programatically.
870 \layout Section
871
872 Debugger
873 \layout Standard
874
875 Current system uses a minimally tweaked pdb.
876 Fine-tune it a bit, to provide at least:
877 \layout Itemize
878
879 Tab-completion in each stack frame.
880 See email to Chris Hart for details.
881 \layout Itemize
882
883 Object information via ? at least.
884 Break up magic_oinfo a bit so that pdb can call it without loading all
885 of IPython.
886 If possible, also have the other magics for object study: doc, source,
887 pdef and pfile.
888 \layout Itemize
889
890 Shell access via !
891 \layout Itemize
892
893 Syntax highlighting in listings.
894 Use py2html code, implement color schemes.
895 \layout Section
896
897 A Python-based system shell - pysh?
898 \layout Standard
899
900 Note: as of IPython 0.6.1, most of this functionality has actually been implemente
901 d.
902 \layout Standard
903
904 This section is meant as a working draft for discussions on the possibility
905 of having a python-based system shell.
906 It is the result of my own thinking about these issues as much of discussions
907 on the ipython lists.
908 I apologize in advance for not giving individual credit to the various
909 contributions, but right now I don't have the time to track down each message
910 from the archives.
911 So please consider this as the result of a collective effort by the ipython
912 user community.
913 \layout Standard
914
915 While IPyhton is (and will remain) a python shell first, it does offer a
916 fair amount of system access functionality:
917 \layout Standard
918
919 - ! and !! for direct system access,
920 \layout Standard
921
922 - magic commands which wrap various system commands,
923 \layout Standard
924
925 - @sc and @sx, for shell output capture into python variables,
926 \layout Standard
927
928 - @alias, for aliasing system commands.
929 \layout Standard
930
931 This has prompted many users, over time, to ask for a way of extending ipython
932 to the point where it could be used as a full-time replacement over typical
933 user shells like bash, csh or tcsh.
934 While my interest in ipython is such that I'll concentrate my personal
935 efforts on other fronts (debugging, architecture, improvements for scientific
936 use, gui access), I will be happy to do anything which could make such
937 a development possible.
938 It would be the responsibility of someone else to maintain the code, but
939 I would do all necessary architectural changes to ipython for such an extension
940 to be feasible.
941 \layout Standard
942
943 I'll try to outline here what I see as the key issues which need to be taken
944 into account.
945 This document should be considered an evolving draft.
946 Feel free to submit comments/improvements, even in the form of patches.
947 \layout Standard
948
949 In what follows, I'll represent the hypothetical python-based shell ('pysh'
950 for now) prompt with '>>'.
951 \layout Subsection
952
953 Basic design principles
954 \layout Standard
955
956 I think the basic design guideline should be the following: a hypothetical
957 python system shell should behave, as much as possible, like a normal shell
958 that users are familiar with (bash, tcsh, etc).
959 This means:
960 \layout Standard
961
962 1.
963 System commands can be issued directly at the prompt with no special syntax:
964 \layout Standard
965
966 >> ls
967 \layout Standard
968
969 >> xemacs
970 \layout Standard
971
972 should just work like a user expects.
973 \layout Standard
974
975 2.
976 The facilities of the python language should always be available, like
977 they are in ipython:
978 \layout Standard
979
980 >> 3+4
981 \newline
982 7
983 \layout Standard
984
985 3.
986 It should be possible to easily capture shell output into a variable.
987 bash and friends use backquotes, I think using a command (@sc) like ipython
988 currently does is an acceptable compromise.
989 \layout Standard
990
991 4.
992 It should also be possible to expand python variables/commands in the middle
993 of system commands.
994 I thihk this will make it necessary to use $var for name expansions:
995 \layout Standard
996
997 >> var='hello' # var is a Python variable
998 \newline
999 >> print var hello # This is the result of a Python print command
1000 \newline
1001 >> echo $var hello # This calls the echo command, expanding 'var'.
1002 \layout Standard
1003
1004 5.
1005 The above capabilities should remain possible for multi-line commands.
1006 One of the most annoying things I find about tcsh, is that I never quite
1007 remember the syntactic details of looping.
1008 I often want to do something at the shell which involves a simple loop,
1009 but I can never remember how to do it in tcsh.
1010 This often means I just write a quick throwaway python script to do it
1011 (Perl is great for this kind of quick things, but I've forgotten most its
1012 syntax as well).
1013 \layout Standard
1014
1015 It should be possible to write code like:
1016 \layout Standard
1017
1018 >> for ext in ['.jpg','.gif']:
1019 \newline
1020 ..
1021 ls file$ext
1022 \layout Standard
1023
1024 And have it work as 'ls file.jpg;ls file.gif'.
1025 \layout Subsection
1026
1027 Smaller details
1028 \layout Standard
1029
1030 If the above are considered as valid guiding principles for how such a python
1031 system shell should behave, then some smaller considerations and comments
1032 to keep in mind are listed below.
1033 \layout Standard
1034
1035 - it's ok for shell builtins (in this case this includes the python language)
1036 to override system commands on the path.
1037 See tcsh's 'time' vs '/usr/bin/time'.
1038 This settles the 'print' issue and related.
1039 \layout Standard
1040
1041 - pysh should take
1042 \layout Standard
1043
1044 foo args
1045 \layout Standard
1046
1047 as a command if (foo args is NOT valid python) and (foo is in $PATH).
1048 \layout Standard
1049
1050 If the user types
1051 \layout Standard
1052
1053 >> ./foo args
1054 \layout Standard
1055
1056 it should be considered a system command always.
1057 \layout Standard
1058
1059 - _, __ and ___ should automatically remember the previous 3 outputs captured
1060 from stdout.
1061 In parallel, there should be _e, __e and ___e for stderr.
1062 Whether capture is done as a single string or in list mode should be a
1063 user preference.
1064 If users have numbered prompts, ipython's full In/Out cache system should
1065 be available.
1066 \layout Standard
1067
1068 But regardless of how variables are captured, the printout should be like
1069 that of a plain shell (without quotes or braces to indicate strings/lists).
1070 The everyday 'feel' of pysh should be more that of bash/tcsh than that
1071 of ipython.
1072 \layout Standard
1073
1074 - filename completion first.
1075 Tab completion could work like in ipython, but with the order of priorities
1076 reversed: first files, then python names.
1077 \layout Standard
1078
1079 - configuration via standard python files.
1080 Instead of 'setenv' you'd simply write into the os.environ[] dictionary.
1081 This assumes that IPython itself has been fixed to be configured via normal
1082 python files, instead of the current clunky ipythonrc format.
1083 \layout Standard
1084
1085 - IPython can already configure the prompt in fairly generic ways.
1086 It should be able to generate almost any kind of prompt which bash/tcsh
1087 can (within reason).
1088 \layout Standard
1089
1090 - Keep the Magics system.
1091 They provide a lightweight syntax for configuring and modifying the state
1092 of the user's session itself.
1093 Plus, they are an extensible system so why not give the users one more
1094 tool which is fairly flexible by nature? Finally, having the @magic optional
1095 syntax allows a user to always be able to access the shell's control system,
1096 regardless of name collisions with defined variables or system commands.
1097 \layout Standard
1098
1099 But we need to move all magic functionality into a protected namespace,
1100 instead of the current messy name-mangling tricks (which don't scale well).
1101
1102 \layout Section
1103
1104 Future improvements
1105 \layout Itemize
1106
1107 When from <mod> import * is used, first check the existing namespace and
1108 at least issue a warning on screen if names are overwritten.
1109 \layout Itemize
1110
1111 Auto indent? Done, for users with readline support.
1112 \layout Subsection
1113
1114 Better completion a la zsh
1115 \layout Standard
1116
1117 This was suggested by Arnd:
1118 \layout Standard
1119
1120 > >\SpecialChar ~
1121 \SpecialChar ~
1122 \SpecialChar ~
1123 More general, this might lead to something like
1124 \layout Standard
1125
1126 > >\SpecialChar ~
1127 \SpecialChar ~
1128 \SpecialChar ~
1129 command specific completion ?
1130 \layout Standard
1131
1132 >
1133 \layout Standard
1134
1135 > I'm not sure what you mean here.
1136 \layout Standard
1137
1138 \SpecialChar ~
1139
1140 \layout Standard
1141
1142 Sorry, that was not understandable, indeed ...
1143 \layout Standard
1144
1145 I thought of something like
1146 \layout Standard
1147
1148 \SpecialChar ~
1149 - cd and then use TAB to go through the list of directories
1150 \layout Standard
1151
1152 \SpecialChar ~
1153 - ls and then TAB to consider all files and directories
1154 \layout Standard
1155
1156 \SpecialChar ~
1157 - cat and TAB: only files (no directories ...)
1158 \layout Standard
1159
1160 \SpecialChar ~
1161
1162 \layout Standard
1163
1164 For zsh things like this are established by defining in .zshrc
1165 \layout Standard
1166
1167 \SpecialChar ~
1168
1169 \layout Standard
1170
1171 compctl -g '*.dvi' xdvi
1172 \layout Standard
1173
1174 compctl -g '*.dvi' dvips
1175 \layout Standard
1176
1177 compctl -g '*.tex' latex
1178 \layout Standard
1179
1180 compctl -g '*.tex' tex
1181 \layout Standard
1182
1183 ...
1184 \layout Section
1185
1186 Outline of steps
1187 \layout Standard
1188
1189 Here's a rough outline of the order in which to start implementing the various
1190 parts of the redesign.
1191 The first 'test of success' should be a clean pychecker run (not the mess
1192 we get right now).
1193 \layout Itemize
1194
1195 Make Logger and Magic not be mixins but attributes of the main class.
1196
1197 \begin_deeper
1198 \layout Itemize
1199
1200 Magic should have a pointer back to the main instance (even if this creates
1201 a recursive structure) so it can control it with minimal message-passing
1202 machinery.
1203
1204 \layout Itemize
1205
1206 Logger can be a standalone object, simply with a nice, clean interface.
1207 \layout Itemize
1208
1209 Logger currently handles part of the prompt caching, but other parts of
1210 that are in the prompts class itself.
1211 Clean up.
1212 \end_deeper
1213 \layout Itemize
1214
1215 Change to python-based config system.
1216 \layout Itemize
1217
1218 Move make_IPython() into the main shell class, as part of the constructor.
1219 Do this
1220 \emph on
1221 after
1222 \emph default
1223 the config system has been changed, debugging will be a lot easier then.
1224 \layout Itemize
1225
1226 Merge the embeddable class and the normal one into one.
1227 After all, the standard ipython script
1228 \emph on
1229 is
1230 \emph default
1231 a python program with IPython embedded in it.
1232 There's no need for two separate classes (
1233 \emph on
1234 maybe
1235 \emph default
1236 keep the old one around for the sake of backwards compatibility).
1237 \layout Section
1238
1239 Ville Vainio's suggestions
1240 \layout Standard
1241
1242 Some notes sent in by Ville Vainio
1243 \family typewriter
1244 <vivainio@kolumbus.fi>
1245 \family default
1246 on Tue, 29 Jun 2004.
1247 Keep here for reference, some of it replicates things already said above.
1248 \layout Standard
1249
1250 Current ipython seems to "special case" lots of stuff - aliases, magics
1251 etc.
1252 It would seem to yield itself to a simpler and more extensible architecture,
1253 consisting of multple dictionaries, where just the order of search is determine
1254 d by profile/prefix.
1255 All the functionality would just be "pushed" to ipython core, i.e.
1256 the objects that represent the functionality are instantiated on "plugins"
1257 and they are registered with ipython core.
1258 i.e.
1259 \layout Standard
1260
1261 def magic_f(options, args): pass
1262 \layout Standard
1263
1264 m = MyMagic(magic_f) m.arghandler = stockhandlers.OptParseArgHandler m.options
1265 = ....
1266 # optparse options, for easy passing to magic_f and help display
1267 \layout Standard
1268
1269 # note that arghandler takes a peek at the instance, sees options, and proceeds
1270 # accordingly.
1271 Various arg handlers can ask for arbitrary options.
1272 # some handler might optionally glob the filenames, search data folders
1273 for filenames etc.
1274 \layout Standard
1275
1276 ipythonregistry.register(category = "magic", name = "mymagic", obj = m)
1277 \layout Standard
1278
1279 I bet most of the current functionality could easily be added to such a
1280 registry by just instantiating e.g.
1281 "Magic" class and registering all the functions with some sensible default
1282 args.
1283 Supporting legacy stuff in general would be easy - just implement new handlers
1284 (arg and otherwise) for new stuff, and have the old handlers around forever
1285 / as long as is deemed appropriate.
1286 The 'python' namespace (locals() + globals()) should be special, of course.
1287 \layout Standard
1288
1289 It should be easy to have arbitrary number of "categories" (like 'magic',
1290 'shellcommand','projectspecific_myproject', 'projectspecific_otherproject').
1291 It would only influence the order in which the completions are suggested,
1292 and in case of name collision which one is selected.
1293 Also, I think all completions should be shown, even the ones in "later"
1294 categories in the case of a match in an "earlier" category.
1295 \layout Standard
1296
1297 The "functionality object" might also have a callable object 'expandarg',
1298 and ipython would run it (with the arg index) when tab completion is attempted
1299 after typing the function name.
1300 It would return the possible completions for that particular command...
1301 or None to "revert to default file completions".
1302 Such functionality could be useful in making ipython an "operating console"
1303 of a sort.
1304 I'm talking about:
1305 \layout Standard
1306
1307 >> lscat reactor # list commands in category - reactor is "project specific"
1308 category
1309 \layout Standard
1310
1311 r_operate
1312 \layout Standard
1313
1314 >> r_operate <tab> start shutdown notify_meltdown evacuate
1315 \layout Standard
1316
1317 >> r_operate shutdown <tab>
1318 \layout Standard
1319
1320 1 2 5 6 # note that 3 and 4 are already shut down
1321 \layout Standard
1322
1323 >> r_operate shutdown 2
1324 \layout Standard
1325
1326 Shutting down..
1327 ok.
1328 \layout Standard
1329
1330 >> r_operate start <tab>
1331 \layout Standard
1332
1333 2 3 4 # 2 was shut down, can be started now
1334 \layout Standard
1335
1336 >> r_operate start 2
1337 \layout Standard
1338
1339 Starting....
1340 ok.
1341 \layout Standard
1342
1343 I'm talking about having a super-configurable man-machine language here!
1344 Like cmd.Cmd on steroids, as a free addition to ipython!
1345 \the_end
@@ -0,0 +1,33 b''
1 .\" Hey, EMACS: -*- nroff -*-
2 .\" First parameter, NAME, should be all caps
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
4 .\" other parameters are allowed: see man(7), man(1)
5 .TH PYCOLOR 1 "March 21, 2003"
6 .\" Please adjust this date whenever revising the manpage.
7 .\"
8 .\" Some roff macros, for reference:
9 .\" .nh disable hyphenation
10 .\" .hy enable hyphenation
11 .\" .ad l left justify
12 .\" .ad b justify to both left and right margins
13 .\" .nf disable filling
14 .\" .fi enable filling
15 .\" .br insert line break
16 .\" .sp <n> insert n+1 empty lines
17 .\" for manpage-specific macros, see man(7)
18 .SH NAME
19 pycolor \- Colorize a python file using ANSI and print to stdout.
20 .SH SYNOPSIS
21 .B pycolor
22 .RI [ options ] " file"
23 .SH DESCRIPTION
24 Prints a colorized version of the input file to standard out.
25 .SH OPTIONS
26 .TP
27 .B \-s <scheme>
28 Give the color scheme to use. Currently only Linux (default),
29 LightBG, and NOColor are implemented.
30 .SH AUTHOR
31 pycolor was written by Fernando Perez <fperez@colorado.edu>.
32 This manual page was written by Jack Moffitt <jack@xiph.org>,
33 for the Debian project (but may be used by others).
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
@@ -0,0 +1,2 b''
1 #!/bin/sh
2 ipython --magic_docstrings > magic.tex No newline at end of file
@@ -0,0 +1,3 b''
1 #!/bin/sh
2 ver=`ipython -V`
3 sed "s/__version__/${ver}/" manual_base.lyx > manual.lyx
@@ -0,0 +1,28 b''
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """IPython -- An enhanced Interactive Python
4
5 This is just the startup wrapper script, kept deliberately to a minimum.
6
7 The shell's mainloop() takes an optional argument, sys_exit (default=0). If
8 set to 1, it calls sys.exit() at exit time. You can use the following code in
9 your PYTHONSTARTUP file:
10
11 import IPython
12 IPython.Shell.IPShell().mainloop(sys_exit=1)
13
14 [or simply IPython.Shell.IPShell().mainloop(1) ]
15
16 and IPython will be your working environment when you start python. The final
17 sys.exit() call will make python exit transparently when IPython finishes, so
18 you don't have an extra prompt to get out of.
19
20 This is probably useful to developers who manage multiple Python versions and
21 don't want to have correspondingly multiple IPython versions. Note that in
22 this mode, there is no way to pass IPython any command-line options, as those
23 are trapped first by Python itself.
24 """
25
26 import IPython
27
28 IPython.Shell.start().mainloop()
@@ -0,0 +1,78 b''
1 #!python
2 """Windows-specific part of the installation"""
3
4 import os, sys
5
6 def create_shortcut_safe(target,description,link_file,*args,**kw):
7 """make a shortcut if it doesn't exist, and register its creation"""
8
9 if not os.path.isfile(link_file):
10 create_shortcut(target, description, link_file,*args,**kw)
11 file_created(link_file)
12
13 def install():
14 """Routine to be run by the win32 installer with the -install switch."""
15
16 from IPython.Release import version
17
18 # Get some system constants
19 prefix = sys.prefix
20 python = prefix + r'\python.exe'
21 # Lookup path to common startmenu ...
22 ip_dir = get_special_folder_path('CSIDL_COMMON_PROGRAMS') + r'\IPython'
23
24 # Some usability warnings at installation time. I don't want them at the
25 # top-level, so they don't appear if the user is uninstalling.
26 try:
27 import ctypes
28 except ImportError:
29 print ('To take full advantage of IPython, you need ctypes from:\n'
30 'http://sourceforge.net/projects/ctypes')
31
32 try:
33 import win32con
34 except ImportError:
35 print ('To take full advantage of IPython, you need pywin32 from:\n'
36 'http://starship.python.net/crew/mhammond/win32/Downloads.html')
37
38 try:
39 import readline
40 except ImportError:
41 print ('To take full advantage of IPython, you need readline from:\n'
42 'http://sourceforge.net/projects/uncpythontools')
43
44 # Create IPython entry ...
45 if not os.path.isdir(ip_dir):
46 os.mkdir(ip_dir)
47 directory_created(ip_dir)
48
49 # Create program shortcuts ...
50 f = ip_dir + r'\IPython.lnk'
51 a = prefix + r'\scripts\ipython'
52 create_shortcut_safe(python,'IPython',f,a)
53
54 f = ip_dir + r'\pysh.lnk'
55 a = prefix + r'\scripts\ipython -p pysh'
56 create_shortcut_safe(python,'pysh',f,a)
57
58 # Create documentation shortcuts ...
59 t = prefix + r'\share\doc\ipython-%s\manual.pdf' % version
60 f = ip_dir + r'\Manual in PDF.lnk'
61 create_shortcut_safe(t,r'IPython Manual - PDF-Format',f)
62
63 t = prefix + r'\share\doc\ipython-%s\manual\manual.html' % version
64 f = ip_dir + r'\Manual in HTML.lnk'
65 create_shortcut_safe(t,'IPython Manual - HTML-Format',f)
66
67 def remove():
68 """Routine to be run by the win32 installer with the -remove switch."""
69 pass
70
71 # main()
72 if len(sys.argv) > 1:
73 if sys.argv[1] == '-install':
74 install()
75 elif sys.argv[1] == '-remove':
76 remove()
77 else:
78 print "Script was called with option %s" % sys.argv[1]
@@ -0,0 +1,6 b''
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """Simple wrapper around PyColorize, which colorizes python sources."""
4
5 import IPython.PyColorize
6 IPython.PyColorize.main()
@@ -0,0 +1,146 b''
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """Setup script for IPython.
4
5 Under Posix environments it works like a typical setup.py script.
6 Under Windows, the command sdist is not supported, since IPython
7 requires utilities, which are not available under Windows."""
8
9 #*****************************************************************************
10 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
11 #
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
15
16 import sys, os
17 from glob import glob
18 from setupext import install_data_ext
19 isfile = os.path.isfile
20
21 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
22 # update it when the contents of directories change.
23 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
24
25 if os.name == 'posix':
26 os_name = 'posix'
27 elif os.name in ['nt','dos']:
28 os_name = 'windows'
29 else:
30 print 'Unsupported operating system:',os.name
31 sys.exit(1)
32
33 # Under Windows, 'sdist' is not supported, since it requires lyxport (and
34 # hence lyx,perl,latex,pdflatex,latex2html,sh,...)
35 if os_name == 'windows' and sys.argv[1] == 'sdist':
36 print 'The sdist command is not available under Windows. Exiting.'
37 sys.exit(1)
38
39 from distutils.core import setup
40
41 # update the manuals when building a source dist
42 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
43 from IPython.genutils import target_update
44 # list of things to be updated. Each entry is a triplet of args for
45 # target_update()
46 to_update = [('doc/magic.tex',
47 ['IPython/Magic.py'],
48 "cd doc && ./update_magic.sh" ),
49
50 ('doc/manual.lyx',
51 ['IPython/Release.py','doc/manual_base.lyx'],
52 "cd doc && ./update_version.sh" ),
53
54 ('doc/manual/manual.html',
55 ['doc/manual.lyx',
56 'doc/magic.tex',
57 'doc/examples/example-gnuplot.py',
58 'doc/examples/example-magic.py',
59 'doc/examples/example-embed.py',
60 'doc/examples/example-embed-short.py',
61 'IPython/UserConfig/ipythonrc',
62 ],
63 "cd doc && "
64 "lyxport -tt --leave --pdf "
65 "--html -o '-noinfo -split +1 -local_icons' manual.lyx"),
66
67 ('doc/new_design.pdf',
68 ['doc/new_design.lyx'],
69 "cd doc && lyxport -tt --pdf new_design.lyx"),
70
71 ('doc/ipython.1.gz',
72 ['doc/ipython.1'],
73 "cd doc && gzip -9c ipython.1 > ipython.1.gz"),
74
75 ('doc/pycolor.1.gz',
76 ['doc/pycolor.1'],
77 "cd doc && gzip -9c pycolor.1 > pycolor.1.gz"),
78 ]
79 for target in to_update:
80 target_update(*target)
81
82 # Release.py contains version, authors, license, url, keywords, etc.
83 execfile(os.path.join('IPython','Release.py'))
84
85 # A little utility we'll need below, since glob() does NOT allow you to do
86 # exclusion on multiple endings!
87 def file_doesnt_endwith(test,endings):
88 """Return true if test is a file and its name does NOT end with any
89 of the strings listed in endings."""
90 if not isfile(test):
91 return False
92 for e in endings:
93 if test.endswith(e):
94 return False
95 return True
96
97 # I can't find how to make distutils create a nested dir. structure, so
98 # in the meantime do it manually. Butt ugly.
99 docdirbase = 'share/doc/ipython-%s' % version
100 manpagebase = 'share/man/man1'
101
102 # We only need to exclude from this things NOT already excluded in the
103 # MANIFEST.in file.
104 exclude = ('.sh','.1.gz')
105 docfiles = filter(lambda f:file_doesnt_endwith(f,exclude),glob('doc/*'))
106
107 examfiles = filter(isfile, glob('doc/examples/*.py'))
108 manfiles = filter(isfile, glob('doc/manual/*.html')) + \
109 filter(isfile, glob('doc/manual/*.css')) + \
110 filter(isfile, glob('doc/manual/*.png'))
111 manpages = filter(isfile, glob('doc/*.1.gz'))
112 cfgfiles = filter(isfile, glob('IPython/UserConfig/*'))
113 scriptfiles = filter(isfile, ['scripts/ipython','scripts/pycolor'])
114
115 # Script to be run by the windows binary installer after the default setup
116 # routine, to add shortcuts and similar windows-only things. Windows
117 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
118 # doesn't find them.
119 if 'bdist_wininst' in sys.argv:
120 if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
121 print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting."
122 sys.exit(1)
123 scriptfiles.append('scripts/ipython_win_post_install.py')
124
125 # Call the setup() routine which does most of the work
126 setup(name = name,
127 version = version,
128 description = description,
129 long_description = long_description,
130 author = authors['Fernando'][0],
131 author_email = authors['Fernando'][1],
132 url = url,
133 license = license,
134 platforms = platforms,
135 keywords = keywords,
136 packages = ['IPython', 'IPython.Extensions'],
137 scripts = scriptfiles,
138 cmdclass = {'install_data': install_data_ext},
139 data_files = [('data', docdirbase, docfiles),
140 ('data', os.path.join(docdirbase, 'examples'),
141 examfiles),
142 ('data', os.path.join(docdirbase, 'manual'),
143 manfiles),
144 ('data', manpagebase, manpages),
145 ('lib', 'IPython/UserConfig', cfgfiles)]
146 )
@@ -0,0 +1,3 b''
1 # load extended setup modules for distuils
2
3 from install_data_ext import install_data_ext
@@ -0,0 +1,80 b''
1 # install_data_ext.py
2 #
3 # Subclass of normal distutils install_data command to allow more
4 # configurable installation of data files.
5
6 import os
7 from distutils.command.install_data import install_data
8 from distutils.util import change_root, convert_path
9
10 class install_data_ext(install_data):
11
12 def initialize_options(self):
13 self.install_base = None
14 self.install_platbase = None
15 self.install_purelib = None
16 self.install_headers = None
17 self.install_lib = None
18 self.install_scripts = None
19 self.install_data = None
20
21 self.outfiles = []
22 self.root = None
23 self.force = 0
24 self.data_files = self.distribution.data_files
25 self.warn_dir = 1
26
27
28 def finalize_options(self):
29 self.set_undefined_options('install',
30 ('root', 'root'),
31 ('force', 'force'),
32 ('install_base', 'install_base'),
33 ('install_platbase',
34 'install_platbase'),
35 ('install_purelib',
36 'install_purelib'),
37 ('install_headers',
38 'install_headers'),
39 ('install_lib', 'install_lib'),
40 ('install_scripts',
41 'install_scripts'),
42 ('install_data', 'install_data'))
43
44
45 def run(self):
46 """
47 This is where the meat is. Basically the data_files list must
48 now be a list of tuples of 3 entries. The first
49 entry is one of 'base', 'platbase', etc, which indicates which
50 base to install from. The second entry is the path to install
51 too. The third entry is a list of files to install.
52 """
53 for lof in self.data_files:
54 if lof[0]:
55 base = getattr(self, 'install_' + lof[0])
56 else:
57 base = getattr(self, 'install_base')
58 dir = convert_path(lof[1])
59 if not os.path.isabs(dir):
60 dir = os.path.join(base, dir)
61 elif self.root:
62 dir = change_root(self.root, dir)
63 self.mkpath(dir)
64
65 files = lof[2]
66 if len(files) == 0:
67 # If there are no files listed, the user must be
68 # trying to create an empty directory, so add the the
69 # directory to the list of output files.
70 self.outfiles.append(dir)
71 else:
72 # Copy files, adding them to the list of output files.
73 for f in files:
74 f = convert_path(f)
75 (out, _) = self.copy_file(f, dir)
76 #print "DEBUG: ", out # dbg
77 self.outfiles.append(out)
78
79
80 return self.outfiles
@@ -0,0 +1,72 b''
1 #!/usr/bin/env python
2 """Backup directories using rsync. Quick and dirty.
3
4 backup.py config_file final_actions
5 """
6
7 #----------------------------------------------------------------------------
8 # configure in this section
9
10 # all dirs relative to current dir.
11
12 # output directory for backups
13 outdir = ''
14
15 # list directories to backup as a dict with 1 or 0 values for
16 # recursive (or not) descent:
17 to_backup = {}
18
19 # list exclude patterns here (space-separated):
20 # if the pattern ends with a / then it will only match a directory, not a
21 # file, link or device.
22 # see man rsync for more details on the exclude patterns
23 exc_pats = '#*# *~ *.pyc *.pyo *.o '
24
25 # global options for rsync
26 rsync_opts='-v -t -a --delete --delete-excluded'
27
28 #----------------------------------------------------------------------------
29 # real code begins
30 import os,string,re,sys
31 from IPython.genutils import *
32 from IPython.Itpl import itpl
33
34 # config file can redefine final actions
35 def final():
36 pass
37
38 # load config from cmd line config file or default bkprc.py
39 try:
40 execfile(sys.argv[1])
41 except:
42 try:
43 execfile('bkprc.py')
44 except IOError:
45 print 'You need to provide a config file: bkp.py rcfile'
46 sys.exit()
47
48 # make output dir if needed
49 outdir = os.path.expanduser(outdir)
50 try:
51 os.makedirs(outdir)
52 except OSError: # raised if dir already exists -> no need to make it
53 pass
54
55 # build rsync command and call:
56 exclude = re.sub(r'([^\s].*?)(\s|$)',r'--exclude "\1"\2',exc_pats)
57 rsync = itpl('rsync $rsync_opts $exclude')
58
59 # the same can also be done with lists (keep it for reference):
60 #exclude = string.join(['--exclude "'+p+'"' for p in qw(exc_pats)])
61
62 # rsync takes -r as a flag, not 0/1 so translate:
63 rec_flag = {0:'',1:'-r'}
64
65 # loop over user specified directories calling rsync
66 for bakdir,rec in to_backup.items():
67 bakdir = os.path.expanduser(bakdir)
68 xsys(itpl('$rsync $rec_flag[rec] $bakdir $outdir'),
69 debug=0,verbose=1,header='\n### ')
70
71 # final actions?
72 final()
@@ -0,0 +1,22 b''
1 # config file for a quick'n dirty backup script that uses rsync
2
3 # output directory for backups
4 outdir = '~/tmp'
5
6 # list directories to backup as a dict with 1 or 0 values for
7 # recursive (or not) descent:
8 to_backup = {'~/ipython/ipython':1}
9
10 # exclude patterns. anything ending in / is considered a directory
11 exc_pats = '#*# *~ *.o *.pyc *.pyo MANIFEST *.pdf *.flc build/ dist/ ' \
12 ' doc/manual/ doc/manual.lyx ChangeLog.* magic.tex *.1.gz '
13
14 # final actions after doing the backup
15 def final():
16 dbg = 0
17 version = bq('ipython -V')
18 out_tgz = outdir+'/ipython-'+version+'.tgz'
19 xsys(itpl('cd $outdir; pwd;tar -czf $out_tgz ipython'),debug=dbg,verbose=1)
20 #xsys(itpl('cp $out_tgz /mnt/card/fperez/ipython'),debug=dbg,verbose=1)
21 xsys(itpl('mv $out_tgz ~/ipython/backup'),debug=dbg,verbose=1)
22 xsys(itpl('rm -rf ${outdir}/ipython'),debug=dbg,verbose=1)
@@ -0,0 +1,99 b''
1 #!/bin/sh
2 # IPython release script
3
4 PYVER=`python -V 2>&1 | awk '{print $2}' | awk -F '.' '{print $1$2}' `
5 version=`ipython -Version`
6 ipdir=~/ipython/ipython
7
8 echo
9 echo "Releasing IPython version $version"
10 echo "=================================="
11
12 echo "Marking ChangeLog with release information and making NEWS file..."
13
14 # Stamp changelog and save a copy of the status at each version, in case later
15 # we want the NEWS file to start from a point before the very last release (if
16 # very small interim releases have no significant changes).
17
18 cd $ipdir/doc
19 cp ChangeLog ChangeLog.old
20 cp ChangeLog ChangeLog.$version
21 daystamp=`date +%Y-%m-%d`
22 echo $daystamp " ***" Released version $version > ChangeLog
23 echo >> ChangeLog
24 cat ChangeLog.old >> ChangeLog
25 rm ChangeLog.old
26
27 # Build NEWS file
28 echo "Changes between the last two releases (major or minor)" > NEWS
29 echo "Note that this is an auto-generated diff of the ChangeLogs" >> NEWS
30 echo >> NEWS
31 diff ChangeLog.previous ChangeLog | grep -v '^0a' | sed 's/^> //g' >> NEWS
32 cp ChangeLog ChangeLog.previous
33
34 # Clean up build/dist directories
35 rm -rf $ipdir/build/*
36 rm -rf $ipdir/dist/*
37
38 # Perform local backup
39 cd $ipdir/tools
40 ./bkp.py
41
42 # Build source and binary distros
43 cd $ipdir
44 ./setup.py sdist --formats=gztar
45 #./setup.py bdist_rpm --release=py$PYVER
46 python2.3 ./setup.py bdist_rpm --release=py23 --python=/usr/bin/python2.3
47
48 # A 2.4-specific RPM, where we must use the --python option to ensure that
49 # the resulting RPM is really built with 2.4 (so things go to
50 # lib/python2.4/...)
51 python2.4 ./setup.py bdist_rpm --release=py24 --python=/usr/bin/python2.4
52
53 # Call the windows build separately, so that the extra Windows scripts don't
54 # get pulled into Unix builds (setup.py has code which checks for
55 # bdist_wininst)
56 #./setup.py bdist_wininst --install-script=ipython_win_post_install.py
57
58 # For now, make the win32 installer with a hand-built 2.3.5 python, which is
59 # the only one that fixes a crash in the post-install phase.
60 $HOME/tmp/local/bin/python2.3 setup.py bdist_wininst \
61 --install-script=ipython_win_post_install.py
62
63
64 # Register with the Python Package Index (PyPI)
65 echo "Registering with PyPI..."
66 cd $ipdir
67 ./setup.py register
68
69 # Upload all files
70 cd $ipdir/dist
71 echo "Uploading distribution files..."
72 scp * fperez@scipy.org:www/dist/
73
74 echo "Uploading backup files..."
75 cd ~/ipython/backup
76 scp `ls -1tr | tail -1` fperez@scipy.org:www/backup/
77
78 echo "Updating webpage..."
79 cd $ipdir/doc
80 www=~/ipython/homepage
81 cp ChangeLog NEWS $www
82 rm -rf $www/doc/*
83 cp -r manual.pdf manual/ $www/doc
84 cd $www
85 ./update
86
87 # Alert package maintainers
88 echo "Alerting package maintainers..."
89 maintainers='fperez@colorado.edu ariciputi@users.sourceforge.net jack@xiph.org tretkowski@inittab.de dryice@hotpop.com'
90 #maintainers='fperez@colorado.edu'
91
92 for email in $maintainers
93 do
94 echo "Emailing $email..."
95 mail -s "[Package maintainer notice] A new IPython is out. Version: $version" \
96 $email < NEWS
97 done
98
99 echo "Done!"
@@ -0,0 +1,27 b''
1 #!/bin/sh
2
3 # release test
4 PYVER=`python -V 2>&1 | awk '{print $2}' | awk -F '.' '{print $1$2}' `
5
6 # clean up build/dist directories
7 rm -rf ~/ipython/ipython/build/*
8 rm -rf ~/ipython/ipython/dist/*
9
10 # build source distros
11 cd ~/ipython/ipython
12
13 ./setup.py sdist --formats=gztar
14
15 #./setup.py bdist_rpm --release=py$PYVER
16 python2.3 ./setup.py bdist_rpm --release=py23 --python=/usr/bin/python2.3
17 python2.4 ./setup.py bdist_rpm --release=py24 --python=/usr/bin/python2.4
18
19 # Call the windows build separately, so that the extra Windows scripts don't
20 # get pulled into Unix builds (setup.py has code which checks for
21 # bdist_wininst)
22 #./setup.py bdist_wininst --install-script=ipython_win_post_install.py
23
24 # For now, make the win32 installer with a hand-built 2.3.5 python, which is
25 # the only one that fixes a crash in the post-install phase.
26 $HOME/tmp/local/bin/python2.3 setup.py bdist_wininst \
27 --install-script=ipython_win_post_install.py
@@ -0,0 +1,130 b''
1 #!python
2 """Windows-specific part of the installation"""
3
4 import os, sys
5
6 try:
7 import shutil,pythoncom
8 from win32com.shell import shell
9 import _winreg as wreg
10 except ImportError:
11 print """
12 You seem to be missing the PythonWin extensions necessary for automatic
13 installation. You can get them (free) from
14 http://starship.python.net/crew/mhammond/
15
16 Please see the manual for details if you want to finish the installation by
17 hand, or get PythonWin and repeat the procedure.
18
19 Press <Enter> to exit this installer."""
20 raw_input()
21 sys.exit()
22
23
24 def make_shortcut(fname,target,args='',start_in='',comment='',icon=None):
25 """Make a Windows shortcut (.lnk) file.
26
27 make_shortcut(fname,target,args='',start_in='',comment='',icon=None)
28
29 Arguments:
30 fname - name of the final shortcut file (include the .lnk)
31 target - what the shortcut will point to
32 args - additional arguments to pass to the target program
33 start_in - directory where the target command will be called
34 comment - for the popup tooltips
35 icon - optional icon file. This must be a tuple of the type
36 (icon_file,index), where index is the index of the icon you want
37 in the file. For single .ico files, index=0, but for icon libraries
38 contained in a single file it can be >0.
39 """
40
41 shortcut = pythoncom.CoCreateInstance(
42 shell.CLSID_ShellLink, None,
43 pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink
44 )
45 shortcut.SetPath(target)
46 shortcut.SetArguments(args)
47 shortcut.SetWorkingDirectory(start_in)
48 shortcut.SetDescription(comment)
49 if icon:
50 shortcut.SetIconLocation(*icon)
51 shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(fname,0)
52
53
54 def run(wait=0):
55 # Find where the Start Menu and My Documents are on the filesystem
56 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
57 r'Software\Microsoft\Windows\CurrentVersion'
58 r'\Explorer\Shell Folders')
59
60 programs_dir = wreg.QueryValueEx(key,'Programs')[0]
61 my_documents_dir = wreg.QueryValueEx(key,'Personal')[0]
62 key.Close()
63
64 # Find where the 'program files' directory is
65 key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE,
66 r'SOFTWARE\Microsoft\Windows\CurrentVersion')
67
68 program_files_dir = wreg.QueryValueEx(key,'ProgramFilesDir')[0]
69 key.Close()
70
71
72 # File and directory names
73 ip_dir = program_files_dir + '\\IPython'
74 ip_prog_dir = programs_dir + '\\IPython'
75 doc_dir = ip_dir+'\\doc'
76 ip_filename = ip_dir+'\\IPython_shell.py'
77 pycon_icon = doc_dir+'\\pycon.ico'
78
79 if not os.path.isdir(ip_dir):
80 os.mkdir(ip_dir)
81
82 # Copy startup script and documentation
83 shutil.copy(sys.prefix+'\\Scripts\\ipython',ip_filename)
84 if os.path.isdir(doc_dir):
85 shutil.rmtree(doc_dir)
86 shutil.copytree('doc',doc_dir)
87
88 # make shortcuts for IPython, html and pdf docs.
89 print 'Making entries for IPython in Start Menu...',
90
91 # Create shortcuts in Programs\IPython:
92 if not os.path.isdir(ip_prog_dir):
93 os.mkdir(ip_prog_dir)
94 os.chdir(ip_prog_dir)
95
96 man_pdf = doc_dir + '\\manual.pdf'
97 man_htm = doc_dir + '\\manual\\manual.html'
98
99 make_shortcut('IPython.lnk',sys.executable, '"%s"' % ip_filename,
100 my_documents_dir,
101 'IPython - Enhanced python command line interpreter',
102 (pycon_icon,0))
103 make_shortcut('pysh.lnk',sys.executable, '"%s" -p pysh' % ip_filename,
104 my_documents_dir,
105 'pysh - a system shell with Python syntax (IPython based)',
106 (pycon_icon,0))
107 make_shortcut('Manual in HTML format.lnk',man_htm,'','',
108 'IPython Manual - HTML format')
109 make_shortcut('Manual in PDF format.lnk',man_pdf,'','',
110 'IPython Manual - PDF format')
111
112 print """Done.
113
114 I created the directory %s. There you will find the
115 IPython startup script and manuals.
116
117 An IPython menu was also created in your Start Menu, with entries for
118 IPython itself and the manual in HTML and PDF formats.
119
120 For reading PDF documents you need the freely available Adobe Acrobat
121 Reader. If you don't have it, you can download it from:
122 http://www.adobe.com/products/acrobat/readstep2.html
123 """ % ip_dir
124
125 if wait:
126 print "Finished with IPython installation. Press Enter to exit this installer.",
127 raw_input()
128
129 if __name__ == '__main__':
130 run()
General Comments 0
You need to be logged in to leave comments. Login now