##// END OF EJS Templates
Rename Struct to ipstruct, to fix a bug under windows due to shadowing of...
fperez -
Show More
@@ -1,164 +1,164 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for coloring text in ANSI terminals.
2 """Tools for coloring text in ANSI terminals.
3
3
4 $Id: ColorANSI.py 994 2006-01-08 08:29:44Z fperez $"""
4 $Id: ColorANSI.py 1005 2006-01-12 08:39:26Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 from IPython import Release
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
15 __license__ = Release.license
16
16
17 __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
17 __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
18
18
19 import os
19 import os
20
20
21 from IPython.Struct import Struct
21 from IPython.ipstruct import Struct
22
22
23 def make_color_table(in_class):
23 def make_color_table(in_class):
24 """Build a set of color attributes in a class.
24 """Build a set of color attributes in a class.
25
25
26 Helper function for building the *TermColors classes."""
26 Helper function for building the *TermColors classes."""
27
27
28 color_templates = (
28 color_templates = (
29 ("Black" , "0;30"),
29 ("Black" , "0;30"),
30 ("Red" , "0;31"),
30 ("Red" , "0;31"),
31 ("Green" , "0;32"),
31 ("Green" , "0;32"),
32 ("Brown" , "0;33"),
32 ("Brown" , "0;33"),
33 ("Blue" , "0;34"),
33 ("Blue" , "0;34"),
34 ("Purple" , "0;35"),
34 ("Purple" , "0;35"),
35 ("Cyan" , "0;36"),
35 ("Cyan" , "0;36"),
36 ("LightGray" , "0;37"),
36 ("LightGray" , "0;37"),
37 ("DarkGray" , "1;30"),
37 ("DarkGray" , "1;30"),
38 ("LightRed" , "1;31"),
38 ("LightRed" , "1;31"),
39 ("LightGreen" , "1;32"),
39 ("LightGreen" , "1;32"),
40 ("Yellow" , "1;33"),
40 ("Yellow" , "1;33"),
41 ("LightBlue" , "1;34"),
41 ("LightBlue" , "1;34"),
42 ("LightPurple" , "1;35"),
42 ("LightPurple" , "1;35"),
43 ("LightCyan" , "1;36"),
43 ("LightCyan" , "1;36"),
44 ("White" , "1;37"), )
44 ("White" , "1;37"), )
45
45
46 for name,value in color_templates:
46 for name,value in color_templates:
47 setattr(in_class,name,in_class._base % value)
47 setattr(in_class,name,in_class._base % value)
48
48
49 class TermColors:
49 class TermColors:
50 """Color escape sequences.
50 """Color escape sequences.
51
51
52 This class defines the escape sequences for all the standard (ANSI?)
52 This class defines the escape sequences for all the standard (ANSI?)
53 colors in terminals. Also defines a NoColor escape which is just the null
53 colors in terminals. Also defines a NoColor escape which is just the null
54 string, suitable for defining 'dummy' color schemes in terminals which get
54 string, suitable for defining 'dummy' color schemes in terminals which get
55 confused by color escapes.
55 confused by color escapes.
56
56
57 This class should be used as a mixin for building color schemes."""
57 This class should be used as a mixin for building color schemes."""
58
58
59 NoColor = '' # for color schemes in color-less terminals.
59 NoColor = '' # for color schemes in color-less terminals.
60 Normal = '\033[0m' # Reset normal coloring
60 Normal = '\033[0m' # Reset normal coloring
61 _base = '\033[%sm' # Template for all other colors
61 _base = '\033[%sm' # Template for all other colors
62
62
63 # Build the actual color table as a set of class attributes:
63 # Build the actual color table as a set of class attributes:
64 make_color_table(TermColors)
64 make_color_table(TermColors)
65
65
66 class InputTermColors:
66 class InputTermColors:
67 """Color escape sequences for input prompts.
67 """Color escape sequences for input prompts.
68
68
69 This class is similar to TermColors, but the escapes are wrapped in \001
69 This class is similar to TermColors, but the escapes are wrapped in \001
70 and \002 so that readline can properly know the length of each line and
70 and \002 so that readline can properly know the length of each line and
71 can wrap lines accordingly. Use this class for any colored text which
71 can wrap lines accordingly. Use this class for any colored text which
72 needs to be used in input prompts, such as in calls to raw_input().
72 needs to be used in input prompts, such as in calls to raw_input().
73
73
74 This class defines the escape sequences for all the standard (ANSI?)
74 This class defines the escape sequences for all the standard (ANSI?)
75 colors in terminals. Also defines a NoColor escape which is just the null
75 colors in terminals. Also defines a NoColor escape which is just the null
76 string, suitable for defining 'dummy' color schemes in terminals which get
76 string, suitable for defining 'dummy' color schemes in terminals which get
77 confused by color escapes.
77 confused by color escapes.
78
78
79 This class should be used as a mixin for building color schemes."""
79 This class should be used as a mixin for building color schemes."""
80
80
81 NoColor = '' # for color schemes in color-less terminals.
81 NoColor = '' # for color schemes in color-less terminals.
82 Normal = '\001\033[0m\002' # Reset normal coloring
82 Normal = '\001\033[0m\002' # Reset normal coloring
83 _base = '\001\033[%sm\002' # Template for all other colors
83 _base = '\001\033[%sm\002' # Template for all other colors
84
84
85 # Build the actual color table as a set of class attributes:
85 # Build the actual color table as a set of class attributes:
86 make_color_table(InputTermColors)
86 make_color_table(InputTermColors)
87
87
88 class ColorScheme:
88 class ColorScheme:
89 """Generic color scheme class. Just a name and a Struct."""
89 """Generic color scheme class. Just a name and a Struct."""
90 def __init__(self,__scheme_name_,colordict=None,**colormap):
90 def __init__(self,__scheme_name_,colordict=None,**colormap):
91 self.name = __scheme_name_
91 self.name = __scheme_name_
92 if colordict is None:
92 if colordict is None:
93 self.colors = Struct(**colormap)
93 self.colors = Struct(**colormap)
94 else:
94 else:
95 self.colors = Struct(colordict)
95 self.colors = Struct(colordict)
96
96
97 def copy(self,name=None):
97 def copy(self,name=None):
98 """Return a full copy of the object, optionally renaming it."""
98 """Return a full copy of the object, optionally renaming it."""
99 if name is None:
99 if name is None:
100 name = self.name
100 name = self.name
101 return ColorScheme(name,self.colors.__dict__)
101 return ColorScheme(name,self.colors.__dict__)
102
102
103 class ColorSchemeTable(dict):
103 class ColorSchemeTable(dict):
104 """General class to handle tables of color schemes.
104 """General class to handle tables of color schemes.
105
105
106 It's basically a dict of color schemes with a couple of shorthand
106 It's basically a dict of color schemes with a couple of shorthand
107 attributes and some convenient methods.
107 attributes and some convenient methods.
108
108
109 active_scheme_name -> obvious
109 active_scheme_name -> obvious
110 active_colors -> actual color table of the active scheme"""
110 active_colors -> actual color table of the active scheme"""
111
111
112 def __init__(self,scheme_list=None,default_scheme=''):
112 def __init__(self,scheme_list=None,default_scheme=''):
113 """Create a table of color schemes.
113 """Create a table of color schemes.
114
114
115 The table can be created empty and manually filled or it can be
115 The table can be created empty and manually filled or it can be
116 created with a list of valid color schemes AND the specification for
116 created with a list of valid color schemes AND the specification for
117 the default active scheme.
117 the default active scheme.
118 """
118 """
119
119
120 # create object attributes to be set later
120 # create object attributes to be set later
121 self.active_scheme_name = ''
121 self.active_scheme_name = ''
122 self.active_colors = None
122 self.active_colors = None
123
123
124 if scheme_list:
124 if scheme_list:
125 if default_scheme == '':
125 if default_scheme == '':
126 raise ValueError,'you must specify the default color scheme'
126 raise ValueError,'you must specify the default color scheme'
127 for scheme in scheme_list:
127 for scheme in scheme_list:
128 self.add_scheme(scheme)
128 self.add_scheme(scheme)
129 self.set_active_scheme(default_scheme)
129 self.set_active_scheme(default_scheme)
130
130
131 def copy(self):
131 def copy(self):
132 """Return full copy of object"""
132 """Return full copy of object"""
133 return ColorSchemeTable(self.values(),self.active_scheme_name)
133 return ColorSchemeTable(self.values(),self.active_scheme_name)
134
134
135 def add_scheme(self,new_scheme):
135 def add_scheme(self,new_scheme):
136 """Add a new color scheme to the table."""
136 """Add a new color scheme to the table."""
137 if not isinstance(new_scheme,ColorScheme):
137 if not isinstance(new_scheme,ColorScheme):
138 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
138 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
139 self[new_scheme.name] = new_scheme
139 self[new_scheme.name] = new_scheme
140
140
141 def set_active_scheme(self,scheme,case_sensitive=0):
141 def set_active_scheme(self,scheme,case_sensitive=0):
142 """Set the currently active scheme.
142 """Set the currently active scheme.
143
143
144 Names are by default compared in a case-insensitive way, but this can
144 Names are by default compared in a case-insensitive way, but this can
145 be changed by setting the parameter case_sensitive to true."""
145 be changed by setting the parameter case_sensitive to true."""
146
146
147 scheme_names = self.keys()
147 scheme_names = self.keys()
148 if case_sensitive:
148 if case_sensitive:
149 valid_schemes = scheme_names
149 valid_schemes = scheme_names
150 scheme_test = scheme
150 scheme_test = scheme
151 else:
151 else:
152 valid_schemes = [s.lower() for s in scheme_names]
152 valid_schemes = [s.lower() for s in scheme_names]
153 scheme_test = scheme.lower()
153 scheme_test = scheme.lower()
154 try:
154 try:
155 scheme_idx = valid_schemes.index(scheme_test)
155 scheme_idx = valid_schemes.index(scheme_test)
156 except ValueError:
156 except ValueError:
157 raise ValueError,'Unrecognized color scheme: ' + scheme + \
157 raise ValueError,'Unrecognized color scheme: ' + scheme + \
158 '\nValid schemes: '+str(scheme_names).replace("'', ",'')
158 '\nValid schemes: '+str(scheme_names).replace("'', ",'')
159 else:
159 else:
160 active = scheme_names[scheme_idx]
160 active = scheme_names[scheme_idx]
161 self.active_scheme_name = active
161 self.active_scheme_name = active
162 self.active_colors = self[active].colors
162 self.active_colors = self[active].colors
163 # Now allow using '' as an index for the current active scheme
163 # Now allow using '' as an index for the current active scheme
164 self[''] = self[active]
164 self[''] = self[active]
@@ -1,116 +1,116 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Configuration loader
2 """Configuration loader
3
3
4 $Id: ConfigLoader.py 994 2006-01-08 08:29:44Z fperez $"""
4 $Id: ConfigLoader.py 1005 2006-01-12 08:39:26Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 from IPython import Release
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
15 __license__ = Release.license
16
16
17 import exceptions
17 import exceptions
18 import os
18 import os
19 from pprint import pprint
19 from pprint import pprint
20
20
21 from IPython import ultraTB
21 from IPython import ultraTB
22 from IPython.Struct import Struct
22 from IPython.ipstruct import Struct
23 from IPython.genutils import *
23 from IPython.genutils import *
24
24
25 class ConfigLoaderError(exceptions.Exception):
25 class ConfigLoaderError(exceptions.Exception):
26 """Exception for ConfigLoader class."""
26 """Exception for ConfigLoader class."""
27
27
28 def __init__(self,args=None):
28 def __init__(self,args=None):
29 self.args = args
29 self.args = args
30
30
31 class ConfigLoader:
31 class ConfigLoader:
32
32
33 """Configuration file loader capable of handling recursive inclusions and
33 """Configuration file loader capable of handling recursive inclusions and
34 with parametrized conflict resolution for multiply found keys."""
34 with parametrized conflict resolution for multiply found keys."""
35
35
36 def __init__(self,conflict=None,field_sep=None,reclimit=15):
36 def __init__(self,conflict=None,field_sep=None,reclimit=15):
37
37
38 """The reclimit parameter controls the number of recursive
38 """The reclimit parameter controls the number of recursive
39 configuration file inclusions. This way we can stop early on (before
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
40 python's own recursion limit is hit) if there is a circular
41 inclusion.
41 inclusion.
42
42
43 - conflict: dictionary for conflict resolutions (see Struct.merge())
43 - conflict: dictionary for conflict resolutions (see Struct.merge())
44
44
45 """
45 """
46 self.conflict = conflict
46 self.conflict = conflict
47 self.field_sep = field_sep
47 self.field_sep = field_sep
48 self.reset(reclimit)
48 self.reset(reclimit)
49
49
50 def reset(self,reclimit=15):
50 def reset(self,reclimit=15):
51 self.reclimit = reclimit
51 self.reclimit = reclimit
52 self.recdepth = 0
52 self.recdepth = 0
53 self.included = []
53 self.included = []
54
54
55 def load(self,fname,convert=None,recurse_key='',incpath = '.',**kw):
55 def load(self,fname,convert=None,recurse_key='',incpath = '.',**kw):
56 """Load a configuration file, return the resulting Struct.
56 """Load a configuration file, return the resulting Struct.
57
57
58 Call: load_config(fname,convert=None,conflict=None,recurse_key='')
58 Call: load_config(fname,convert=None,conflict=None,recurse_key='')
59
59
60 - fname: file to load from.
60 - fname: file to load from.
61 - convert: dictionary of type conversions (see read_dict())
61 - convert: dictionary of type conversions (see read_dict())
62 - recurse_key: keyword in dictionary to trigger recursive file
62 - recurse_key: keyword in dictionary to trigger recursive file
63 inclusions.
63 inclusions.
64 """
64 """
65
65
66 if self.recdepth > self.reclimit:
66 if self.recdepth > self.reclimit:
67 raise ConfigLoaderError, 'maximum recursive inclusion of rcfiles '+\
67 raise ConfigLoaderError, 'maximum recursive inclusion of rcfiles '+\
68 'exceeded: ' + `self.recdepth` + \
68 'exceeded: ' + `self.recdepth` + \
69 '.\nMaybe you have a circular chain of inclusions?'
69 '.\nMaybe you have a circular chain of inclusions?'
70 self.recdepth += 1
70 self.recdepth += 1
71 fname = filefind(fname,incpath)
71 fname = filefind(fname,incpath)
72 data = Struct()
72 data = Struct()
73 # avoid including the same file more than once
73 # avoid including the same file more than once
74 if fname in self.included:
74 if fname in self.included:
75 return data
75 return data
76 Xinfo = ultraTB.AutoFormattedTB()
76 Xinfo = ultraTB.AutoFormattedTB()
77 if convert==None and recurse_key : convert = {qwflat:recurse_key}
77 if convert==None and recurse_key : convert = {qwflat:recurse_key}
78 # for production, change warn to 0:
78 # for production, change warn to 0:
79 data.merge(read_dict(fname,convert,fs=self.field_sep,strip=1,
79 data.merge(read_dict(fname,convert,fs=self.field_sep,strip=1,
80 warn=0,no_empty=0,**kw))
80 warn=0,no_empty=0,**kw))
81 # keep track of successfully loaded files
81 # keep track of successfully loaded files
82 self.included.append(fname)
82 self.included.append(fname)
83 if recurse_key in data.keys():
83 if recurse_key in data.keys():
84 for incfilename in data[recurse_key]:
84 for incfilename in data[recurse_key]:
85 found=0
85 found=0
86 try:
86 try:
87 incfile = filefind(incfilename,incpath)
87 incfile = filefind(incfilename,incpath)
88 except IOError:
88 except IOError:
89 if os.name in ['nt','dos']:
89 if os.name in ['nt','dos']:
90 try:
90 try:
91 # Try again with '.ini' extension
91 # Try again with '.ini' extension
92 incfilename += '.ini'
92 incfilename += '.ini'
93 incfile = filefind(incfilename,incpath)
93 incfile = filefind(incfilename,incpath)
94 except IOError:
94 except IOError:
95 found = 0
95 found = 0
96 else:
96 else:
97 found = 1
97 found = 1
98 else:
98 else:
99 found = 0
99 found = 0
100 else:
100 else:
101 found = 1
101 found = 1
102 if found:
102 if found:
103 try:
103 try:
104 data.merge(self.load(incfile,convert,recurse_key,
104 data.merge(self.load(incfile,convert,recurse_key,
105 incpath,**kw),
105 incpath,**kw),
106 self.conflict)
106 self.conflict)
107 except:
107 except:
108 Xinfo()
108 Xinfo()
109 warn('Problem loading included file: '+
109 warn('Problem loading included file: '+
110 `incfilename` + '. Ignoring it...')
110 `incfilename` + '. Ignoring it...')
111 else:
111 else:
112 warn('File `%s` not found. Included by %s' % (incfilename,fname))
112 warn('File `%s` not found. Included by %s' % (incfilename,fname))
113
113
114 return data
114 return data
115
115
116 # end ConfigLoader
116 # end ConfigLoader
@@ -1,2741 +1,2741 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 1003 2006-01-11 22:18:56Z vivainio $"""
4 $Id: Magic.py 1005 2006-01-12 08:39:26Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 from cStringIO import StringIO
34 from cStringIO import StringIO
35 from getopt import getopt
35 from getopt import getopt
36 from pprint import pprint, pformat
36 from pprint import pprint, pformat
37
37
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # Homebrewed
44 # Homebrewed
45 from IPython import Debugger, OInspect, wildcard
45 from IPython import Debugger, OInspect, wildcard
46 from IPython.FakeModule import FakeModule
46 from IPython.FakeModule import FakeModule
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.PyColorize import Parser
48 from IPython.PyColorize import Parser
49 from IPython.Struct import Struct
49 from IPython.ipstruct import Struct
50 from IPython.macro import Macro
50 from IPython.macro import Macro
51 from IPython.genutils import *
51 from IPython.genutils import *
52
52
53 #***************************************************************************
53 #***************************************************************************
54 # Utility functions
54 # Utility functions
55 def on_off(tag):
55 def on_off(tag):
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
57 return ['OFF','ON'][tag]
57 return ['OFF','ON'][tag]
58
58
59 class Bunch: pass
59 class Bunch: pass
60
60
61 #***************************************************************************
61 #***************************************************************************
62 # Main class implementing Magic functionality
62 # Main class implementing Magic functionality
63 class Magic:
63 class Magic:
64 """Magic functions for InteractiveShell.
64 """Magic functions for InteractiveShell.
65
65
66 Shell functions which can be reached as %function_name. All magic
66 Shell functions which can be reached as %function_name. All magic
67 functions should accept a string, which they can parse for their own
67 functions should accept a string, which they can parse for their own
68 needs. This can make some functions easier to type, eg `%cd ../`
68 needs. This can make some functions easier to type, eg `%cd ../`
69 vs. `%cd("../")`
69 vs. `%cd("../")`
70
70
71 ALL definitions MUST begin with the prefix magic_. The user won't need it
71 ALL definitions MUST begin with the prefix magic_. The user won't need it
72 at the command line, but it is is needed in the definition. """
72 at the command line, but it is is needed in the definition. """
73
73
74 # class globals
74 # class globals
75 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
75 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
76 'Automagic is ON, % prefix NOT needed for magic functions.']
76 'Automagic is ON, % prefix NOT needed for magic functions.']
77
77
78 #......................................................................
78 #......................................................................
79 # some utility functions
79 # some utility functions
80
80
81 def __init__(self,shell):
81 def __init__(self,shell):
82
82
83 self.options_table = {}
83 self.options_table = {}
84 if profile is None:
84 if profile is None:
85 self.magic_prun = self.profile_missing_notice
85 self.magic_prun = self.profile_missing_notice
86 self.shell = shell
86 self.shell = shell
87
87
88 # namespace for holding state we may need
88 # namespace for holding state we may need
89 self._magic_state = Bunch()
89 self._magic_state = Bunch()
90
90
91 def profile_missing_notice(self, *args, **kwargs):
91 def profile_missing_notice(self, *args, **kwargs):
92 error("""\
92 error("""\
93 The profile module could not be found. If you are a Debian user,
93 The profile module could not be found. If you are a Debian user,
94 it has been removed from the standard Debian package because of its non-free
94 it has been removed from the standard Debian package because of its non-free
95 license. To use profiling, please install"python2.3-profiler" from non-free.""")
95 license. To use profiling, please install"python2.3-profiler" from non-free.""")
96
96
97 def default_option(self,fn,optstr):
97 def default_option(self,fn,optstr):
98 """Make an entry in the options_table for fn, with value optstr"""
98 """Make an entry in the options_table for fn, with value optstr"""
99
99
100 if fn not in self.lsmagic():
100 if fn not in self.lsmagic():
101 error("%s is not a magic function" % fn)
101 error("%s is not a magic function" % fn)
102 self.options_table[fn] = optstr
102 self.options_table[fn] = optstr
103
103
104 def lsmagic(self):
104 def lsmagic(self):
105 """Return a list of currently available magic functions.
105 """Return a list of currently available magic functions.
106
106
107 Gives a list of the bare names after mangling (['ls','cd', ...], not
107 Gives a list of the bare names after mangling (['ls','cd', ...], not
108 ['magic_ls','magic_cd',...]"""
108 ['magic_ls','magic_cd',...]"""
109
109
110 # FIXME. This needs a cleanup, in the way the magics list is built.
110 # FIXME. This needs a cleanup, in the way the magics list is built.
111
111
112 # magics in class definition
112 # magics in class definition
113 class_magic = lambda fn: fn.startswith('magic_') and \
113 class_magic = lambda fn: fn.startswith('magic_') and \
114 callable(Magic.__dict__[fn])
114 callable(Magic.__dict__[fn])
115 # in instance namespace (run-time user additions)
115 # in instance namespace (run-time user additions)
116 inst_magic = lambda fn: fn.startswith('magic_') and \
116 inst_magic = lambda fn: fn.startswith('magic_') and \
117 callable(self.__dict__[fn])
117 callable(self.__dict__[fn])
118 # and bound magics by user (so they can access self):
118 # and bound magics by user (so they can access self):
119 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
119 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
120 callable(self.__class__.__dict__[fn])
120 callable(self.__class__.__dict__[fn])
121 magics = filter(class_magic,Magic.__dict__.keys()) + \
121 magics = filter(class_magic,Magic.__dict__.keys()) + \
122 filter(inst_magic,self.__dict__.keys()) + \
122 filter(inst_magic,self.__dict__.keys()) + \
123 filter(inst_bound_magic,self.__class__.__dict__.keys())
123 filter(inst_bound_magic,self.__class__.__dict__.keys())
124 out = []
124 out = []
125 for fn in magics:
125 for fn in magics:
126 out.append(fn.replace('magic_','',1))
126 out.append(fn.replace('magic_','',1))
127 out.sort()
127 out.sort()
128 return out
128 return out
129
129
130 def extract_input_slices(self,slices):
130 def extract_input_slices(self,slices):
131 """Return as a string a set of input history slices.
131 """Return as a string a set of input history slices.
132
132
133 The set of slices is given as a list of strings (like ['1','4:8','9'],
133 The set of slices is given as a list of strings (like ['1','4:8','9'],
134 since this function is for use by magic functions which get their
134 since this function is for use by magic functions which get their
135 arguments as strings.
135 arguments as strings.
136
136
137 Note that slices can be called with two notations:
137 Note that slices can be called with two notations:
138
138
139 N:M -> standard python form, means including items N...(M-1).
139 N:M -> standard python form, means including items N...(M-1).
140
140
141 N-M -> include items N..M (closed endpoint)."""
141 N-M -> include items N..M (closed endpoint)."""
142
142
143 cmds = []
143 cmds = []
144 for chunk in slices:
144 for chunk in slices:
145 if ':' in chunk:
145 if ':' in chunk:
146 ini,fin = map(int,chunk.split(':'))
146 ini,fin = map(int,chunk.split(':'))
147 elif '-' in chunk:
147 elif '-' in chunk:
148 ini,fin = map(int,chunk.split('-'))
148 ini,fin = map(int,chunk.split('-'))
149 fin += 1
149 fin += 1
150 else:
150 else:
151 ini = int(chunk)
151 ini = int(chunk)
152 fin = ini+1
152 fin = ini+1
153 cmds.append(self.shell.input_hist[ini:fin])
153 cmds.append(self.shell.input_hist[ini:fin])
154 return cmds
154 return cmds
155
155
156 def _ofind(self,oname):
156 def _ofind(self,oname):
157 """Find an object in the available namespaces.
157 """Find an object in the available namespaces.
158
158
159 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
159 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
160
160
161 Has special code to detect magic functions.
161 Has special code to detect magic functions.
162 """
162 """
163
163
164 oname = oname.strip()
164 oname = oname.strip()
165
165
166 # Namespaces to search in:
166 # Namespaces to search in:
167 user_ns = self.shell.user_ns
167 user_ns = self.shell.user_ns
168 internal_ns = self.shell.internal_ns
168 internal_ns = self.shell.internal_ns
169 builtin_ns = __builtin__.__dict__
169 builtin_ns = __builtin__.__dict__
170 alias_ns = self.shell.alias_table
170 alias_ns = self.shell.alias_table
171
171
172 # Put them in a list. The order is important so that we find things in
172 # Put them in a list. The order is important so that we find things in
173 # the same order that Python finds them.
173 # the same order that Python finds them.
174 namespaces = [ ('Interactive',user_ns),
174 namespaces = [ ('Interactive',user_ns),
175 ('IPython internal',internal_ns),
175 ('IPython internal',internal_ns),
176 ('Python builtin',builtin_ns),
176 ('Python builtin',builtin_ns),
177 ('Alias',alias_ns),
177 ('Alias',alias_ns),
178 ]
178 ]
179
179
180 # initialize results to 'null'
180 # initialize results to 'null'
181 found = 0; obj = None; ospace = None; ds = None;
181 found = 0; obj = None; ospace = None; ds = None;
182 ismagic = 0; isalias = 0
182 ismagic = 0; isalias = 0
183
183
184 # Look for the given name by splitting it in parts. If the head is
184 # Look for the given name by splitting it in parts. If the head is
185 # found, then we look for all the remaining parts as members, and only
185 # found, then we look for all the remaining parts as members, and only
186 # declare success if we can find them all.
186 # declare success if we can find them all.
187 oname_parts = oname.split('.')
187 oname_parts = oname.split('.')
188 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
188 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
189 for nsname,ns in namespaces:
189 for nsname,ns in namespaces:
190 try:
190 try:
191 obj = ns[oname_head]
191 obj = ns[oname_head]
192 except KeyError:
192 except KeyError:
193 continue
193 continue
194 else:
194 else:
195 for part in oname_rest:
195 for part in oname_rest:
196 try:
196 try:
197 obj = getattr(obj,part)
197 obj = getattr(obj,part)
198 except:
198 except:
199 # Blanket except b/c some badly implemented objects
199 # Blanket except b/c some badly implemented objects
200 # allow __getattr__ to raise exceptions other than
200 # allow __getattr__ to raise exceptions other than
201 # AttributeError, which then crashes IPython.
201 # AttributeError, which then crashes IPython.
202 break
202 break
203 else:
203 else:
204 # If we finish the for loop (no break), we got all members
204 # If we finish the for loop (no break), we got all members
205 found = 1
205 found = 1
206 ospace = nsname
206 ospace = nsname
207 if ns == alias_ns:
207 if ns == alias_ns:
208 isalias = 1
208 isalias = 1
209 break # namespace loop
209 break # namespace loop
210
210
211 # Try to see if it's magic
211 # Try to see if it's magic
212 if not found:
212 if not found:
213 if oname.startswith(self.shell.ESC_MAGIC):
213 if oname.startswith(self.shell.ESC_MAGIC):
214 oname = oname[1:]
214 oname = oname[1:]
215 obj = getattr(self,'magic_'+oname,None)
215 obj = getattr(self,'magic_'+oname,None)
216 if obj is not None:
216 if obj is not None:
217 found = 1
217 found = 1
218 ospace = 'IPython internal'
218 ospace = 'IPython internal'
219 ismagic = 1
219 ismagic = 1
220
220
221 # Last try: special-case some literals like '', [], {}, etc:
221 # Last try: special-case some literals like '', [], {}, etc:
222 if not found and oname_head in ["''",'""','[]','{}','()']:
222 if not found and oname_head in ["''",'""','[]','{}','()']:
223 obj = eval(oname_head)
223 obj = eval(oname_head)
224 found = 1
224 found = 1
225 ospace = 'Interactive'
225 ospace = 'Interactive'
226
226
227 return {'found':found, 'obj':obj, 'namespace':ospace,
227 return {'found':found, 'obj':obj, 'namespace':ospace,
228 'ismagic':ismagic, 'isalias':isalias}
228 'ismagic':ismagic, 'isalias':isalias}
229
229
230 def arg_err(self,func):
230 def arg_err(self,func):
231 """Print docstring if incorrect arguments were passed"""
231 """Print docstring if incorrect arguments were passed"""
232 print 'Error in arguments:'
232 print 'Error in arguments:'
233 print OInspect.getdoc(func)
233 print OInspect.getdoc(func)
234
234
235 def format_latex(self,strng):
235 def format_latex(self,strng):
236 """Format a string for latex inclusion."""
236 """Format a string for latex inclusion."""
237
237
238 # Characters that need to be escaped for latex:
238 # Characters that need to be escaped for latex:
239 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
239 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
240 # Magic command names as headers:
240 # Magic command names as headers:
241 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
241 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
242 re.MULTILINE)
242 re.MULTILINE)
243 # Magic commands
243 # Magic commands
244 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
244 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
245 re.MULTILINE)
245 re.MULTILINE)
246 # Paragraph continue
246 # Paragraph continue
247 par_re = re.compile(r'\\$',re.MULTILINE)
247 par_re = re.compile(r'\\$',re.MULTILINE)
248
248
249 # The "\n" symbol
249 # The "\n" symbol
250 newline_re = re.compile(r'\\n')
250 newline_re = re.compile(r'\\n')
251
251
252 # Now build the string for output:
252 # Now build the string for output:
253 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
253 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
254 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
254 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
255 strng)
255 strng)
256 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
256 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
257 strng = par_re.sub(r'\\\\',strng)
257 strng = par_re.sub(r'\\\\',strng)
258 strng = escape_re.sub(r'\\\1',strng)
258 strng = escape_re.sub(r'\\\1',strng)
259 strng = newline_re.sub(r'\\textbackslash{}n',strng)
259 strng = newline_re.sub(r'\\textbackslash{}n',strng)
260 return strng
260 return strng
261
261
262 def format_screen(self,strng):
262 def format_screen(self,strng):
263 """Format a string for screen printing.
263 """Format a string for screen printing.
264
264
265 This removes some latex-type format codes."""
265 This removes some latex-type format codes."""
266 # Paragraph continue
266 # Paragraph continue
267 par_re = re.compile(r'\\$',re.MULTILINE)
267 par_re = re.compile(r'\\$',re.MULTILINE)
268 strng = par_re.sub('',strng)
268 strng = par_re.sub('',strng)
269 return strng
269 return strng
270
270
271 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
271 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
272 """Parse options passed to an argument string.
272 """Parse options passed to an argument string.
273
273
274 The interface is similar to that of getopt(), but it returns back a
274 The interface is similar to that of getopt(), but it returns back a
275 Struct with the options as keys and the stripped argument string still
275 Struct with the options as keys and the stripped argument string still
276 as a string.
276 as a string.
277
277
278 arg_str is quoted as a true sys.argv vector by using shlex.split.
278 arg_str is quoted as a true sys.argv vector by using shlex.split.
279 This allows us to easily expand variables, glob files, quote
279 This allows us to easily expand variables, glob files, quote
280 arguments, etc.
280 arguments, etc.
281
281
282 Options:
282 Options:
283 -mode: default 'string'. If given as 'list', the argument string is
283 -mode: default 'string'. If given as 'list', the argument string is
284 returned as a list (split on whitespace) instead of a string.
284 returned as a list (split on whitespace) instead of a string.
285
285
286 -list_all: put all option values in lists. Normally only options
286 -list_all: put all option values in lists. Normally only options
287 appearing more than once are put in a list."""
287 appearing more than once are put in a list."""
288
288
289 # inject default options at the beginning of the input line
289 # inject default options at the beginning of the input line
290 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
290 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
291 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
291 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
292
292
293 mode = kw.get('mode','string')
293 mode = kw.get('mode','string')
294 if mode not in ['string','list']:
294 if mode not in ['string','list']:
295 raise ValueError,'incorrect mode given: %s' % mode
295 raise ValueError,'incorrect mode given: %s' % mode
296 # Get options
296 # Get options
297 list_all = kw.get('list_all',0)
297 list_all = kw.get('list_all',0)
298
298
299 # Check if we have more than one argument to warrant extra processing:
299 # Check if we have more than one argument to warrant extra processing:
300 odict = {} # Dictionary with options
300 odict = {} # Dictionary with options
301 args = arg_str.split()
301 args = arg_str.split()
302 if len(args) >= 1:
302 if len(args) >= 1:
303 # If the list of inputs only has 0 or 1 thing in it, there's no
303 # If the list of inputs only has 0 or 1 thing in it, there's no
304 # need to look for options
304 # need to look for options
305 argv = shlex_split(arg_str)
305 argv = shlex_split(arg_str)
306 # Do regular option processing
306 # Do regular option processing
307 opts,args = getopt(argv,opt_str,*long_opts)
307 opts,args = getopt(argv,opt_str,*long_opts)
308 for o,a in opts:
308 for o,a in opts:
309 if o.startswith('--'):
309 if o.startswith('--'):
310 o = o[2:]
310 o = o[2:]
311 else:
311 else:
312 o = o[1:]
312 o = o[1:]
313 try:
313 try:
314 odict[o].append(a)
314 odict[o].append(a)
315 except AttributeError:
315 except AttributeError:
316 odict[o] = [odict[o],a]
316 odict[o] = [odict[o],a]
317 except KeyError:
317 except KeyError:
318 if list_all:
318 if list_all:
319 odict[o] = [a]
319 odict[o] = [a]
320 else:
320 else:
321 odict[o] = a
321 odict[o] = a
322
322
323 # Prepare opts,args for return
323 # Prepare opts,args for return
324 opts = Struct(odict)
324 opts = Struct(odict)
325 if mode == 'string':
325 if mode == 'string':
326 args = ' '.join(args)
326 args = ' '.join(args)
327
327
328 return opts,args
328 return opts,args
329
329
330 #......................................................................
330 #......................................................................
331 # And now the actual magic functions
331 # And now the actual magic functions
332
332
333 # Functions for IPython shell work (vars,funcs, config, etc)
333 # Functions for IPython shell work (vars,funcs, config, etc)
334 def magic_lsmagic(self, parameter_s = ''):
334 def magic_lsmagic(self, parameter_s = ''):
335 """List currently available magic functions."""
335 """List currently available magic functions."""
336 mesc = self.shell.ESC_MAGIC
336 mesc = self.shell.ESC_MAGIC
337 print 'Available magic functions:\n'+mesc+\
337 print 'Available magic functions:\n'+mesc+\
338 (' '+mesc).join(self.lsmagic())
338 (' '+mesc).join(self.lsmagic())
339 print '\n' + Magic.auto_status[self.shell.rc.automagic]
339 print '\n' + Magic.auto_status[self.shell.rc.automagic]
340 return None
340 return None
341
341
342 def magic_magic(self, parameter_s = ''):
342 def magic_magic(self, parameter_s = ''):
343 """Print information about the magic function system."""
343 """Print information about the magic function system."""
344
344
345 mode = ''
345 mode = ''
346 try:
346 try:
347 if parameter_s.split()[0] == '-latex':
347 if parameter_s.split()[0] == '-latex':
348 mode = 'latex'
348 mode = 'latex'
349 except:
349 except:
350 pass
350 pass
351
351
352 magic_docs = []
352 magic_docs = []
353 for fname in self.lsmagic():
353 for fname in self.lsmagic():
354 mname = 'magic_' + fname
354 mname = 'magic_' + fname
355 for space in (Magic,self,self.__class__):
355 for space in (Magic,self,self.__class__):
356 try:
356 try:
357 fn = space.__dict__[mname]
357 fn = space.__dict__[mname]
358 except KeyError:
358 except KeyError:
359 pass
359 pass
360 else:
360 else:
361 break
361 break
362 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
362 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
363 fname,fn.__doc__))
363 fname,fn.__doc__))
364 magic_docs = ''.join(magic_docs)
364 magic_docs = ''.join(magic_docs)
365
365
366 if mode == 'latex':
366 if mode == 'latex':
367 print self.format_latex(magic_docs)
367 print self.format_latex(magic_docs)
368 return
368 return
369 else:
369 else:
370 magic_docs = self.format_screen(magic_docs)
370 magic_docs = self.format_screen(magic_docs)
371
371
372 outmsg = """
372 outmsg = """
373 IPython's 'magic' functions
373 IPython's 'magic' functions
374 ===========================
374 ===========================
375
375
376 The magic function system provides a series of functions which allow you to
376 The magic function system provides a series of functions which allow you to
377 control the behavior of IPython itself, plus a lot of system-type
377 control the behavior of IPython itself, plus a lot of system-type
378 features. All these functions are prefixed with a % character, but parameters
378 features. All these functions are prefixed with a % character, but parameters
379 are given without parentheses or quotes.
379 are given without parentheses or quotes.
380
380
381 NOTE: If you have 'automagic' enabled (via the command line option or with the
381 NOTE: If you have 'automagic' enabled (via the command line option or with the
382 %automagic function), you don't need to type in the % explicitly. By default,
382 %automagic function), you don't need to type in the % explicitly. By default,
383 IPython ships with automagic on, so you should only rarely need the % escape.
383 IPython ships with automagic on, so you should only rarely need the % escape.
384
384
385 Example: typing '%cd mydir' (without the quotes) changes you working directory
385 Example: typing '%cd mydir' (without the quotes) changes you working directory
386 to 'mydir', if it exists.
386 to 'mydir', if it exists.
387
387
388 You can define your own magic functions to extend the system. See the supplied
388 You can define your own magic functions to extend the system. See the supplied
389 ipythonrc and example-magic.py files for details (in your ipython
389 ipythonrc and example-magic.py files for details (in your ipython
390 configuration directory, typically $HOME/.ipython/).
390 configuration directory, typically $HOME/.ipython/).
391
391
392 You can also define your own aliased names for magic functions. In your
392 You can also define your own aliased names for magic functions. In your
393 ipythonrc file, placing a line like:
393 ipythonrc file, placing a line like:
394
394
395 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
395 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
396
396
397 will define %pf as a new name for %profile.
397 will define %pf as a new name for %profile.
398
398
399 You can also call magics in code using the ipmagic() function, which IPython
399 You can also call magics in code using the ipmagic() function, which IPython
400 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
400 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
401
401
402 For a list of the available magic functions, use %lsmagic. For a description
402 For a list of the available magic functions, use %lsmagic. For a description
403 of any of them, type %magic_name?, e.g. '%cd?'.
403 of any of them, type %magic_name?, e.g. '%cd?'.
404
404
405 Currently the magic system has the following functions:\n"""
405 Currently the magic system has the following functions:\n"""
406
406
407 mesc = self.shell.ESC_MAGIC
407 mesc = self.shell.ESC_MAGIC
408 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
408 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
409 "\n\n%s%s\n\n%s" % (outmsg,
409 "\n\n%s%s\n\n%s" % (outmsg,
410 magic_docs,mesc,mesc,
410 magic_docs,mesc,mesc,
411 (' '+mesc).join(self.lsmagic()),
411 (' '+mesc).join(self.lsmagic()),
412 Magic.auto_status[self.shell.rc.automagic] ) )
412 Magic.auto_status[self.shell.rc.automagic] ) )
413
413
414 page(outmsg,screen_lines=self.shell.rc.screen_length)
414 page(outmsg,screen_lines=self.shell.rc.screen_length)
415
415
416 def magic_automagic(self, parameter_s = ''):
416 def magic_automagic(self, parameter_s = ''):
417 """Make magic functions callable without having to type the initial %.
417 """Make magic functions callable without having to type the initial %.
418
418
419 Toggles on/off (when off, you must call it as %automagic, of
419 Toggles on/off (when off, you must call it as %automagic, of
420 course). Note that magic functions have lowest priority, so if there's
420 course). Note that magic functions have lowest priority, so if there's
421 a variable whose name collides with that of a magic fn, automagic
421 a variable whose name collides with that of a magic fn, automagic
422 won't work for that function (you get the variable instead). However,
422 won't work for that function (you get the variable instead). However,
423 if you delete the variable (del var), the previously shadowed magic
423 if you delete the variable (del var), the previously shadowed magic
424 function becomes visible to automagic again."""
424 function becomes visible to automagic again."""
425
425
426 rc = self.shell.rc
426 rc = self.shell.rc
427 rc.automagic = not rc.automagic
427 rc.automagic = not rc.automagic
428 print '\n' + Magic.auto_status[rc.automagic]
428 print '\n' + Magic.auto_status[rc.automagic]
429
429
430 def magic_autocall(self, parameter_s = ''):
430 def magic_autocall(self, parameter_s = ''):
431 """Make functions callable without having to type parentheses.
431 """Make functions callable without having to type parentheses.
432
432
433 Usage:
433 Usage:
434
434
435 %autocall [mode]
435 %autocall [mode]
436
436
437 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
437 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
438 value is toggled on and off (remembering the previous state)."""
438 value is toggled on and off (remembering the previous state)."""
439
439
440 rc = self.shell.rc
440 rc = self.shell.rc
441
441
442 if parameter_s:
442 if parameter_s:
443 arg = int(parameter_s)
443 arg = int(parameter_s)
444 else:
444 else:
445 arg = 'toggle'
445 arg = 'toggle'
446
446
447 if not arg in (0,1,2,'toggle'):
447 if not arg in (0,1,2,'toggle'):
448 error('Valid modes: (0->Off, 1->Smart, 2->Full')
448 error('Valid modes: (0->Off, 1->Smart, 2->Full')
449 return
449 return
450
450
451 if arg in (0,1,2):
451 if arg in (0,1,2):
452 rc.autocall = arg
452 rc.autocall = arg
453 else: # toggle
453 else: # toggle
454 if rc.autocall:
454 if rc.autocall:
455 self._magic_state.autocall_save = rc.autocall
455 self._magic_state.autocall_save = rc.autocall
456 rc.autocall = 0
456 rc.autocall = 0
457 else:
457 else:
458 try:
458 try:
459 rc.autocall = self._magic_state.autocall_save
459 rc.autocall = self._magic_state.autocall_save
460 except AttributeError:
460 except AttributeError:
461 rc.autocall = self._magic_state.autocall_save = 1
461 rc.autocall = self._magic_state.autocall_save = 1
462
462
463 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
463 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
464
464
465 def magic_autoindent(self, parameter_s = ''):
465 def magic_autoindent(self, parameter_s = ''):
466 """Toggle autoindent on/off (if available)."""
466 """Toggle autoindent on/off (if available)."""
467
467
468 self.shell.set_autoindent()
468 self.shell.set_autoindent()
469 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
469 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
470
470
471 def magic_system_verbose(self, parameter_s = ''):
471 def magic_system_verbose(self, parameter_s = ''):
472 """Toggle verbose printing of system calls on/off."""
472 """Toggle verbose printing of system calls on/off."""
473
473
474 self.shell.rc_set_toggle('system_verbose')
474 self.shell.rc_set_toggle('system_verbose')
475 print "System verbose printing is:",\
475 print "System verbose printing is:",\
476 ['OFF','ON'][self.shell.rc.system_verbose]
476 ['OFF','ON'][self.shell.rc.system_verbose]
477
477
478 def magic_history(self, parameter_s = ''):
478 def magic_history(self, parameter_s = ''):
479 """Print input history (_i<n> variables), with most recent last.
479 """Print input history (_i<n> variables), with most recent last.
480
480
481 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
481 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
482 %history [-n] n -> print at most n inputs\\
482 %history [-n] n -> print at most n inputs\\
483 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
483 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
484
484
485 Each input's number <n> is shown, and is accessible as the
485 Each input's number <n> is shown, and is accessible as the
486 automatically generated variable _i<n>. Multi-line statements are
486 automatically generated variable _i<n>. Multi-line statements are
487 printed starting at a new line for easy copy/paste.
487 printed starting at a new line for easy copy/paste.
488
488
489 If option -n is used, input numbers are not printed. This is useful if
489 If option -n is used, input numbers are not printed. This is useful if
490 you want to get a printout of many lines which can be directly pasted
490 you want to get a printout of many lines which can be directly pasted
491 into a text editor.
491 into a text editor.
492
492
493 This feature is only available if numbered prompts are in use."""
493 This feature is only available if numbered prompts are in use."""
494
494
495 shell = self.shell
495 shell = self.shell
496 if not shell.outputcache.do_full_cache:
496 if not shell.outputcache.do_full_cache:
497 print 'This feature is only available if numbered prompts are in use.'
497 print 'This feature is only available if numbered prompts are in use.'
498 return
498 return
499 opts,args = self.parse_options(parameter_s,'n',mode='list')
499 opts,args = self.parse_options(parameter_s,'n',mode='list')
500
500
501 input_hist = shell.input_hist
501 input_hist = shell.input_hist
502 default_length = 40
502 default_length = 40
503 if len(args) == 0:
503 if len(args) == 0:
504 final = len(input_hist)
504 final = len(input_hist)
505 init = max(1,final-default_length)
505 init = max(1,final-default_length)
506 elif len(args) == 1:
506 elif len(args) == 1:
507 final = len(input_hist)
507 final = len(input_hist)
508 init = max(1,final-int(args[0]))
508 init = max(1,final-int(args[0]))
509 elif len(args) == 2:
509 elif len(args) == 2:
510 init,final = map(int,args)
510 init,final = map(int,args)
511 else:
511 else:
512 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
512 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
513 print self.magic_hist.__doc__
513 print self.magic_hist.__doc__
514 return
514 return
515 width = len(str(final))
515 width = len(str(final))
516 line_sep = ['','\n']
516 line_sep = ['','\n']
517 print_nums = not opts.has_key('n')
517 print_nums = not opts.has_key('n')
518 for in_num in range(init,final):
518 for in_num in range(init,final):
519 inline = input_hist[in_num]
519 inline = input_hist[in_num]
520 multiline = int(inline.count('\n') > 1)
520 multiline = int(inline.count('\n') > 1)
521 if print_nums:
521 if print_nums:
522 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
522 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
523 print inline,
523 print inline,
524
524
525 def magic_hist(self, parameter_s=''):
525 def magic_hist(self, parameter_s=''):
526 """Alternate name for %history."""
526 """Alternate name for %history."""
527 return self.magic_history(parameter_s)
527 return self.magic_history(parameter_s)
528
528
529 def magic_p(self, parameter_s=''):
529 def magic_p(self, parameter_s=''):
530 """Just a short alias for Python's 'print'."""
530 """Just a short alias for Python's 'print'."""
531 exec 'print ' + parameter_s in self.shell.user_ns
531 exec 'print ' + parameter_s in self.shell.user_ns
532
532
533 def magic_r(self, parameter_s=''):
533 def magic_r(self, parameter_s=''):
534 """Repeat previous input.
534 """Repeat previous input.
535
535
536 If given an argument, repeats the previous command which starts with
536 If given an argument, repeats the previous command which starts with
537 the same string, otherwise it just repeats the previous input.
537 the same string, otherwise it just repeats the previous input.
538
538
539 Shell escaped commands (with ! as first character) are not recognized
539 Shell escaped commands (with ! as first character) are not recognized
540 by this system, only pure python code and magic commands.
540 by this system, only pure python code and magic commands.
541 """
541 """
542
542
543 start = parameter_s.strip()
543 start = parameter_s.strip()
544 esc_magic = self.shell.ESC_MAGIC
544 esc_magic = self.shell.ESC_MAGIC
545 # Identify magic commands even if automagic is on (which means
545 # Identify magic commands even if automagic is on (which means
546 # the in-memory version is different from that typed by the user).
546 # the in-memory version is different from that typed by the user).
547 if self.shell.rc.automagic:
547 if self.shell.rc.automagic:
548 start_magic = esc_magic+start
548 start_magic = esc_magic+start
549 else:
549 else:
550 start_magic = start
550 start_magic = start
551 # Look through the input history in reverse
551 # Look through the input history in reverse
552 for n in range(len(self.shell.input_hist)-2,0,-1):
552 for n in range(len(self.shell.input_hist)-2,0,-1):
553 input = self.shell.input_hist[n]
553 input = self.shell.input_hist[n]
554 # skip plain 'r' lines so we don't recurse to infinity
554 # skip plain 'r' lines so we don't recurse to infinity
555 if input != 'ipmagic("r")\n' and \
555 if input != 'ipmagic("r")\n' and \
556 (input.startswith(start) or input.startswith(start_magic)):
556 (input.startswith(start) or input.startswith(start_magic)):
557 #print 'match',`input` # dbg
557 #print 'match',`input` # dbg
558 print 'Executing:',input,
558 print 'Executing:',input,
559 self.shell.runlines(input)
559 self.shell.runlines(input)
560 return
560 return
561 print 'No previous input matching `%s` found.' % start
561 print 'No previous input matching `%s` found.' % start
562
562
563 def magic_page(self, parameter_s=''):
563 def magic_page(self, parameter_s=''):
564 """Pretty print the object and display it through a pager.
564 """Pretty print the object and display it through a pager.
565
565
566 If no parameter is given, use _ (last output)."""
566 If no parameter is given, use _ (last output)."""
567 # After a function contributed by Olivier Aubert, slightly modified.
567 # After a function contributed by Olivier Aubert, slightly modified.
568
568
569 oname = parameter_s and parameter_s or '_'
569 oname = parameter_s and parameter_s or '_'
570 info = self._ofind(oname)
570 info = self._ofind(oname)
571 if info['found']:
571 if info['found']:
572 page(pformat(info['obj']))
572 page(pformat(info['obj']))
573 else:
573 else:
574 print 'Object `%s` not found' % oname
574 print 'Object `%s` not found' % oname
575
575
576 def magic_profile(self, parameter_s=''):
576 def magic_profile(self, parameter_s=''):
577 """Print your currently active IPyhton profile."""
577 """Print your currently active IPyhton profile."""
578 if self.shell.rc.profile:
578 if self.shell.rc.profile:
579 printpl('Current IPython profile: $self.shell.rc.profile.')
579 printpl('Current IPython profile: $self.shell.rc.profile.')
580 else:
580 else:
581 print 'No profile active.'
581 print 'No profile active.'
582
582
583 def _inspect(self,meth,oname,**kw):
583 def _inspect(self,meth,oname,**kw):
584 """Generic interface to the inspector system.
584 """Generic interface to the inspector system.
585
585
586 This function is meant to be called by pdef, pdoc & friends."""
586 This function is meant to be called by pdef, pdoc & friends."""
587
587
588 oname = oname.strip()
588 oname = oname.strip()
589 info = Struct(self._ofind(oname))
589 info = Struct(self._ofind(oname))
590 if info.found:
590 if info.found:
591 pmethod = getattr(self.shell.inspector,meth)
591 pmethod = getattr(self.shell.inspector,meth)
592 formatter = info.ismagic and self.format_screen or None
592 formatter = info.ismagic and self.format_screen or None
593 if meth == 'pdoc':
593 if meth == 'pdoc':
594 pmethod(info.obj,oname,formatter)
594 pmethod(info.obj,oname,formatter)
595 elif meth == 'pinfo':
595 elif meth == 'pinfo':
596 pmethod(info.obj,oname,formatter,info,**kw)
596 pmethod(info.obj,oname,formatter,info,**kw)
597 else:
597 else:
598 pmethod(info.obj,oname)
598 pmethod(info.obj,oname)
599 else:
599 else:
600 print 'Object `%s` not found.' % oname
600 print 'Object `%s` not found.' % oname
601 return 'not found' # so callers can take other action
601 return 'not found' # so callers can take other action
602
602
603 def magic_pdef(self, parameter_s=''):
603 def magic_pdef(self, parameter_s=''):
604 """Print the definition header for any callable object.
604 """Print the definition header for any callable object.
605
605
606 If the object is a class, print the constructor information."""
606 If the object is a class, print the constructor information."""
607 self._inspect('pdef',parameter_s)
607 self._inspect('pdef',parameter_s)
608
608
609 def magic_pdoc(self, parameter_s=''):
609 def magic_pdoc(self, parameter_s=''):
610 """Print the docstring for an object.
610 """Print the docstring for an object.
611
611
612 If the given object is a class, it will print both the class and the
612 If the given object is a class, it will print both the class and the
613 constructor docstrings."""
613 constructor docstrings."""
614 self._inspect('pdoc',parameter_s)
614 self._inspect('pdoc',parameter_s)
615
615
616 def magic_psource(self, parameter_s=''):
616 def magic_psource(self, parameter_s=''):
617 """Print (or run through pager) the source code for an object."""
617 """Print (or run through pager) the source code for an object."""
618 self._inspect('psource',parameter_s)
618 self._inspect('psource',parameter_s)
619
619
620 def magic_pfile(self, parameter_s=''):
620 def magic_pfile(self, parameter_s=''):
621 """Print (or run through pager) the file where an object is defined.
621 """Print (or run through pager) the file where an object is defined.
622
622
623 The file opens at the line where the object definition begins. IPython
623 The file opens at the line where the object definition begins. IPython
624 will honor the environment variable PAGER if set, and otherwise will
624 will honor the environment variable PAGER if set, and otherwise will
625 do its best to print the file in a convenient form.
625 do its best to print the file in a convenient form.
626
626
627 If the given argument is not an object currently defined, IPython will
627 If the given argument is not an object currently defined, IPython will
628 try to interpret it as a filename (automatically adding a .py extension
628 try to interpret it as a filename (automatically adding a .py extension
629 if needed). You can thus use %pfile as a syntax highlighting code
629 if needed). You can thus use %pfile as a syntax highlighting code
630 viewer."""
630 viewer."""
631
631
632 # first interpret argument as an object name
632 # first interpret argument as an object name
633 out = self._inspect('pfile',parameter_s)
633 out = self._inspect('pfile',parameter_s)
634 # if not, try the input as a filename
634 # if not, try the input as a filename
635 if out == 'not found':
635 if out == 'not found':
636 try:
636 try:
637 filename = get_py_filename(parameter_s)
637 filename = get_py_filename(parameter_s)
638 except IOError,msg:
638 except IOError,msg:
639 print msg
639 print msg
640 return
640 return
641 page(self.shell.inspector.format(file(filename).read()))
641 page(self.shell.inspector.format(file(filename).read()))
642
642
643 def magic_pinfo(self, parameter_s=''):
643 def magic_pinfo(self, parameter_s=''):
644 """Provide detailed information about an object.
644 """Provide detailed information about an object.
645
645
646 '%pinfo object' is just a synonym for object? or ?object."""
646 '%pinfo object' is just a synonym for object? or ?object."""
647
647
648 #print 'pinfo par: <%s>' % parameter_s # dbg
648 #print 'pinfo par: <%s>' % parameter_s # dbg
649
649
650 # detail_level: 0 -> obj? , 1 -> obj??
650 # detail_level: 0 -> obj? , 1 -> obj??
651 detail_level = 0
651 detail_level = 0
652 # We need to detect if we got called as 'pinfo pinfo foo', which can
652 # We need to detect if we got called as 'pinfo pinfo foo', which can
653 # happen if the user types 'pinfo foo?' at the cmd line.
653 # happen if the user types 'pinfo foo?' at the cmd line.
654 pinfo,qmark1,oname,qmark2 = \
654 pinfo,qmark1,oname,qmark2 = \
655 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
655 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
656 if pinfo or qmark1 or qmark2:
656 if pinfo or qmark1 or qmark2:
657 detail_level = 1
657 detail_level = 1
658 if "*" in oname:
658 if "*" in oname:
659 self.magic_psearch(oname)
659 self.magic_psearch(oname)
660 else:
660 else:
661 self._inspect('pinfo',oname,detail_level=detail_level)
661 self._inspect('pinfo',oname,detail_level=detail_level)
662
662
663 def magic_psearch(self, parameter_s=''):
663 def magic_psearch(self, parameter_s=''):
664 """Search for object in namespaces by wildcard.
664 """Search for object in namespaces by wildcard.
665
665
666 %psearch [options] PATTERN [OBJECT TYPE]
666 %psearch [options] PATTERN [OBJECT TYPE]
667
667
668 Note: ? can be used as a synonym for %psearch, at the beginning or at
668 Note: ? can be used as a synonym for %psearch, at the beginning or at
669 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
669 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
670 rest of the command line must be unchanged (options come first), so
670 rest of the command line must be unchanged (options come first), so
671 for example the following forms are equivalent
671 for example the following forms are equivalent
672
672
673 %psearch -i a* function
673 %psearch -i a* function
674 -i a* function?
674 -i a* function?
675 ?-i a* function
675 ?-i a* function
676
676
677 Arguments:
677 Arguments:
678
678
679 PATTERN
679 PATTERN
680
680
681 where PATTERN is a string containing * as a wildcard similar to its
681 where PATTERN is a string containing * as a wildcard similar to its
682 use in a shell. The pattern is matched in all namespaces on the
682 use in a shell. The pattern is matched in all namespaces on the
683 search path. By default objects starting with a single _ are not
683 search path. By default objects starting with a single _ are not
684 matched, many IPython generated objects have a single
684 matched, many IPython generated objects have a single
685 underscore. The default is case insensitive matching. Matching is
685 underscore. The default is case insensitive matching. Matching is
686 also done on the attributes of objects and not only on the objects
686 also done on the attributes of objects and not only on the objects
687 in a module.
687 in a module.
688
688
689 [OBJECT TYPE]
689 [OBJECT TYPE]
690
690
691 Is the name of a python type from the types module. The name is
691 Is the name of a python type from the types module. The name is
692 given in lowercase without the ending type, ex. StringType is
692 given in lowercase without the ending type, ex. StringType is
693 written string. By adding a type here only objects matching the
693 written string. By adding a type here only objects matching the
694 given type are matched. Using all here makes the pattern match all
694 given type are matched. Using all here makes the pattern match all
695 types (this is the default).
695 types (this is the default).
696
696
697 Options:
697 Options:
698
698
699 -a: makes the pattern match even objects whose names start with a
699 -a: makes the pattern match even objects whose names start with a
700 single underscore. These names are normally ommitted from the
700 single underscore. These names are normally ommitted from the
701 search.
701 search.
702
702
703 -i/-c: make the pattern case insensitive/sensitive. If neither of
703 -i/-c: make the pattern case insensitive/sensitive. If neither of
704 these options is given, the default is read from your ipythonrc
704 these options is given, the default is read from your ipythonrc
705 file. The option name which sets this value is
705 file. The option name which sets this value is
706 'wildcards_case_sensitive'. If this option is not specified in your
706 'wildcards_case_sensitive'. If this option is not specified in your
707 ipythonrc file, IPython's internal default is to do a case sensitive
707 ipythonrc file, IPython's internal default is to do a case sensitive
708 search.
708 search.
709
709
710 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
710 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
711 specifiy can be searched in any of the following namespaces:
711 specifiy can be searched in any of the following namespaces:
712 'builtin', 'user', 'user_global','internal', 'alias', where
712 'builtin', 'user', 'user_global','internal', 'alias', where
713 'builtin' and 'user' are the search defaults. Note that you should
713 'builtin' and 'user' are the search defaults. Note that you should
714 not use quotes when specifying namespaces.
714 not use quotes when specifying namespaces.
715
715
716 'Builtin' contains the python module builtin, 'user' contains all
716 'Builtin' contains the python module builtin, 'user' contains all
717 user data, 'alias' only contain the shell aliases and no python
717 user data, 'alias' only contain the shell aliases and no python
718 objects, 'internal' contains objects used by IPython. The
718 objects, 'internal' contains objects used by IPython. The
719 'user_global' namespace is only used by embedded IPython instances,
719 'user_global' namespace is only used by embedded IPython instances,
720 and it contains module-level globals. You can add namespaces to the
720 and it contains module-level globals. You can add namespaces to the
721 search with -s or exclude them with -e (these options can be given
721 search with -s or exclude them with -e (these options can be given
722 more than once).
722 more than once).
723
723
724 Examples:
724 Examples:
725
725
726 %psearch a* -> objects beginning with an a
726 %psearch a* -> objects beginning with an a
727 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
727 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
728 %psearch a* function -> all functions beginning with an a
728 %psearch a* function -> all functions beginning with an a
729 %psearch re.e* -> objects beginning with an e in module re
729 %psearch re.e* -> objects beginning with an e in module re
730 %psearch r*.e* -> objects that start with e in modules starting in r
730 %psearch r*.e* -> objects that start with e in modules starting in r
731 %psearch r*.* string -> all strings in modules beginning with r
731 %psearch r*.* string -> all strings in modules beginning with r
732
732
733 Case sensitve search:
733 Case sensitve search:
734
734
735 %psearch -c a* list all object beginning with lower case a
735 %psearch -c a* list all object beginning with lower case a
736
736
737 Show objects beginning with a single _:
737 Show objects beginning with a single _:
738
738
739 %psearch -a _* list objects beginning with a single underscore"""
739 %psearch -a _* list objects beginning with a single underscore"""
740
740
741 # default namespaces to be searched
741 # default namespaces to be searched
742 def_search = ['user','builtin']
742 def_search = ['user','builtin']
743
743
744 # Process options/args
744 # Process options/args
745 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
745 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
746 opt = opts.get
746 opt = opts.get
747 shell = self.shell
747 shell = self.shell
748 psearch = shell.inspector.psearch
748 psearch = shell.inspector.psearch
749
749
750 # select case options
750 # select case options
751 if opts.has_key('i'):
751 if opts.has_key('i'):
752 ignore_case = True
752 ignore_case = True
753 elif opts.has_key('c'):
753 elif opts.has_key('c'):
754 ignore_case = False
754 ignore_case = False
755 else:
755 else:
756 ignore_case = not shell.rc.wildcards_case_sensitive
756 ignore_case = not shell.rc.wildcards_case_sensitive
757
757
758 # Build list of namespaces to search from user options
758 # Build list of namespaces to search from user options
759 def_search.extend(opt('s',[]))
759 def_search.extend(opt('s',[]))
760 ns_exclude = ns_exclude=opt('e',[])
760 ns_exclude = ns_exclude=opt('e',[])
761 ns_search = [nm for nm in def_search if nm not in ns_exclude]
761 ns_search = [nm for nm in def_search if nm not in ns_exclude]
762
762
763 # Call the actual search
763 # Call the actual search
764 try:
764 try:
765 psearch(args,shell.ns_table,ns_search,
765 psearch(args,shell.ns_table,ns_search,
766 show_all=opt('a'),ignore_case=ignore_case)
766 show_all=opt('a'),ignore_case=ignore_case)
767 except:
767 except:
768 shell.showtraceback()
768 shell.showtraceback()
769
769
770 def magic_who_ls(self, parameter_s=''):
770 def magic_who_ls(self, parameter_s=''):
771 """Return a sorted list of all interactive variables.
771 """Return a sorted list of all interactive variables.
772
772
773 If arguments are given, only variables of types matching these
773 If arguments are given, only variables of types matching these
774 arguments are returned."""
774 arguments are returned."""
775
775
776 user_ns = self.shell.user_ns
776 user_ns = self.shell.user_ns
777 internal_ns = self.shell.internal_ns
777 internal_ns = self.shell.internal_ns
778 user_config_ns = self.shell.user_config_ns
778 user_config_ns = self.shell.user_config_ns
779 out = []
779 out = []
780 typelist = parameter_s.split()
780 typelist = parameter_s.split()
781
781
782 for i in user_ns:
782 for i in user_ns:
783 if not (i.startswith('_') or i.startswith('_i')) \
783 if not (i.startswith('_') or i.startswith('_i')) \
784 and not (i in internal_ns or i in user_config_ns):
784 and not (i in internal_ns or i in user_config_ns):
785 if typelist:
785 if typelist:
786 if type(user_ns[i]).__name__ in typelist:
786 if type(user_ns[i]).__name__ in typelist:
787 out.append(i)
787 out.append(i)
788 else:
788 else:
789 out.append(i)
789 out.append(i)
790 out.sort()
790 out.sort()
791 return out
791 return out
792
792
793 def magic_who(self, parameter_s=''):
793 def magic_who(self, parameter_s=''):
794 """Print all interactive variables, with some minimal formatting.
794 """Print all interactive variables, with some minimal formatting.
795
795
796 If any arguments are given, only variables whose type matches one of
796 If any arguments are given, only variables whose type matches one of
797 these are printed. For example:
797 these are printed. For example:
798
798
799 %who function str
799 %who function str
800
800
801 will only list functions and strings, excluding all other types of
801 will only list functions and strings, excluding all other types of
802 variables. To find the proper type names, simply use type(var) at a
802 variables. To find the proper type names, simply use type(var) at a
803 command line to see how python prints type names. For example:
803 command line to see how python prints type names. For example:
804
804
805 In [1]: type('hello')\\
805 In [1]: type('hello')\\
806 Out[1]: <type 'str'>
806 Out[1]: <type 'str'>
807
807
808 indicates that the type name for strings is 'str'.
808 indicates that the type name for strings is 'str'.
809
809
810 %who always excludes executed names loaded through your configuration
810 %who always excludes executed names loaded through your configuration
811 file and things which are internal to IPython.
811 file and things which are internal to IPython.
812
812
813 This is deliberate, as typically you may load many modules and the
813 This is deliberate, as typically you may load many modules and the
814 purpose of %who is to show you only what you've manually defined."""
814 purpose of %who is to show you only what you've manually defined."""
815
815
816 varlist = self.magic_who_ls(parameter_s)
816 varlist = self.magic_who_ls(parameter_s)
817 if not varlist:
817 if not varlist:
818 print 'Interactive namespace is empty.'
818 print 'Interactive namespace is empty.'
819 return
819 return
820
820
821 # if we have variables, move on...
821 # if we have variables, move on...
822
822
823 # stupid flushing problem: when prompts have no separators, stdout is
823 # stupid flushing problem: when prompts have no separators, stdout is
824 # getting lost. I'm starting to think this is a python bug. I'm having
824 # getting lost. I'm starting to think this is a python bug. I'm having
825 # to force a flush with a print because even a sys.stdout.flush
825 # to force a flush with a print because even a sys.stdout.flush
826 # doesn't seem to do anything!
826 # doesn't seem to do anything!
827
827
828 count = 0
828 count = 0
829 for i in varlist:
829 for i in varlist:
830 print i+'\t',
830 print i+'\t',
831 count += 1
831 count += 1
832 if count > 8:
832 if count > 8:
833 count = 0
833 count = 0
834 print
834 print
835 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
835 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
836
836
837 print # well, this does force a flush at the expense of an extra \n
837 print # well, this does force a flush at the expense of an extra \n
838
838
839 def magic_whos(self, parameter_s=''):
839 def magic_whos(self, parameter_s=''):
840 """Like %who, but gives some extra information about each variable.
840 """Like %who, but gives some extra information about each variable.
841
841
842 The same type filtering of %who can be applied here.
842 The same type filtering of %who can be applied here.
843
843
844 For all variables, the type is printed. Additionally it prints:
844 For all variables, the type is printed. Additionally it prints:
845
845
846 - For {},[],(): their length.
846 - For {},[],(): their length.
847
847
848 - For Numeric arrays, a summary with shape, number of elements,
848 - For Numeric arrays, a summary with shape, number of elements,
849 typecode and size in memory.
849 typecode and size in memory.
850
850
851 - Everything else: a string representation, snipping their middle if
851 - Everything else: a string representation, snipping their middle if
852 too long."""
852 too long."""
853
853
854 varnames = self.magic_who_ls(parameter_s)
854 varnames = self.magic_who_ls(parameter_s)
855 if not varnames:
855 if not varnames:
856 print 'Interactive namespace is empty.'
856 print 'Interactive namespace is empty.'
857 return
857 return
858
858
859 # if we have variables, move on...
859 # if we have variables, move on...
860
860
861 # for these types, show len() instead of data:
861 # for these types, show len() instead of data:
862 seq_types = [types.DictType,types.ListType,types.TupleType]
862 seq_types = [types.DictType,types.ListType,types.TupleType]
863
863
864 # for Numeric arrays, display summary info
864 # for Numeric arrays, display summary info
865 try:
865 try:
866 import Numeric
866 import Numeric
867 except ImportError:
867 except ImportError:
868 array_type = None
868 array_type = None
869 else:
869 else:
870 array_type = Numeric.ArrayType.__name__
870 array_type = Numeric.ArrayType.__name__
871
871
872 # Find all variable names and types so we can figure out column sizes
872 # Find all variable names and types so we can figure out column sizes
873 get_vars = lambda i: self.shell.user_ns[i]
873 get_vars = lambda i: self.shell.user_ns[i]
874 type_name = lambda v: type(v).__name__
874 type_name = lambda v: type(v).__name__
875 varlist = map(get_vars,varnames)
875 varlist = map(get_vars,varnames)
876
876
877 typelist = []
877 typelist = []
878 for vv in varlist:
878 for vv in varlist:
879 tt = type_name(vv)
879 tt = type_name(vv)
880 if tt=='instance':
880 if tt=='instance':
881 typelist.append(str(vv.__class__))
881 typelist.append(str(vv.__class__))
882 else:
882 else:
883 typelist.append(tt)
883 typelist.append(tt)
884
884
885 # column labels and # of spaces as separator
885 # column labels and # of spaces as separator
886 varlabel = 'Variable'
886 varlabel = 'Variable'
887 typelabel = 'Type'
887 typelabel = 'Type'
888 datalabel = 'Data/Info'
888 datalabel = 'Data/Info'
889 colsep = 3
889 colsep = 3
890 # variable format strings
890 # variable format strings
891 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
891 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
892 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
892 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
893 aformat = "%s: %s elems, type `%s`, %s bytes"
893 aformat = "%s: %s elems, type `%s`, %s bytes"
894 # find the size of the columns to format the output nicely
894 # find the size of the columns to format the output nicely
895 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
895 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
896 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
896 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
897 # table header
897 # table header
898 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
898 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
899 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
899 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
900 # and the table itself
900 # and the table itself
901 kb = 1024
901 kb = 1024
902 Mb = 1048576 # kb**2
902 Mb = 1048576 # kb**2
903 for vname,var,vtype in zip(varnames,varlist,typelist):
903 for vname,var,vtype in zip(varnames,varlist,typelist):
904 print itpl(vformat),
904 print itpl(vformat),
905 if vtype in seq_types:
905 if vtype in seq_types:
906 print len(var)
906 print len(var)
907 elif vtype==array_type:
907 elif vtype==array_type:
908 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
908 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
909 vsize = Numeric.size(var)
909 vsize = Numeric.size(var)
910 vbytes = vsize*var.itemsize()
910 vbytes = vsize*var.itemsize()
911 if vbytes < 100000:
911 if vbytes < 100000:
912 print aformat % (vshape,vsize,var.typecode(),vbytes)
912 print aformat % (vshape,vsize,var.typecode(),vbytes)
913 else:
913 else:
914 print aformat % (vshape,vsize,var.typecode(),vbytes),
914 print aformat % (vshape,vsize,var.typecode(),vbytes),
915 if vbytes < Mb:
915 if vbytes < Mb:
916 print '(%s kb)' % (vbytes/kb,)
916 print '(%s kb)' % (vbytes/kb,)
917 else:
917 else:
918 print '(%s Mb)' % (vbytes/Mb,)
918 print '(%s Mb)' % (vbytes/Mb,)
919 else:
919 else:
920 vstr = str(var).replace('\n','\\n')
920 vstr = str(var).replace('\n','\\n')
921 if len(vstr) < 50:
921 if len(vstr) < 50:
922 print vstr
922 print vstr
923 else:
923 else:
924 printpl(vfmt_short)
924 printpl(vfmt_short)
925
925
926 def magic_reset(self, parameter_s=''):
926 def magic_reset(self, parameter_s=''):
927 """Resets the namespace by removing all names defined by the user.
927 """Resets the namespace by removing all names defined by the user.
928
928
929 Input/Output history are left around in case you need them."""
929 Input/Output history are left around in case you need them."""
930
930
931 ans = raw_input(
931 ans = raw_input(
932 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
932 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
933 if not ans.lower() == 'y':
933 if not ans.lower() == 'y':
934 print 'Nothing done.'
934 print 'Nothing done.'
935 return
935 return
936 user_ns = self.shell.user_ns
936 user_ns = self.shell.user_ns
937 for i in self.magic_who_ls():
937 for i in self.magic_who_ls():
938 del(user_ns[i])
938 del(user_ns[i])
939
939
940 def magic_config(self,parameter_s=''):
940 def magic_config(self,parameter_s=''):
941 """Show IPython's internal configuration."""
941 """Show IPython's internal configuration."""
942
942
943 page('Current configuration structure:\n'+
943 page('Current configuration structure:\n'+
944 pformat(self.shell.rc.dict()))
944 pformat(self.shell.rc.dict()))
945
945
946 def magic_logstart(self,parameter_s=''):
946 def magic_logstart(self,parameter_s=''):
947 """Start logging anywhere in a session.
947 """Start logging anywhere in a session.
948
948
949 %logstart [-o|-t] [log_name [log_mode]]
949 %logstart [-o|-t] [log_name [log_mode]]
950
950
951 If no name is given, it defaults to a file named 'ipython_log.py' in your
951 If no name is given, it defaults to a file named 'ipython_log.py' in your
952 current directory, in 'rotate' mode (see below).
952 current directory, in 'rotate' mode (see below).
953
953
954 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
954 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
955 history up to that point and then continues logging.
955 history up to that point and then continues logging.
956
956
957 %logstart takes a second optional parameter: logging mode. This can be one
957 %logstart takes a second optional parameter: logging mode. This can be one
958 of (note that the modes are given unquoted):\\
958 of (note that the modes are given unquoted):\\
959 append: well, that says it.\\
959 append: well, that says it.\\
960 backup: rename (if exists) to name~ and start name.\\
960 backup: rename (if exists) to name~ and start name.\\
961 global: single logfile in your home dir, appended to.\\
961 global: single logfile in your home dir, appended to.\\
962 over : overwrite existing log.\\
962 over : overwrite existing log.\\
963 rotate: create rotating logs name.1~, name.2~, etc.
963 rotate: create rotating logs name.1~, name.2~, etc.
964
964
965 Options:
965 Options:
966
966
967 -o: log also IPython's output. In this mode, all commands which
967 -o: log also IPython's output. In this mode, all commands which
968 generate an Out[NN] prompt are recorded to the logfile, right after
968 generate an Out[NN] prompt are recorded to the logfile, right after
969 their corresponding input line. The output lines are always
969 their corresponding input line. The output lines are always
970 prepended with a '#[Out]# ' marker, so that the log remains valid
970 prepended with a '#[Out]# ' marker, so that the log remains valid
971 Python code.
971 Python code.
972
972
973 Since this marker is always the same, filtering only the output from
973 Since this marker is always the same, filtering only the output from
974 a log is very easy, using for example a simple awk call:
974 a log is very easy, using for example a simple awk call:
975
975
976 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
976 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
977
977
978 -t: put timestamps before each input line logged (these are put in
978 -t: put timestamps before each input line logged (these are put in
979 comments)."""
979 comments)."""
980
980
981 opts,par = self.parse_options(parameter_s,'ot')
981 opts,par = self.parse_options(parameter_s,'ot')
982 log_output = 'o' in opts
982 log_output = 'o' in opts
983 timestamp = 't' in opts
983 timestamp = 't' in opts
984
984
985 rc = self.shell.rc
985 rc = self.shell.rc
986 logger = self.shell.logger
986 logger = self.shell.logger
987
987
988 # if no args are given, the defaults set in the logger constructor by
988 # if no args are given, the defaults set in the logger constructor by
989 # ipytohn remain valid
989 # ipytohn remain valid
990 if par:
990 if par:
991 try:
991 try:
992 logfname,logmode = par.split()
992 logfname,logmode = par.split()
993 except:
993 except:
994 logfname = par
994 logfname = par
995 logmode = 'backup'
995 logmode = 'backup'
996 else:
996 else:
997 logfname = logger.logfname
997 logfname = logger.logfname
998 logmode = logger.logmode
998 logmode = logger.logmode
999 # put logfname into rc struct as if it had been called on the command
999 # put logfname into rc struct as if it had been called on the command
1000 # line, so it ends up saved in the log header Save it in case we need
1000 # line, so it ends up saved in the log header Save it in case we need
1001 # to restore it...
1001 # to restore it...
1002 old_logfile = rc.opts.get('logfile','')
1002 old_logfile = rc.opts.get('logfile','')
1003 if logfname:
1003 if logfname:
1004 logfname = os.path.expanduser(logfname)
1004 logfname = os.path.expanduser(logfname)
1005 rc.opts.logfile = logfname
1005 rc.opts.logfile = logfname
1006 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1006 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1007 try:
1007 try:
1008 started = logger.logstart(logfname,loghead,logmode,
1008 started = logger.logstart(logfname,loghead,logmode,
1009 log_output,timestamp)
1009 log_output,timestamp)
1010 except:
1010 except:
1011 rc.opts.logfile = old_logfile
1011 rc.opts.logfile = old_logfile
1012 warn("Couldn't start log: %s" % sys.exc_info()[1])
1012 warn("Couldn't start log: %s" % sys.exc_info()[1])
1013 else:
1013 else:
1014 # log input history up to this point, optionally interleaving
1014 # log input history up to this point, optionally interleaving
1015 # output if requested
1015 # output if requested
1016
1016
1017 if timestamp:
1017 if timestamp:
1018 # disable timestamping for the previous history, since we've
1018 # disable timestamping for the previous history, since we've
1019 # lost those already (no time machine here).
1019 # lost those already (no time machine here).
1020 logger.timestamp = False
1020 logger.timestamp = False
1021 if log_output:
1021 if log_output:
1022 log_write = logger.log_write
1022 log_write = logger.log_write
1023 input_hist = self.shell.input_hist
1023 input_hist = self.shell.input_hist
1024 output_hist = self.shell.output_hist
1024 output_hist = self.shell.output_hist
1025 for n in range(1,len(input_hist)-1):
1025 for n in range(1,len(input_hist)-1):
1026 log_write(input_hist[n].rstrip())
1026 log_write(input_hist[n].rstrip())
1027 if n in output_hist:
1027 if n in output_hist:
1028 log_write(repr(output_hist[n]),'output')
1028 log_write(repr(output_hist[n]),'output')
1029 else:
1029 else:
1030 logger.log_write(self.shell.input_hist[1:])
1030 logger.log_write(self.shell.input_hist[1:])
1031 if timestamp:
1031 if timestamp:
1032 # re-enable timestamping
1032 # re-enable timestamping
1033 logger.timestamp = True
1033 logger.timestamp = True
1034
1034
1035 print ('Activating auto-logging. '
1035 print ('Activating auto-logging. '
1036 'Current session state plus future input saved.')
1036 'Current session state plus future input saved.')
1037 logger.logstate()
1037 logger.logstate()
1038
1038
1039 def magic_logoff(self,parameter_s=''):
1039 def magic_logoff(self,parameter_s=''):
1040 """Temporarily stop logging.
1040 """Temporarily stop logging.
1041
1041
1042 You must have previously started logging."""
1042 You must have previously started logging."""
1043 self.shell.logger.switch_log(0)
1043 self.shell.logger.switch_log(0)
1044
1044
1045 def magic_logon(self,parameter_s=''):
1045 def magic_logon(self,parameter_s=''):
1046 """Restart logging.
1046 """Restart logging.
1047
1047
1048 This function is for restarting logging which you've temporarily
1048 This function is for restarting logging which you've temporarily
1049 stopped with %logoff. For starting logging for the first time, you
1049 stopped with %logoff. For starting logging for the first time, you
1050 must use the %logstart function, which allows you to specify an
1050 must use the %logstart function, which allows you to specify an
1051 optional log filename."""
1051 optional log filename."""
1052
1052
1053 self.shell.logger.switch_log(1)
1053 self.shell.logger.switch_log(1)
1054
1054
1055 def magic_logstate(self,parameter_s=''):
1055 def magic_logstate(self,parameter_s=''):
1056 """Print the status of the logging system."""
1056 """Print the status of the logging system."""
1057
1057
1058 self.shell.logger.logstate()
1058 self.shell.logger.logstate()
1059
1059
1060 def magic_pdb(self, parameter_s=''):
1060 def magic_pdb(self, parameter_s=''):
1061 """Control the calling of the pdb interactive debugger.
1061 """Control the calling of the pdb interactive debugger.
1062
1062
1063 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1063 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1064 argument it works as a toggle.
1064 argument it works as a toggle.
1065
1065
1066 When an exception is triggered, IPython can optionally call the
1066 When an exception is triggered, IPython can optionally call the
1067 interactive pdb debugger after the traceback printout. %pdb toggles
1067 interactive pdb debugger after the traceback printout. %pdb toggles
1068 this feature on and off."""
1068 this feature on and off."""
1069
1069
1070 par = parameter_s.strip().lower()
1070 par = parameter_s.strip().lower()
1071
1071
1072 if par:
1072 if par:
1073 try:
1073 try:
1074 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1074 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1075 except KeyError:
1075 except KeyError:
1076 print ('Incorrect argument. Use on/1, off/0, '
1076 print ('Incorrect argument. Use on/1, off/0, '
1077 'or nothing for a toggle.')
1077 'or nothing for a toggle.')
1078 return
1078 return
1079 else:
1079 else:
1080 # toggle
1080 # toggle
1081 new_pdb = not self.shell.InteractiveTB.call_pdb
1081 new_pdb = not self.shell.InteractiveTB.call_pdb
1082
1082
1083 # set on the shell
1083 # set on the shell
1084 self.shell.call_pdb = new_pdb
1084 self.shell.call_pdb = new_pdb
1085 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1085 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1086
1086
1087 def magic_prun(self, parameter_s ='',user_mode=1,
1087 def magic_prun(self, parameter_s ='',user_mode=1,
1088 opts=None,arg_lst=None,prog_ns=None):
1088 opts=None,arg_lst=None,prog_ns=None):
1089
1089
1090 """Run a statement through the python code profiler.
1090 """Run a statement through the python code profiler.
1091
1091
1092 Usage:\\
1092 Usage:\\
1093 %prun [options] statement
1093 %prun [options] statement
1094
1094
1095 The given statement (which doesn't require quote marks) is run via the
1095 The given statement (which doesn't require quote marks) is run via the
1096 python profiler in a manner similar to the profile.run() function.
1096 python profiler in a manner similar to the profile.run() function.
1097 Namespaces are internally managed to work correctly; profile.run
1097 Namespaces are internally managed to work correctly; profile.run
1098 cannot be used in IPython because it makes certain assumptions about
1098 cannot be used in IPython because it makes certain assumptions about
1099 namespaces which do not hold under IPython.
1099 namespaces which do not hold under IPython.
1100
1100
1101 Options:
1101 Options:
1102
1102
1103 -l <limit>: you can place restrictions on what or how much of the
1103 -l <limit>: you can place restrictions on what or how much of the
1104 profile gets printed. The limit value can be:
1104 profile gets printed. The limit value can be:
1105
1105
1106 * A string: only information for function names containing this string
1106 * A string: only information for function names containing this string
1107 is printed.
1107 is printed.
1108
1108
1109 * An integer: only these many lines are printed.
1109 * An integer: only these many lines are printed.
1110
1110
1111 * A float (between 0 and 1): this fraction of the report is printed
1111 * A float (between 0 and 1): this fraction of the report is printed
1112 (for example, use a limit of 0.4 to see the topmost 40% only).
1112 (for example, use a limit of 0.4 to see the topmost 40% only).
1113
1113
1114 You can combine several limits with repeated use of the option. For
1114 You can combine several limits with repeated use of the option. For
1115 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1115 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1116 information about class constructors.
1116 information about class constructors.
1117
1117
1118 -r: return the pstats.Stats object generated by the profiling. This
1118 -r: return the pstats.Stats object generated by the profiling. This
1119 object has all the information about the profile in it, and you can
1119 object has all the information about the profile in it, and you can
1120 later use it for further analysis or in other functions.
1120 later use it for further analysis or in other functions.
1121
1121
1122 Since magic functions have a particular form of calling which prevents
1122 Since magic functions have a particular form of calling which prevents
1123 you from writing something like:\\
1123 you from writing something like:\\
1124 In [1]: p = %prun -r print 4 # invalid!\\
1124 In [1]: p = %prun -r print 4 # invalid!\\
1125 you must instead use IPython's automatic variables to assign this:\\
1125 you must instead use IPython's automatic variables to assign this:\\
1126 In [1]: %prun -r print 4 \\
1126 In [1]: %prun -r print 4 \\
1127 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1127 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1128 In [2]: stats = _
1128 In [2]: stats = _
1129
1129
1130 If you really need to assign this value via an explicit function call,
1130 If you really need to assign this value via an explicit function call,
1131 you can always tap directly into the true name of the magic function
1131 you can always tap directly into the true name of the magic function
1132 by using the ipmagic function (which IPython automatically adds to the
1132 by using the ipmagic function (which IPython automatically adds to the
1133 builtins):\\
1133 builtins):\\
1134 In [3]: stats = ipmagic('prun','-r print 4')
1134 In [3]: stats = ipmagic('prun','-r print 4')
1135
1135
1136 You can type ipmagic? for more details on ipmagic.
1136 You can type ipmagic? for more details on ipmagic.
1137
1137
1138 -s <key>: sort profile by given key. You can provide more than one key
1138 -s <key>: sort profile by given key. You can provide more than one key
1139 by using the option several times: '-s key1 -s key2 -s key3...'. The
1139 by using the option several times: '-s key1 -s key2 -s key3...'. The
1140 default sorting key is 'time'.
1140 default sorting key is 'time'.
1141
1141
1142 The following is copied verbatim from the profile documentation
1142 The following is copied verbatim from the profile documentation
1143 referenced below:
1143 referenced below:
1144
1144
1145 When more than one key is provided, additional keys are used as
1145 When more than one key is provided, additional keys are used as
1146 secondary criteria when the there is equality in all keys selected
1146 secondary criteria when the there is equality in all keys selected
1147 before them.
1147 before them.
1148
1148
1149 Abbreviations can be used for any key names, as long as the
1149 Abbreviations can be used for any key names, as long as the
1150 abbreviation is unambiguous. The following are the keys currently
1150 abbreviation is unambiguous. The following are the keys currently
1151 defined:
1151 defined:
1152
1152
1153 Valid Arg Meaning\\
1153 Valid Arg Meaning\\
1154 "calls" call count\\
1154 "calls" call count\\
1155 "cumulative" cumulative time\\
1155 "cumulative" cumulative time\\
1156 "file" file name\\
1156 "file" file name\\
1157 "module" file name\\
1157 "module" file name\\
1158 "pcalls" primitive call count\\
1158 "pcalls" primitive call count\\
1159 "line" line number\\
1159 "line" line number\\
1160 "name" function name\\
1160 "name" function name\\
1161 "nfl" name/file/line\\
1161 "nfl" name/file/line\\
1162 "stdname" standard name\\
1162 "stdname" standard name\\
1163 "time" internal time
1163 "time" internal time
1164
1164
1165 Note that all sorts on statistics are in descending order (placing
1165 Note that all sorts on statistics are in descending order (placing
1166 most time consuming items first), where as name, file, and line number
1166 most time consuming items first), where as name, file, and line number
1167 searches are in ascending order (i.e., alphabetical). The subtle
1167 searches are in ascending order (i.e., alphabetical). The subtle
1168 distinction between "nfl" and "stdname" is that the standard name is a
1168 distinction between "nfl" and "stdname" is that the standard name is a
1169 sort of the name as printed, which means that the embedded line
1169 sort of the name as printed, which means that the embedded line
1170 numbers get compared in an odd way. For example, lines 3, 20, and 40
1170 numbers get compared in an odd way. For example, lines 3, 20, and 40
1171 would (if the file names were the same) appear in the string order
1171 would (if the file names were the same) appear in the string order
1172 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1172 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1173 line numbers. In fact, sort_stats("nfl") is the same as
1173 line numbers. In fact, sort_stats("nfl") is the same as
1174 sort_stats("name", "file", "line").
1174 sort_stats("name", "file", "line").
1175
1175
1176 -T <filename>: save profile results as shown on screen to a text
1176 -T <filename>: save profile results as shown on screen to a text
1177 file. The profile is still shown on screen.
1177 file. The profile is still shown on screen.
1178
1178
1179 -D <filename>: save (via dump_stats) profile statistics to given
1179 -D <filename>: save (via dump_stats) profile statistics to given
1180 filename. This data is in a format understod by the pstats module, and
1180 filename. This data is in a format understod by the pstats module, and
1181 is generated by a call to the dump_stats() method of profile
1181 is generated by a call to the dump_stats() method of profile
1182 objects. The profile is still shown on screen.
1182 objects. The profile is still shown on screen.
1183
1183
1184 If you want to run complete programs under the profiler's control, use
1184 If you want to run complete programs under the profiler's control, use
1185 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1185 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1186 contains profiler specific options as described here.
1186 contains profiler specific options as described here.
1187
1187
1188 You can read the complete documentation for the profile module with:\\
1188 You can read the complete documentation for the profile module with:\\
1189 In [1]: import profile; profile.help() """
1189 In [1]: import profile; profile.help() """
1190
1190
1191 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1191 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1192 # protect user quote marks
1192 # protect user quote marks
1193 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1193 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1194
1194
1195 if user_mode: # regular user call
1195 if user_mode: # regular user call
1196 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1196 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1197 list_all=1)
1197 list_all=1)
1198 namespace = self.shell.user_ns
1198 namespace = self.shell.user_ns
1199 else: # called to run a program by %run -p
1199 else: # called to run a program by %run -p
1200 try:
1200 try:
1201 filename = get_py_filename(arg_lst[0])
1201 filename = get_py_filename(arg_lst[0])
1202 except IOError,msg:
1202 except IOError,msg:
1203 error(msg)
1203 error(msg)
1204 return
1204 return
1205
1205
1206 arg_str = 'execfile(filename,prog_ns)'
1206 arg_str = 'execfile(filename,prog_ns)'
1207 namespace = locals()
1207 namespace = locals()
1208
1208
1209 opts.merge(opts_def)
1209 opts.merge(opts_def)
1210
1210
1211 prof = profile.Profile()
1211 prof = profile.Profile()
1212 try:
1212 try:
1213 prof = prof.runctx(arg_str,namespace,namespace)
1213 prof = prof.runctx(arg_str,namespace,namespace)
1214 sys_exit = ''
1214 sys_exit = ''
1215 except SystemExit:
1215 except SystemExit:
1216 sys_exit = """*** SystemExit exception caught in code being profiled."""
1216 sys_exit = """*** SystemExit exception caught in code being profiled."""
1217
1217
1218 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1218 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1219
1219
1220 lims = opts.l
1220 lims = opts.l
1221 if lims:
1221 if lims:
1222 lims = [] # rebuild lims with ints/floats/strings
1222 lims = [] # rebuild lims with ints/floats/strings
1223 for lim in opts.l:
1223 for lim in opts.l:
1224 try:
1224 try:
1225 lims.append(int(lim))
1225 lims.append(int(lim))
1226 except ValueError:
1226 except ValueError:
1227 try:
1227 try:
1228 lims.append(float(lim))
1228 lims.append(float(lim))
1229 except ValueError:
1229 except ValueError:
1230 lims.append(lim)
1230 lims.append(lim)
1231
1231
1232 # trap output
1232 # trap output
1233 sys_stdout = sys.stdout
1233 sys_stdout = sys.stdout
1234 stdout_trap = StringIO()
1234 stdout_trap = StringIO()
1235 try:
1235 try:
1236 sys.stdout = stdout_trap
1236 sys.stdout = stdout_trap
1237 stats.print_stats(*lims)
1237 stats.print_stats(*lims)
1238 finally:
1238 finally:
1239 sys.stdout = sys_stdout
1239 sys.stdout = sys_stdout
1240 output = stdout_trap.getvalue()
1240 output = stdout_trap.getvalue()
1241 output = output.rstrip()
1241 output = output.rstrip()
1242
1242
1243 page(output,screen_lines=self.shell.rc.screen_length)
1243 page(output,screen_lines=self.shell.rc.screen_length)
1244 print sys_exit,
1244 print sys_exit,
1245
1245
1246 dump_file = opts.D[0]
1246 dump_file = opts.D[0]
1247 text_file = opts.T[0]
1247 text_file = opts.T[0]
1248 if dump_file:
1248 if dump_file:
1249 prof.dump_stats(dump_file)
1249 prof.dump_stats(dump_file)
1250 print '\n*** Profile stats marshalled to file',\
1250 print '\n*** Profile stats marshalled to file',\
1251 `dump_file`+'.',sys_exit
1251 `dump_file`+'.',sys_exit
1252 if text_file:
1252 if text_file:
1253 file(text_file,'w').write(output)
1253 file(text_file,'w').write(output)
1254 print '\n*** Profile printout saved to text file',\
1254 print '\n*** Profile printout saved to text file',\
1255 `text_file`+'.',sys_exit
1255 `text_file`+'.',sys_exit
1256
1256
1257 if opts.has_key('r'):
1257 if opts.has_key('r'):
1258 return stats
1258 return stats
1259 else:
1259 else:
1260 return None
1260 return None
1261
1261
1262 def magic_run(self, parameter_s ='',runner=None):
1262 def magic_run(self, parameter_s ='',runner=None):
1263 """Run the named file inside IPython as a program.
1263 """Run the named file inside IPython as a program.
1264
1264
1265 Usage:\\
1265 Usage:\\
1266 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1266 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1267
1267
1268 Parameters after the filename are passed as command-line arguments to
1268 Parameters after the filename are passed as command-line arguments to
1269 the program (put in sys.argv). Then, control returns to IPython's
1269 the program (put in sys.argv). Then, control returns to IPython's
1270 prompt.
1270 prompt.
1271
1271
1272 This is similar to running at a system prompt:\\
1272 This is similar to running at a system prompt:\\
1273 $ python file args\\
1273 $ python file args\\
1274 but with the advantage of giving you IPython's tracebacks, and of
1274 but with the advantage of giving you IPython's tracebacks, and of
1275 loading all variables into your interactive namespace for further use
1275 loading all variables into your interactive namespace for further use
1276 (unless -p is used, see below).
1276 (unless -p is used, see below).
1277
1277
1278 The file is executed in a namespace initially consisting only of
1278 The file is executed in a namespace initially consisting only of
1279 __name__=='__main__' and sys.argv constructed as indicated. It thus
1279 __name__=='__main__' and sys.argv constructed as indicated. It thus
1280 sees its environment as if it were being run as a stand-alone
1280 sees its environment as if it were being run as a stand-alone
1281 program. But after execution, the IPython interactive namespace gets
1281 program. But after execution, the IPython interactive namespace gets
1282 updated with all variables defined in the program (except for __name__
1282 updated with all variables defined in the program (except for __name__
1283 and sys.argv). This allows for very convenient loading of code for
1283 and sys.argv). This allows for very convenient loading of code for
1284 interactive work, while giving each program a 'clean sheet' to run in.
1284 interactive work, while giving each program a 'clean sheet' to run in.
1285
1285
1286 Options:
1286 Options:
1287
1287
1288 -n: __name__ is NOT set to '__main__', but to the running file's name
1288 -n: __name__ is NOT set to '__main__', but to the running file's name
1289 without extension (as python does under import). This allows running
1289 without extension (as python does under import). This allows running
1290 scripts and reloading the definitions in them without calling code
1290 scripts and reloading the definitions in them without calling code
1291 protected by an ' if __name__ == "__main__" ' clause.
1291 protected by an ' if __name__ == "__main__" ' clause.
1292
1292
1293 -i: run the file in IPython's namespace instead of an empty one. This
1293 -i: run the file in IPython's namespace instead of an empty one. This
1294 is useful if you are experimenting with code written in a text editor
1294 is useful if you are experimenting with code written in a text editor
1295 which depends on variables defined interactively.
1295 which depends on variables defined interactively.
1296
1296
1297 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1297 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1298 being run. This is particularly useful if IPython is being used to
1298 being run. This is particularly useful if IPython is being used to
1299 run unittests, which always exit with a sys.exit() call. In such
1299 run unittests, which always exit with a sys.exit() call. In such
1300 cases you are interested in the output of the test results, not in
1300 cases you are interested in the output of the test results, not in
1301 seeing a traceback of the unittest module.
1301 seeing a traceback of the unittest module.
1302
1302
1303 -t: print timing information at the end of the run. IPython will give
1303 -t: print timing information at the end of the run. IPython will give
1304 you an estimated CPU time consumption for your script, which under
1304 you an estimated CPU time consumption for your script, which under
1305 Unix uses the resource module to avoid the wraparound problems of
1305 Unix uses the resource module to avoid the wraparound problems of
1306 time.clock(). Under Unix, an estimate of time spent on system tasks
1306 time.clock(). Under Unix, an estimate of time spent on system tasks
1307 is also given (for Windows platforms this is reported as 0.0).
1307 is also given (for Windows platforms this is reported as 0.0).
1308
1308
1309 If -t is given, an additional -N<N> option can be given, where <N>
1309 If -t is given, an additional -N<N> option can be given, where <N>
1310 must be an integer indicating how many times you want the script to
1310 must be an integer indicating how many times you want the script to
1311 run. The final timing report will include total and per run results.
1311 run. The final timing report will include total and per run results.
1312
1312
1313 For example (testing the script uniq_stable.py):
1313 For example (testing the script uniq_stable.py):
1314
1314
1315 In [1]: run -t uniq_stable
1315 In [1]: run -t uniq_stable
1316
1316
1317 IPython CPU timings (estimated):\\
1317 IPython CPU timings (estimated):\\
1318 User : 0.19597 s.\\
1318 User : 0.19597 s.\\
1319 System: 0.0 s.\\
1319 System: 0.0 s.\\
1320
1320
1321 In [2]: run -t -N5 uniq_stable
1321 In [2]: run -t -N5 uniq_stable
1322
1322
1323 IPython CPU timings (estimated):\\
1323 IPython CPU timings (estimated):\\
1324 Total runs performed: 5\\
1324 Total runs performed: 5\\
1325 Times : Total Per run\\
1325 Times : Total Per run\\
1326 User : 0.910862 s, 0.1821724 s.\\
1326 User : 0.910862 s, 0.1821724 s.\\
1327 System: 0.0 s, 0.0 s.
1327 System: 0.0 s, 0.0 s.
1328
1328
1329 -d: run your program under the control of pdb, the Python debugger.
1329 -d: run your program under the control of pdb, the Python debugger.
1330 This allows you to execute your program step by step, watch variables,
1330 This allows you to execute your program step by step, watch variables,
1331 etc. Internally, what IPython does is similar to calling:
1331 etc. Internally, what IPython does is similar to calling:
1332
1332
1333 pdb.run('execfile("YOURFILENAME")')
1333 pdb.run('execfile("YOURFILENAME")')
1334
1334
1335 with a breakpoint set on line 1 of your file. You can change the line
1335 with a breakpoint set on line 1 of your file. You can change the line
1336 number for this automatic breakpoint to be <N> by using the -bN option
1336 number for this automatic breakpoint to be <N> by using the -bN option
1337 (where N must be an integer). For example:
1337 (where N must be an integer). For example:
1338
1338
1339 %run -d -b40 myscript
1339 %run -d -b40 myscript
1340
1340
1341 will set the first breakpoint at line 40 in myscript.py. Note that
1341 will set the first breakpoint at line 40 in myscript.py. Note that
1342 the first breakpoint must be set on a line which actually does
1342 the first breakpoint must be set on a line which actually does
1343 something (not a comment or docstring) for it to stop execution.
1343 something (not a comment or docstring) for it to stop execution.
1344
1344
1345 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1345 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1346 first enter 'c' (without qoutes) to start execution up to the first
1346 first enter 'c' (without qoutes) to start execution up to the first
1347 breakpoint.
1347 breakpoint.
1348
1348
1349 Entering 'help' gives information about the use of the debugger. You
1349 Entering 'help' gives information about the use of the debugger. You
1350 can easily see pdb's full documentation with "import pdb;pdb.help()"
1350 can easily see pdb's full documentation with "import pdb;pdb.help()"
1351 at a prompt.
1351 at a prompt.
1352
1352
1353 -p: run program under the control of the Python profiler module (which
1353 -p: run program under the control of the Python profiler module (which
1354 prints a detailed report of execution times, function calls, etc).
1354 prints a detailed report of execution times, function calls, etc).
1355
1355
1356 You can pass other options after -p which affect the behavior of the
1356 You can pass other options after -p which affect the behavior of the
1357 profiler itself. See the docs for %prun for details.
1357 profiler itself. See the docs for %prun for details.
1358
1358
1359 In this mode, the program's variables do NOT propagate back to the
1359 In this mode, the program's variables do NOT propagate back to the
1360 IPython interactive namespace (because they remain in the namespace
1360 IPython interactive namespace (because they remain in the namespace
1361 where the profiler executes them).
1361 where the profiler executes them).
1362
1362
1363 Internally this triggers a call to %prun, see its documentation for
1363 Internally this triggers a call to %prun, see its documentation for
1364 details on the options available specifically for profiling."""
1364 details on the options available specifically for profiling."""
1365
1365
1366 # get arguments and set sys.argv for program to be run.
1366 # get arguments and set sys.argv for program to be run.
1367 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1367 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1368 mode='list',list_all=1)
1368 mode='list',list_all=1)
1369
1369
1370 try:
1370 try:
1371 filename = get_py_filename(arg_lst[0])
1371 filename = get_py_filename(arg_lst[0])
1372 except IndexError:
1372 except IndexError:
1373 warn('you must provide at least a filename.')
1373 warn('you must provide at least a filename.')
1374 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1374 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1375 return
1375 return
1376 except IOError,msg:
1376 except IOError,msg:
1377 error(msg)
1377 error(msg)
1378 return
1378 return
1379
1379
1380 # Control the response to exit() calls made by the script being run
1380 # Control the response to exit() calls made by the script being run
1381 exit_ignore = opts.has_key('e')
1381 exit_ignore = opts.has_key('e')
1382
1382
1383 # Make sure that the running script gets a proper sys.argv as if it
1383 # Make sure that the running script gets a proper sys.argv as if it
1384 # were run from a system shell.
1384 # were run from a system shell.
1385 save_argv = sys.argv # save it for later restoring
1385 save_argv = sys.argv # save it for later restoring
1386 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1386 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1387
1387
1388 if opts.has_key('i'):
1388 if opts.has_key('i'):
1389 prog_ns = self.shell.user_ns
1389 prog_ns = self.shell.user_ns
1390 __name__save = self.shell.user_ns['__name__']
1390 __name__save = self.shell.user_ns['__name__']
1391 prog_ns['__name__'] = '__main__'
1391 prog_ns['__name__'] = '__main__'
1392 else:
1392 else:
1393 if opts.has_key('n'):
1393 if opts.has_key('n'):
1394 name = os.path.splitext(os.path.basename(filename))[0]
1394 name = os.path.splitext(os.path.basename(filename))[0]
1395 else:
1395 else:
1396 name = '__main__'
1396 name = '__main__'
1397 prog_ns = {'__name__':name}
1397 prog_ns = {'__name__':name}
1398
1398
1399 # pickle fix. See iplib for an explanation. But we need to make sure
1399 # pickle fix. See iplib for an explanation. But we need to make sure
1400 # that, if we overwrite __main__, we replace it at the end
1400 # that, if we overwrite __main__, we replace it at the end
1401 if prog_ns['__name__'] == '__main__':
1401 if prog_ns['__name__'] == '__main__':
1402 restore_main = sys.modules['__main__']
1402 restore_main = sys.modules['__main__']
1403 else:
1403 else:
1404 restore_main = False
1404 restore_main = False
1405
1405
1406 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1406 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1407
1407
1408 stats = None
1408 stats = None
1409 try:
1409 try:
1410 if opts.has_key('p'):
1410 if opts.has_key('p'):
1411 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1411 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1412 else:
1412 else:
1413 if opts.has_key('d'):
1413 if opts.has_key('d'):
1414 deb = Debugger.Pdb(self.shell.rc.colors)
1414 deb = Debugger.Pdb(self.shell.rc.colors)
1415 # reset Breakpoint state, which is moronically kept
1415 # reset Breakpoint state, which is moronically kept
1416 # in a class
1416 # in a class
1417 bdb.Breakpoint.next = 1
1417 bdb.Breakpoint.next = 1
1418 bdb.Breakpoint.bplist = {}
1418 bdb.Breakpoint.bplist = {}
1419 bdb.Breakpoint.bpbynumber = [None]
1419 bdb.Breakpoint.bpbynumber = [None]
1420 # Set an initial breakpoint to stop execution
1420 # Set an initial breakpoint to stop execution
1421 maxtries = 10
1421 maxtries = 10
1422 bp = int(opts.get('b',[1])[0])
1422 bp = int(opts.get('b',[1])[0])
1423 checkline = deb.checkline(filename,bp)
1423 checkline = deb.checkline(filename,bp)
1424 if not checkline:
1424 if not checkline:
1425 for bp in range(bp+1,bp+maxtries+1):
1425 for bp in range(bp+1,bp+maxtries+1):
1426 if deb.checkline(filename,bp):
1426 if deb.checkline(filename,bp):
1427 break
1427 break
1428 else:
1428 else:
1429 msg = ("\nI failed to find a valid line to set "
1429 msg = ("\nI failed to find a valid line to set "
1430 "a breakpoint\n"
1430 "a breakpoint\n"
1431 "after trying up to line: %s.\n"
1431 "after trying up to line: %s.\n"
1432 "Please set a valid breakpoint manually "
1432 "Please set a valid breakpoint manually "
1433 "with the -b option." % bp)
1433 "with the -b option." % bp)
1434 error(msg)
1434 error(msg)
1435 return
1435 return
1436 # if we find a good linenumber, set the breakpoint
1436 # if we find a good linenumber, set the breakpoint
1437 deb.do_break('%s:%s' % (filename,bp))
1437 deb.do_break('%s:%s' % (filename,bp))
1438 # Start file run
1438 # Start file run
1439 print "NOTE: Enter 'c' at the",
1439 print "NOTE: Enter 'c' at the",
1440 print "ipdb> prompt to start your script."
1440 print "ipdb> prompt to start your script."
1441 try:
1441 try:
1442 deb.run('execfile("%s")' % filename,prog_ns)
1442 deb.run('execfile("%s")' % filename,prog_ns)
1443 except:
1443 except:
1444 etype, value, tb = sys.exc_info()
1444 etype, value, tb = sys.exc_info()
1445 # Skip three frames in the traceback: the %run one,
1445 # Skip three frames in the traceback: the %run one,
1446 # one inside bdb.py, and the command-line typed by the
1446 # one inside bdb.py, and the command-line typed by the
1447 # user (run by exec in pdb itself).
1447 # user (run by exec in pdb itself).
1448 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1448 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1449 else:
1449 else:
1450 if runner is None:
1450 if runner is None:
1451 runner = self.shell.safe_execfile
1451 runner = self.shell.safe_execfile
1452 if opts.has_key('t'):
1452 if opts.has_key('t'):
1453 try:
1453 try:
1454 nruns = int(opts['N'][0])
1454 nruns = int(opts['N'][0])
1455 if nruns < 1:
1455 if nruns < 1:
1456 error('Number of runs must be >=1')
1456 error('Number of runs must be >=1')
1457 return
1457 return
1458 except (KeyError):
1458 except (KeyError):
1459 nruns = 1
1459 nruns = 1
1460 if nruns == 1:
1460 if nruns == 1:
1461 t0 = clock2()
1461 t0 = clock2()
1462 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1462 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1463 t1 = clock2()
1463 t1 = clock2()
1464 t_usr = t1[0]-t0[0]
1464 t_usr = t1[0]-t0[0]
1465 t_sys = t1[1]-t1[1]
1465 t_sys = t1[1]-t1[1]
1466 print "\nIPython CPU timings (estimated):"
1466 print "\nIPython CPU timings (estimated):"
1467 print " User : %10s s." % t_usr
1467 print " User : %10s s." % t_usr
1468 print " System: %10s s." % t_sys
1468 print " System: %10s s." % t_sys
1469 else:
1469 else:
1470 runs = range(nruns)
1470 runs = range(nruns)
1471 t0 = clock2()
1471 t0 = clock2()
1472 for nr in runs:
1472 for nr in runs:
1473 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1473 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1474 t1 = clock2()
1474 t1 = clock2()
1475 t_usr = t1[0]-t0[0]
1475 t_usr = t1[0]-t0[0]
1476 t_sys = t1[1]-t1[1]
1476 t_sys = t1[1]-t1[1]
1477 print "\nIPython CPU timings (estimated):"
1477 print "\nIPython CPU timings (estimated):"
1478 print "Total runs performed:",nruns
1478 print "Total runs performed:",nruns
1479 print " Times : %10s %10s" % ('Total','Per run')
1479 print " Times : %10s %10s" % ('Total','Per run')
1480 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1480 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1481 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1481 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1482
1482
1483 else:
1483 else:
1484 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1484 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1485 if opts.has_key('i'):
1485 if opts.has_key('i'):
1486 self.shell.user_ns['__name__'] = __name__save
1486 self.shell.user_ns['__name__'] = __name__save
1487 else:
1487 else:
1488 # update IPython interactive namespace
1488 # update IPython interactive namespace
1489 del prog_ns['__name__']
1489 del prog_ns['__name__']
1490 self.shell.user_ns.update(prog_ns)
1490 self.shell.user_ns.update(prog_ns)
1491 finally:
1491 finally:
1492 sys.argv = save_argv
1492 sys.argv = save_argv
1493 if restore_main:
1493 if restore_main:
1494 sys.modules['__main__'] = restore_main
1494 sys.modules['__main__'] = restore_main
1495 return stats
1495 return stats
1496
1496
1497 def magic_runlog(self, parameter_s =''):
1497 def magic_runlog(self, parameter_s =''):
1498 """Run files as logs.
1498 """Run files as logs.
1499
1499
1500 Usage:\\
1500 Usage:\\
1501 %runlog file1 file2 ...
1501 %runlog file1 file2 ...
1502
1502
1503 Run the named files (treating them as log files) in sequence inside
1503 Run the named files (treating them as log files) in sequence inside
1504 the interpreter, and return to the prompt. This is much slower than
1504 the interpreter, and return to the prompt. This is much slower than
1505 %run because each line is executed in a try/except block, but it
1505 %run because each line is executed in a try/except block, but it
1506 allows running files with syntax errors in them.
1506 allows running files with syntax errors in them.
1507
1507
1508 Normally IPython will guess when a file is one of its own logfiles, so
1508 Normally IPython will guess when a file is one of its own logfiles, so
1509 you can typically use %run even for logs. This shorthand allows you to
1509 you can typically use %run even for logs. This shorthand allows you to
1510 force any file to be treated as a log file."""
1510 force any file to be treated as a log file."""
1511
1511
1512 for f in parameter_s.split():
1512 for f in parameter_s.split():
1513 self.shell.safe_execfile(f,self.shell.user_ns,
1513 self.shell.safe_execfile(f,self.shell.user_ns,
1514 self.shell.user_ns,islog=1)
1514 self.shell.user_ns,islog=1)
1515
1515
1516 def magic_time(self,parameter_s = ''):
1516 def magic_time(self,parameter_s = ''):
1517 """Time execution of a Python statement or expression.
1517 """Time execution of a Python statement or expression.
1518
1518
1519 The CPU and wall clock times are printed, and the value of the
1519 The CPU and wall clock times are printed, and the value of the
1520 expression (if any) is returned. Note that under Win32, system time
1520 expression (if any) is returned. Note that under Win32, system time
1521 is always reported as 0, since it can not be measured.
1521 is always reported as 0, since it can not be measured.
1522
1522
1523 This function provides very basic timing functionality. In Python
1523 This function provides very basic timing functionality. In Python
1524 2.3, the timeit module offers more control and sophistication, but for
1524 2.3, the timeit module offers more control and sophistication, but for
1525 now IPython supports Python 2.2, so we can not rely on timeit being
1525 now IPython supports Python 2.2, so we can not rely on timeit being
1526 present.
1526 present.
1527
1527
1528 Some examples:
1528 Some examples:
1529
1529
1530 In [1]: time 2**128
1530 In [1]: time 2**128
1531 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1531 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1532 Wall time: 0.00
1532 Wall time: 0.00
1533 Out[1]: 340282366920938463463374607431768211456L
1533 Out[1]: 340282366920938463463374607431768211456L
1534
1534
1535 In [2]: n = 1000000
1535 In [2]: n = 1000000
1536
1536
1537 In [3]: time sum(range(n))
1537 In [3]: time sum(range(n))
1538 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1538 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1539 Wall time: 1.37
1539 Wall time: 1.37
1540 Out[3]: 499999500000L
1540 Out[3]: 499999500000L
1541
1541
1542 In [4]: time print 'hello world'
1542 In [4]: time print 'hello world'
1543 hello world
1543 hello world
1544 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1544 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1545 Wall time: 0.00
1545 Wall time: 0.00
1546 """
1546 """
1547
1547
1548 # fail immediately if the given expression can't be compiled
1548 # fail immediately if the given expression can't be compiled
1549 try:
1549 try:
1550 mode = 'eval'
1550 mode = 'eval'
1551 code = compile(parameter_s,'<timed eval>',mode)
1551 code = compile(parameter_s,'<timed eval>',mode)
1552 except SyntaxError:
1552 except SyntaxError:
1553 mode = 'exec'
1553 mode = 'exec'
1554 code = compile(parameter_s,'<timed exec>',mode)
1554 code = compile(parameter_s,'<timed exec>',mode)
1555 # skew measurement as little as possible
1555 # skew measurement as little as possible
1556 glob = self.shell.user_ns
1556 glob = self.shell.user_ns
1557 clk = clock2
1557 clk = clock2
1558 wtime = time.time
1558 wtime = time.time
1559 # time execution
1559 # time execution
1560 wall_st = wtime()
1560 wall_st = wtime()
1561 if mode=='eval':
1561 if mode=='eval':
1562 st = clk()
1562 st = clk()
1563 out = eval(code,glob)
1563 out = eval(code,glob)
1564 end = clk()
1564 end = clk()
1565 else:
1565 else:
1566 st = clk()
1566 st = clk()
1567 exec code in glob
1567 exec code in glob
1568 end = clk()
1568 end = clk()
1569 out = None
1569 out = None
1570 wall_end = wtime()
1570 wall_end = wtime()
1571 # Compute actual times and report
1571 # Compute actual times and report
1572 wall_time = wall_end-wall_st
1572 wall_time = wall_end-wall_st
1573 cpu_user = end[0]-st[0]
1573 cpu_user = end[0]-st[0]
1574 cpu_sys = end[1]-st[1]
1574 cpu_sys = end[1]-st[1]
1575 cpu_tot = cpu_user+cpu_sys
1575 cpu_tot = cpu_user+cpu_sys
1576 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1576 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1577 (cpu_user,cpu_sys,cpu_tot)
1577 (cpu_user,cpu_sys,cpu_tot)
1578 print "Wall time: %.2f" % wall_time
1578 print "Wall time: %.2f" % wall_time
1579 return out
1579 return out
1580
1580
1581 def magic_macro(self,parameter_s = ''):
1581 def magic_macro(self,parameter_s = ''):
1582 """Define a set of input lines as a macro for future re-execution.
1582 """Define a set of input lines as a macro for future re-execution.
1583
1583
1584 Usage:\\
1584 Usage:\\
1585 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1585 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1586
1586
1587 This will define a global variable called `name` which is a string
1587 This will define a global variable called `name` which is a string
1588 made of joining the slices and lines you specify (n1,n2,... numbers
1588 made of joining the slices and lines you specify (n1,n2,... numbers
1589 above) from your input history into a single string. This variable
1589 above) from your input history into a single string. This variable
1590 acts like an automatic function which re-executes those lines as if
1590 acts like an automatic function which re-executes those lines as if
1591 you had typed them. You just type 'name' at the prompt and the code
1591 you had typed them. You just type 'name' at the prompt and the code
1592 executes.
1592 executes.
1593
1593
1594 The notation for indicating number ranges is: n1-n2 means 'use line
1594 The notation for indicating number ranges is: n1-n2 means 'use line
1595 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1595 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1596 using the lines numbered 5,6 and 7.
1596 using the lines numbered 5,6 and 7.
1597
1597
1598 Note: as a 'hidden' feature, you can also use traditional python slice
1598 Note: as a 'hidden' feature, you can also use traditional python slice
1599 notation, where N:M means numbers N through M-1.
1599 notation, where N:M means numbers N through M-1.
1600
1600
1601 For example, if your history contains (%hist prints it):
1601 For example, if your history contains (%hist prints it):
1602
1602
1603 44: x=1\\
1603 44: x=1\\
1604 45: y=3\\
1604 45: y=3\\
1605 46: z=x+y\\
1605 46: z=x+y\\
1606 47: print x\\
1606 47: print x\\
1607 48: a=5\\
1607 48: a=5\\
1608 49: print 'x',x,'y',y\\
1608 49: print 'x',x,'y',y\\
1609
1609
1610 you can create a macro with lines 44 through 47 (included) and line 49
1610 you can create a macro with lines 44 through 47 (included) and line 49
1611 called my_macro with:
1611 called my_macro with:
1612
1612
1613 In [51]: %macro my_macro 44-47 49
1613 In [51]: %macro my_macro 44-47 49
1614
1614
1615 Now, typing `my_macro` (without quotes) will re-execute all this code
1615 Now, typing `my_macro` (without quotes) will re-execute all this code
1616 in one pass.
1616 in one pass.
1617
1617
1618 You don't need to give the line-numbers in order, and any given line
1618 You don't need to give the line-numbers in order, and any given line
1619 number can appear multiple times. You can assemble macros with any
1619 number can appear multiple times. You can assemble macros with any
1620 lines from your input history in any order.
1620 lines from your input history in any order.
1621
1621
1622 The macro is a simple object which holds its value in an attribute,
1622 The macro is a simple object which holds its value in an attribute,
1623 but IPython's display system checks for macros and executes them as
1623 but IPython's display system checks for macros and executes them as
1624 code instead of printing them when you type their name.
1624 code instead of printing them when you type their name.
1625
1625
1626 You can view a macro's contents by explicitly printing it with:
1626 You can view a macro's contents by explicitly printing it with:
1627
1627
1628 'print macro_name'.
1628 'print macro_name'.
1629
1629
1630 For one-off cases which DON'T contain magic function calls in them you
1630 For one-off cases which DON'T contain magic function calls in them you
1631 can obtain similar results by explicitly executing slices from your
1631 can obtain similar results by explicitly executing slices from your
1632 input history with:
1632 input history with:
1633
1633
1634 In [60]: exec In[44:48]+In[49]"""
1634 In [60]: exec In[44:48]+In[49]"""
1635
1635
1636 args = parameter_s.split()
1636 args = parameter_s.split()
1637 name,ranges = args[0], args[1:]
1637 name,ranges = args[0], args[1:]
1638 #print 'rng',ranges # dbg
1638 #print 'rng',ranges # dbg
1639 lines = self.extract_input_slices(ranges)
1639 lines = self.extract_input_slices(ranges)
1640 macro = Macro(lines)
1640 macro = Macro(lines)
1641 self.shell.user_ns.update({name:macro})
1641 self.shell.user_ns.update({name:macro})
1642 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1642 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1643 print 'Macro contents:'
1643 print 'Macro contents:'
1644 print macro,
1644 print macro,
1645
1645
1646 def magic_save(self,parameter_s = ''):
1646 def magic_save(self,parameter_s = ''):
1647 """Save a set of lines to a given filename.
1647 """Save a set of lines to a given filename.
1648
1648
1649 Usage:\\
1649 Usage:\\
1650 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1650 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1651
1651
1652 This function uses the same syntax as %macro for line extraction, but
1652 This function uses the same syntax as %macro for line extraction, but
1653 instead of creating a macro it saves the resulting string to the
1653 instead of creating a macro it saves the resulting string to the
1654 filename you specify.
1654 filename you specify.
1655
1655
1656 It adds a '.py' extension to the file if you don't do so yourself, and
1656 It adds a '.py' extension to the file if you don't do so yourself, and
1657 it asks for confirmation before overwriting existing files."""
1657 it asks for confirmation before overwriting existing files."""
1658
1658
1659 args = parameter_s.split()
1659 args = parameter_s.split()
1660 fname,ranges = args[0], args[1:]
1660 fname,ranges = args[0], args[1:]
1661 if not fname.endswith('.py'):
1661 if not fname.endswith('.py'):
1662 fname += '.py'
1662 fname += '.py'
1663 if os.path.isfile(fname):
1663 if os.path.isfile(fname):
1664 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1664 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1665 if ans.lower() not in ['y','yes']:
1665 if ans.lower() not in ['y','yes']:
1666 print 'Operation cancelled.'
1666 print 'Operation cancelled.'
1667 return
1667 return
1668 cmds = ''.join(self.extract_input_slices(ranges))
1668 cmds = ''.join(self.extract_input_slices(ranges))
1669 f = file(fname,'w')
1669 f = file(fname,'w')
1670 f.write(cmds)
1670 f.write(cmds)
1671 f.close()
1671 f.close()
1672 print 'The following commands were written to file `%s`:' % fname
1672 print 'The following commands were written to file `%s`:' % fname
1673 print cmds
1673 print cmds
1674
1674
1675 def _edit_macro(self,mname,macro):
1675 def _edit_macro(self,mname,macro):
1676 """open an editor with the macro data in a file"""
1676 """open an editor with the macro data in a file"""
1677 filename = self.shell.mktempfile(macro.value)
1677 filename = self.shell.mktempfile(macro.value)
1678 self.shell.hooks.editor(filename)
1678 self.shell.hooks.editor(filename)
1679
1679
1680 # and make a new macro object, to replace the old one
1680 # and make a new macro object, to replace the old one
1681 mfile = open(filename)
1681 mfile = open(filename)
1682 mvalue = mfile.read()
1682 mvalue = mfile.read()
1683 mfile.close()
1683 mfile.close()
1684 self.shell.user_ns[mname] = Macro(mvalue)
1684 self.shell.user_ns[mname] = Macro(mvalue)
1685
1685
1686 def magic_ed(self,parameter_s=''):
1686 def magic_ed(self,parameter_s=''):
1687 """Alias to %edit."""
1687 """Alias to %edit."""
1688 return self.magic_edit(parameter_s)
1688 return self.magic_edit(parameter_s)
1689
1689
1690 def magic_edit(self,parameter_s='',last_call=['','']):
1690 def magic_edit(self,parameter_s='',last_call=['','']):
1691 """Bring up an editor and execute the resulting code.
1691 """Bring up an editor and execute the resulting code.
1692
1692
1693 Usage:
1693 Usage:
1694 %edit [options] [args]
1694 %edit [options] [args]
1695
1695
1696 %edit runs IPython's editor hook. The default version of this hook is
1696 %edit runs IPython's editor hook. The default version of this hook is
1697 set to call the __IPYTHON__.rc.editor command. This is read from your
1697 set to call the __IPYTHON__.rc.editor command. This is read from your
1698 environment variable $EDITOR. If this isn't found, it will default to
1698 environment variable $EDITOR. If this isn't found, it will default to
1699 vi under Linux/Unix and to notepad under Windows. See the end of this
1699 vi under Linux/Unix and to notepad under Windows. See the end of this
1700 docstring for how to change the editor hook.
1700 docstring for how to change the editor hook.
1701
1701
1702 You can also set the value of this editor via the command line option
1702 You can also set the value of this editor via the command line option
1703 '-editor' or in your ipythonrc file. This is useful if you wish to use
1703 '-editor' or in your ipythonrc file. This is useful if you wish to use
1704 specifically for IPython an editor different from your typical default
1704 specifically for IPython an editor different from your typical default
1705 (and for Windows users who typically don't set environment variables).
1705 (and for Windows users who typically don't set environment variables).
1706
1706
1707 This command allows you to conveniently edit multi-line code right in
1707 This command allows you to conveniently edit multi-line code right in
1708 your IPython session.
1708 your IPython session.
1709
1709
1710 If called without arguments, %edit opens up an empty editor with a
1710 If called without arguments, %edit opens up an empty editor with a
1711 temporary file and will execute the contents of this file when you
1711 temporary file and will execute the contents of this file when you
1712 close it (don't forget to save it!).
1712 close it (don't forget to save it!).
1713
1713
1714
1714
1715 Options:
1715 Options:
1716
1716
1717 -p: this will call the editor with the same data as the previous time
1717 -p: this will call the editor with the same data as the previous time
1718 it was used, regardless of how long ago (in your current session) it
1718 it was used, regardless of how long ago (in your current session) it
1719 was.
1719 was.
1720
1720
1721 -x: do not execute the edited code immediately upon exit. This is
1721 -x: do not execute the edited code immediately upon exit. This is
1722 mainly useful if you are editing programs which need to be called with
1722 mainly useful if you are editing programs which need to be called with
1723 command line arguments, which you can then do using %run.
1723 command line arguments, which you can then do using %run.
1724
1724
1725
1725
1726 Arguments:
1726 Arguments:
1727
1727
1728 If arguments are given, the following possibilites exist:
1728 If arguments are given, the following possibilites exist:
1729
1729
1730 - The arguments are numbers or pairs of colon-separated numbers (like
1730 - The arguments are numbers or pairs of colon-separated numbers (like
1731 1 4:8 9). These are interpreted as lines of previous input to be
1731 1 4:8 9). These are interpreted as lines of previous input to be
1732 loaded into the editor. The syntax is the same of the %macro command.
1732 loaded into the editor. The syntax is the same of the %macro command.
1733
1733
1734 - If the argument doesn't start with a number, it is evaluated as a
1734 - If the argument doesn't start with a number, it is evaluated as a
1735 variable and its contents loaded into the editor. You can thus edit
1735 variable and its contents loaded into the editor. You can thus edit
1736 any string which contains python code (including the result of
1736 any string which contains python code (including the result of
1737 previous edits).
1737 previous edits).
1738
1738
1739 - If the argument is the name of an object (other than a string),
1739 - If the argument is the name of an object (other than a string),
1740 IPython will try to locate the file where it was defined and open the
1740 IPython will try to locate the file where it was defined and open the
1741 editor at the point where it is defined. You can use `%edit function`
1741 editor at the point where it is defined. You can use `%edit function`
1742 to load an editor exactly at the point where 'function' is defined,
1742 to load an editor exactly at the point where 'function' is defined,
1743 edit it and have the file be executed automatically.
1743 edit it and have the file be executed automatically.
1744
1744
1745 If the object is a macro (see %macro for details), this opens up your
1745 If the object is a macro (see %macro for details), this opens up your
1746 specified editor with a temporary file containing the macro's data.
1746 specified editor with a temporary file containing the macro's data.
1747 Upon exit, the macro is reloaded with the contents of the file.
1747 Upon exit, the macro is reloaded with the contents of the file.
1748
1748
1749 Note: opening at an exact line is only supported under Unix, and some
1749 Note: opening at an exact line is only supported under Unix, and some
1750 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1750 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1751 '+NUMBER' parameter necessary for this feature. Good editors like
1751 '+NUMBER' parameter necessary for this feature. Good editors like
1752 (X)Emacs, vi, jed, pico and joe all do.
1752 (X)Emacs, vi, jed, pico and joe all do.
1753
1753
1754 - If the argument is not found as a variable, IPython will look for a
1754 - If the argument is not found as a variable, IPython will look for a
1755 file with that name (adding .py if necessary) and load it into the
1755 file with that name (adding .py if necessary) and load it into the
1756 editor. It will execute its contents with execfile() when you exit,
1756 editor. It will execute its contents with execfile() when you exit,
1757 loading any code in the file into your interactive namespace.
1757 loading any code in the file into your interactive namespace.
1758
1758
1759 After executing your code, %edit will return as output the code you
1759 After executing your code, %edit will return as output the code you
1760 typed in the editor (except when it was an existing file). This way
1760 typed in the editor (except when it was an existing file). This way
1761 you can reload the code in further invocations of %edit as a variable,
1761 you can reload the code in further invocations of %edit as a variable,
1762 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1762 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1763 the output.
1763 the output.
1764
1764
1765 Note that %edit is also available through the alias %ed.
1765 Note that %edit is also available through the alias %ed.
1766
1766
1767 This is an example of creating a simple function inside the editor and
1767 This is an example of creating a simple function inside the editor and
1768 then modifying it. First, start up the editor:
1768 then modifying it. First, start up the editor:
1769
1769
1770 In [1]: ed\\
1770 In [1]: ed\\
1771 Editing... done. Executing edited code...\\
1771 Editing... done. Executing edited code...\\
1772 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1772 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1773
1773
1774 We can then call the function foo():
1774 We can then call the function foo():
1775
1775
1776 In [2]: foo()\\
1776 In [2]: foo()\\
1777 foo() was defined in an editing session
1777 foo() was defined in an editing session
1778
1778
1779 Now we edit foo. IPython automatically loads the editor with the
1779 Now we edit foo. IPython automatically loads the editor with the
1780 (temporary) file where foo() was previously defined:
1780 (temporary) file where foo() was previously defined:
1781
1781
1782 In [3]: ed foo\\
1782 In [3]: ed foo\\
1783 Editing... done. Executing edited code...
1783 Editing... done. Executing edited code...
1784
1784
1785 And if we call foo() again we get the modified version:
1785 And if we call foo() again we get the modified version:
1786
1786
1787 In [4]: foo()\\
1787 In [4]: foo()\\
1788 foo() has now been changed!
1788 foo() has now been changed!
1789
1789
1790 Here is an example of how to edit a code snippet successive
1790 Here is an example of how to edit a code snippet successive
1791 times. First we call the editor:
1791 times. First we call the editor:
1792
1792
1793 In [8]: ed\\
1793 In [8]: ed\\
1794 Editing... done. Executing edited code...\\
1794 Editing... done. Executing edited code...\\
1795 hello\\
1795 hello\\
1796 Out[8]: "print 'hello'\\n"
1796 Out[8]: "print 'hello'\\n"
1797
1797
1798 Now we call it again with the previous output (stored in _):
1798 Now we call it again with the previous output (stored in _):
1799
1799
1800 In [9]: ed _\\
1800 In [9]: ed _\\
1801 Editing... done. Executing edited code...\\
1801 Editing... done. Executing edited code...\\
1802 hello world\\
1802 hello world\\
1803 Out[9]: "print 'hello world'\\n"
1803 Out[9]: "print 'hello world'\\n"
1804
1804
1805 Now we call it with the output #8 (stored in _8, also as Out[8]):
1805 Now we call it with the output #8 (stored in _8, also as Out[8]):
1806
1806
1807 In [10]: ed _8\\
1807 In [10]: ed _8\\
1808 Editing... done. Executing edited code...\\
1808 Editing... done. Executing edited code...\\
1809 hello again\\
1809 hello again\\
1810 Out[10]: "print 'hello again'\\n"
1810 Out[10]: "print 'hello again'\\n"
1811
1811
1812
1812
1813 Changing the default editor hook:
1813 Changing the default editor hook:
1814
1814
1815 If you wish to write your own editor hook, you can put it in a
1815 If you wish to write your own editor hook, you can put it in a
1816 configuration file which you load at startup time. The default hook
1816 configuration file which you load at startup time. The default hook
1817 is defined in the IPython.hooks module, and you can use that as a
1817 is defined in the IPython.hooks module, and you can use that as a
1818 starting example for further modifications. That file also has
1818 starting example for further modifications. That file also has
1819 general instructions on how to set a new hook for use once you've
1819 general instructions on how to set a new hook for use once you've
1820 defined it."""
1820 defined it."""
1821
1821
1822 # FIXME: This function has become a convoluted mess. It needs a
1822 # FIXME: This function has become a convoluted mess. It needs a
1823 # ground-up rewrite with clean, simple logic.
1823 # ground-up rewrite with clean, simple logic.
1824
1824
1825 def make_filename(arg):
1825 def make_filename(arg):
1826 "Make a filename from the given args"
1826 "Make a filename from the given args"
1827 try:
1827 try:
1828 filename = get_py_filename(arg)
1828 filename = get_py_filename(arg)
1829 except IOError:
1829 except IOError:
1830 if args.endswith('.py'):
1830 if args.endswith('.py'):
1831 filename = arg
1831 filename = arg
1832 else:
1832 else:
1833 filename = None
1833 filename = None
1834 return filename
1834 return filename
1835
1835
1836 # custom exceptions
1836 # custom exceptions
1837 class DataIsObject(Exception): pass
1837 class DataIsObject(Exception): pass
1838
1838
1839 opts,args = self.parse_options(parameter_s,'px')
1839 opts,args = self.parse_options(parameter_s,'px')
1840
1840
1841 # Default line number value
1841 # Default line number value
1842 lineno = None
1842 lineno = None
1843 if opts.has_key('p'):
1843 if opts.has_key('p'):
1844 args = '_%s' % last_call[0]
1844 args = '_%s' % last_call[0]
1845 if not self.shell.user_ns.has_key(args):
1845 if not self.shell.user_ns.has_key(args):
1846 args = last_call[1]
1846 args = last_call[1]
1847
1847
1848 # use last_call to remember the state of the previous call, but don't
1848 # use last_call to remember the state of the previous call, but don't
1849 # let it be clobbered by successive '-p' calls.
1849 # let it be clobbered by successive '-p' calls.
1850 try:
1850 try:
1851 last_call[0] = self.shell.outputcache.prompt_count
1851 last_call[0] = self.shell.outputcache.prompt_count
1852 if not opts.has_key('p'):
1852 if not opts.has_key('p'):
1853 last_call[1] = parameter_s
1853 last_call[1] = parameter_s
1854 except:
1854 except:
1855 pass
1855 pass
1856
1856
1857 # by default this is done with temp files, except when the given
1857 # by default this is done with temp files, except when the given
1858 # arg is a filename
1858 # arg is a filename
1859 use_temp = 1
1859 use_temp = 1
1860
1860
1861 if re.match(r'\d',args):
1861 if re.match(r'\d',args):
1862 # Mode where user specifies ranges of lines, like in %macro.
1862 # Mode where user specifies ranges of lines, like in %macro.
1863 # This means that you can't edit files whose names begin with
1863 # This means that you can't edit files whose names begin with
1864 # numbers this way. Tough.
1864 # numbers this way. Tough.
1865 ranges = args.split()
1865 ranges = args.split()
1866 data = ''.join(self.extract_input_slices(ranges))
1866 data = ''.join(self.extract_input_slices(ranges))
1867 elif args.endswith('.py'):
1867 elif args.endswith('.py'):
1868 filename = make_filename(args)
1868 filename = make_filename(args)
1869 data = ''
1869 data = ''
1870 use_temp = 0
1870 use_temp = 0
1871 elif args:
1871 elif args:
1872 try:
1872 try:
1873 # Load the parameter given as a variable. If not a string,
1873 # Load the parameter given as a variable. If not a string,
1874 # process it as an object instead (below)
1874 # process it as an object instead (below)
1875
1875
1876 #print '*** args',args,'type',type(args) # dbg
1876 #print '*** args',args,'type',type(args) # dbg
1877 data = eval(args,self.shell.user_ns)
1877 data = eval(args,self.shell.user_ns)
1878 if not type(data) in StringTypes:
1878 if not type(data) in StringTypes:
1879 raise DataIsObject
1879 raise DataIsObject
1880
1880
1881 except (NameError,SyntaxError):
1881 except (NameError,SyntaxError):
1882 # given argument is not a variable, try as a filename
1882 # given argument is not a variable, try as a filename
1883 filename = make_filename(args)
1883 filename = make_filename(args)
1884 if filename is None:
1884 if filename is None:
1885 warn("Argument given (%s) can't be found as a variable "
1885 warn("Argument given (%s) can't be found as a variable "
1886 "or as a filename." % args)
1886 "or as a filename." % args)
1887 return
1887 return
1888
1888
1889 data = ''
1889 data = ''
1890 use_temp = 0
1890 use_temp = 0
1891 except DataIsObject:
1891 except DataIsObject:
1892
1892
1893 # macros have a special edit function
1893 # macros have a special edit function
1894 if isinstance(data,Macro):
1894 if isinstance(data,Macro):
1895 self._edit_macro(args,data)
1895 self._edit_macro(args,data)
1896 return
1896 return
1897
1897
1898 # For objects, try to edit the file where they are defined
1898 # For objects, try to edit the file where they are defined
1899 try:
1899 try:
1900 filename = inspect.getabsfile(data)
1900 filename = inspect.getabsfile(data)
1901 datafile = 1
1901 datafile = 1
1902 except TypeError:
1902 except TypeError:
1903 filename = make_filename(args)
1903 filename = make_filename(args)
1904 datafile = 1
1904 datafile = 1
1905 warn('Could not find file where `%s` is defined.\n'
1905 warn('Could not find file where `%s` is defined.\n'
1906 'Opening a file named `%s`' % (args,filename))
1906 'Opening a file named `%s`' % (args,filename))
1907 # Now, make sure we can actually read the source (if it was in
1907 # Now, make sure we can actually read the source (if it was in
1908 # a temp file it's gone by now).
1908 # a temp file it's gone by now).
1909 if datafile:
1909 if datafile:
1910 try:
1910 try:
1911 lineno = inspect.getsourcelines(data)[1]
1911 lineno = inspect.getsourcelines(data)[1]
1912 except IOError:
1912 except IOError:
1913 filename = make_filename(args)
1913 filename = make_filename(args)
1914 if filename is None:
1914 if filename is None:
1915 warn('The file `%s` where `%s` was defined cannot '
1915 warn('The file `%s` where `%s` was defined cannot '
1916 'be read.' % (filename,data))
1916 'be read.' % (filename,data))
1917 return
1917 return
1918 use_temp = 0
1918 use_temp = 0
1919 else:
1919 else:
1920 data = ''
1920 data = ''
1921
1921
1922 if use_temp:
1922 if use_temp:
1923 filename = self.shell.mktempfile(data)
1923 filename = self.shell.mktempfile(data)
1924 print 'IPython will make a temporary file named:',filename
1924 print 'IPython will make a temporary file named:',filename
1925
1925
1926 # do actual editing here
1926 # do actual editing here
1927 print 'Editing...',
1927 print 'Editing...',
1928 sys.stdout.flush()
1928 sys.stdout.flush()
1929 self.shell.hooks.editor(filename,lineno)
1929 self.shell.hooks.editor(filename,lineno)
1930 if opts.has_key('x'): # -x prevents actual execution
1930 if opts.has_key('x'): # -x prevents actual execution
1931 print
1931 print
1932 else:
1932 else:
1933 print 'done. Executing edited code...'
1933 print 'done. Executing edited code...'
1934 try:
1934 try:
1935 self.shell.safe_execfile(filename,self.shell.user_ns)
1935 self.shell.safe_execfile(filename,self.shell.user_ns)
1936 except IOError,msg:
1936 except IOError,msg:
1937 if msg.filename == filename:
1937 if msg.filename == filename:
1938 warn('File not found. Did you forget to save?')
1938 warn('File not found. Did you forget to save?')
1939 return
1939 return
1940 else:
1940 else:
1941 self.shell.showtraceback()
1941 self.shell.showtraceback()
1942 except:
1942 except:
1943 self.shell.showtraceback()
1943 self.shell.showtraceback()
1944
1944
1945 def magic_xmode(self,parameter_s = ''):
1945 def magic_xmode(self,parameter_s = ''):
1946 """Switch modes for the exception handlers.
1946 """Switch modes for the exception handlers.
1947
1947
1948 Valid modes: Plain, Context and Verbose.
1948 Valid modes: Plain, Context and Verbose.
1949
1949
1950 If called without arguments, acts as a toggle."""
1950 If called without arguments, acts as a toggle."""
1951
1951
1952 def xmode_switch_err(name):
1952 def xmode_switch_err(name):
1953 warn('Error changing %s exception modes.\n%s' %
1953 warn('Error changing %s exception modes.\n%s' %
1954 (name,sys.exc_info()[1]))
1954 (name,sys.exc_info()[1]))
1955
1955
1956 shell = self.shell
1956 shell = self.shell
1957 new_mode = parameter_s.strip().capitalize()
1957 new_mode = parameter_s.strip().capitalize()
1958 try:
1958 try:
1959 shell.InteractiveTB.set_mode(mode=new_mode)
1959 shell.InteractiveTB.set_mode(mode=new_mode)
1960 print 'Exception reporting mode:',shell.InteractiveTB.mode
1960 print 'Exception reporting mode:',shell.InteractiveTB.mode
1961 except:
1961 except:
1962 xmode_switch_err('user')
1962 xmode_switch_err('user')
1963
1963
1964 # threaded shells use a special handler in sys.excepthook
1964 # threaded shells use a special handler in sys.excepthook
1965 if shell.isthreaded:
1965 if shell.isthreaded:
1966 try:
1966 try:
1967 shell.sys_excepthook.set_mode(mode=new_mode)
1967 shell.sys_excepthook.set_mode(mode=new_mode)
1968 except:
1968 except:
1969 xmode_switch_err('threaded')
1969 xmode_switch_err('threaded')
1970
1970
1971 def magic_colors(self,parameter_s = ''):
1971 def magic_colors(self,parameter_s = ''):
1972 """Switch color scheme for prompts, info system and exception handlers.
1972 """Switch color scheme for prompts, info system and exception handlers.
1973
1973
1974 Currently implemented schemes: NoColor, Linux, LightBG.
1974 Currently implemented schemes: NoColor, Linux, LightBG.
1975
1975
1976 Color scheme names are not case-sensitive."""
1976 Color scheme names are not case-sensitive."""
1977
1977
1978 def color_switch_err(name):
1978 def color_switch_err(name):
1979 warn('Error changing %s color schemes.\n%s' %
1979 warn('Error changing %s color schemes.\n%s' %
1980 (name,sys.exc_info()[1]))
1980 (name,sys.exc_info()[1]))
1981
1981
1982
1982
1983 new_scheme = parameter_s.strip()
1983 new_scheme = parameter_s.strip()
1984 if not new_scheme:
1984 if not new_scheme:
1985 print 'You must specify a color scheme.'
1985 print 'You must specify a color scheme.'
1986 return
1986 return
1987 # Under Windows, check for Gary Bishop's readline, which is necessary
1987 # Under Windows, check for Gary Bishop's readline, which is necessary
1988 # for ANSI coloring
1988 # for ANSI coloring
1989 if os.name in ['nt','dos']:
1989 if os.name in ['nt','dos']:
1990 try:
1990 try:
1991 import readline
1991 import readline
1992 except ImportError:
1992 except ImportError:
1993 has_readline = 0
1993 has_readline = 0
1994 else:
1994 else:
1995 try:
1995 try:
1996 readline.GetOutputFile()
1996 readline.GetOutputFile()
1997 except AttributeError:
1997 except AttributeError:
1998 has_readline = 0
1998 has_readline = 0
1999 else:
1999 else:
2000 has_readline = 1
2000 has_readline = 1
2001 if not has_readline:
2001 if not has_readline:
2002 msg = """\
2002 msg = """\
2003 Proper color support under MS Windows requires Gary Bishop's readline library.
2003 Proper color support under MS Windows requires Gary Bishop's readline library.
2004 You can find it at:
2004 You can find it at:
2005 http://sourceforge.net/projects/uncpythontools
2005 http://sourceforge.net/projects/uncpythontools
2006 Gary's readline needs the ctypes module, from:
2006 Gary's readline needs the ctypes module, from:
2007 http://starship.python.net/crew/theller/ctypes
2007 http://starship.python.net/crew/theller/ctypes
2008
2008
2009 Defaulting color scheme to 'NoColor'"""
2009 Defaulting color scheme to 'NoColor'"""
2010 new_scheme = 'NoColor'
2010 new_scheme = 'NoColor'
2011 warn(msg)
2011 warn(msg)
2012 # local shortcut
2012 # local shortcut
2013 shell = self.shell
2013 shell = self.shell
2014
2014
2015 # Set prompt colors
2015 # Set prompt colors
2016 try:
2016 try:
2017 shell.outputcache.set_colors(new_scheme)
2017 shell.outputcache.set_colors(new_scheme)
2018 except:
2018 except:
2019 color_switch_err('prompt')
2019 color_switch_err('prompt')
2020 else:
2020 else:
2021 shell.rc.colors = \
2021 shell.rc.colors = \
2022 shell.outputcache.color_table.active_scheme_name
2022 shell.outputcache.color_table.active_scheme_name
2023 # Set exception colors
2023 # Set exception colors
2024 try:
2024 try:
2025 shell.InteractiveTB.set_colors(scheme = new_scheme)
2025 shell.InteractiveTB.set_colors(scheme = new_scheme)
2026 shell.SyntaxTB.set_colors(scheme = new_scheme)
2026 shell.SyntaxTB.set_colors(scheme = new_scheme)
2027 except:
2027 except:
2028 color_switch_err('exception')
2028 color_switch_err('exception')
2029
2029
2030 # threaded shells use a verbose traceback in sys.excepthook
2030 # threaded shells use a verbose traceback in sys.excepthook
2031 if shell.isthreaded:
2031 if shell.isthreaded:
2032 try:
2032 try:
2033 shell.sys_excepthook.set_colors(scheme=new_scheme)
2033 shell.sys_excepthook.set_colors(scheme=new_scheme)
2034 except:
2034 except:
2035 color_switch_err('system exception handler')
2035 color_switch_err('system exception handler')
2036
2036
2037 # Set info (for 'object?') colors
2037 # Set info (for 'object?') colors
2038 if shell.rc.color_info:
2038 if shell.rc.color_info:
2039 try:
2039 try:
2040 shell.inspector.set_active_scheme(new_scheme)
2040 shell.inspector.set_active_scheme(new_scheme)
2041 except:
2041 except:
2042 color_switch_err('object inspector')
2042 color_switch_err('object inspector')
2043 else:
2043 else:
2044 shell.inspector.set_active_scheme('NoColor')
2044 shell.inspector.set_active_scheme('NoColor')
2045
2045
2046 def magic_color_info(self,parameter_s = ''):
2046 def magic_color_info(self,parameter_s = ''):
2047 """Toggle color_info.
2047 """Toggle color_info.
2048
2048
2049 The color_info configuration parameter controls whether colors are
2049 The color_info configuration parameter controls whether colors are
2050 used for displaying object details (by things like %psource, %pfile or
2050 used for displaying object details (by things like %psource, %pfile or
2051 the '?' system). This function toggles this value with each call.
2051 the '?' system). This function toggles this value with each call.
2052
2052
2053 Note that unless you have a fairly recent pager (less works better
2053 Note that unless you have a fairly recent pager (less works better
2054 than more) in your system, using colored object information displays
2054 than more) in your system, using colored object information displays
2055 will not work properly. Test it and see."""
2055 will not work properly. Test it and see."""
2056
2056
2057 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2057 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2058 self.magic_colors(self.shell.rc.colors)
2058 self.magic_colors(self.shell.rc.colors)
2059 print 'Object introspection functions have now coloring:',
2059 print 'Object introspection functions have now coloring:',
2060 print ['OFF','ON'][self.shell.rc.color_info]
2060 print ['OFF','ON'][self.shell.rc.color_info]
2061
2061
2062 def magic_Pprint(self, parameter_s=''):
2062 def magic_Pprint(self, parameter_s=''):
2063 """Toggle pretty printing on/off."""
2063 """Toggle pretty printing on/off."""
2064
2064
2065 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2065 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2066 print 'Pretty printing has been turned', \
2066 print 'Pretty printing has been turned', \
2067 ['OFF','ON'][self.shell.outputcache.Pprint]
2067 ['OFF','ON'][self.shell.outputcache.Pprint]
2068
2068
2069 def magic_exit(self, parameter_s=''):
2069 def magic_exit(self, parameter_s=''):
2070 """Exit IPython, confirming if configured to do so.
2070 """Exit IPython, confirming if configured to do so.
2071
2071
2072 You can configure whether IPython asks for confirmation upon exit by
2072 You can configure whether IPython asks for confirmation upon exit by
2073 setting the confirm_exit flag in the ipythonrc file."""
2073 setting the confirm_exit flag in the ipythonrc file."""
2074
2074
2075 self.shell.exit()
2075 self.shell.exit()
2076
2076
2077 def magic_quit(self, parameter_s=''):
2077 def magic_quit(self, parameter_s=''):
2078 """Exit IPython, confirming if configured to do so (like %exit)"""
2078 """Exit IPython, confirming if configured to do so (like %exit)"""
2079
2079
2080 self.shell.exit()
2080 self.shell.exit()
2081
2081
2082 def magic_Exit(self, parameter_s=''):
2082 def magic_Exit(self, parameter_s=''):
2083 """Exit IPython without confirmation."""
2083 """Exit IPython without confirmation."""
2084
2084
2085 self.shell.exit_now = True
2085 self.shell.exit_now = True
2086
2086
2087 def magic_Quit(self, parameter_s=''):
2087 def magic_Quit(self, parameter_s=''):
2088 """Exit IPython without confirmation (like %Exit)."""
2088 """Exit IPython without confirmation (like %Exit)."""
2089
2089
2090 self.shell.exit_now = True
2090 self.shell.exit_now = True
2091
2091
2092 #......................................................................
2092 #......................................................................
2093 # Functions to implement unix shell-type things
2093 # Functions to implement unix shell-type things
2094
2094
2095 def magic_alias(self, parameter_s = ''):
2095 def magic_alias(self, parameter_s = ''):
2096 """Define an alias for a system command.
2096 """Define an alias for a system command.
2097
2097
2098 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2098 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2099
2099
2100 Then, typing 'alias_name params' will execute the system command 'cmd
2100 Then, typing 'alias_name params' will execute the system command 'cmd
2101 params' (from your underlying operating system).
2101 params' (from your underlying operating system).
2102
2102
2103 Aliases have lower precedence than magic functions and Python normal
2103 Aliases have lower precedence than magic functions and Python normal
2104 variables, so if 'foo' is both a Python variable and an alias, the
2104 variables, so if 'foo' is both a Python variable and an alias, the
2105 alias can not be executed until 'del foo' removes the Python variable.
2105 alias can not be executed until 'del foo' removes the Python variable.
2106
2106
2107 You can use the %l specifier in an alias definition to represent the
2107 You can use the %l specifier in an alias definition to represent the
2108 whole line when the alias is called. For example:
2108 whole line when the alias is called. For example:
2109
2109
2110 In [2]: alias all echo "Input in brackets: <%l>"\\
2110 In [2]: alias all echo "Input in brackets: <%l>"\\
2111 In [3]: all hello world\\
2111 In [3]: all hello world\\
2112 Input in brackets: <hello world>
2112 Input in brackets: <hello world>
2113
2113
2114 You can also define aliases with parameters using %s specifiers (one
2114 You can also define aliases with parameters using %s specifiers (one
2115 per parameter):
2115 per parameter):
2116
2116
2117 In [1]: alias parts echo first %s second %s\\
2117 In [1]: alias parts echo first %s second %s\\
2118 In [2]: %parts A B\\
2118 In [2]: %parts A B\\
2119 first A second B\\
2119 first A second B\\
2120 In [3]: %parts A\\
2120 In [3]: %parts A\\
2121 Incorrect number of arguments: 2 expected.\\
2121 Incorrect number of arguments: 2 expected.\\
2122 parts is an alias to: 'echo first %s second %s'
2122 parts is an alias to: 'echo first %s second %s'
2123
2123
2124 Note that %l and %s are mutually exclusive. You can only use one or
2124 Note that %l and %s are mutually exclusive. You can only use one or
2125 the other in your aliases.
2125 the other in your aliases.
2126
2126
2127 Aliases expand Python variables just like system calls using ! or !!
2127 Aliases expand Python variables just like system calls using ! or !!
2128 do: all expressions prefixed with '$' get expanded. For details of
2128 do: all expressions prefixed with '$' get expanded. For details of
2129 the semantic rules, see PEP-215:
2129 the semantic rules, see PEP-215:
2130 http://www.python.org/peps/pep-0215.html. This is the library used by
2130 http://www.python.org/peps/pep-0215.html. This is the library used by
2131 IPython for variable expansion. If you want to access a true shell
2131 IPython for variable expansion. If you want to access a true shell
2132 variable, an extra $ is necessary to prevent its expansion by IPython:
2132 variable, an extra $ is necessary to prevent its expansion by IPython:
2133
2133
2134 In [6]: alias show echo\\
2134 In [6]: alias show echo\\
2135 In [7]: PATH='A Python string'\\
2135 In [7]: PATH='A Python string'\\
2136 In [8]: show $PATH\\
2136 In [8]: show $PATH\\
2137 A Python string\\
2137 A Python string\\
2138 In [9]: show $$PATH\\
2138 In [9]: show $$PATH\\
2139 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2139 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2140
2140
2141 You can use the alias facility to acess all of $PATH. See the %rehash
2141 You can use the alias facility to acess all of $PATH. See the %rehash
2142 and %rehashx functions, which automatically create aliases for the
2142 and %rehashx functions, which automatically create aliases for the
2143 contents of your $PATH.
2143 contents of your $PATH.
2144
2144
2145 If called with no parameters, %alias prints the current alias table."""
2145 If called with no parameters, %alias prints the current alias table."""
2146
2146
2147 par = parameter_s.strip()
2147 par = parameter_s.strip()
2148 if not par:
2148 if not par:
2149 if self.shell.rc.automagic:
2149 if self.shell.rc.automagic:
2150 prechar = ''
2150 prechar = ''
2151 else:
2151 else:
2152 prechar = self.shell.ESC_MAGIC
2152 prechar = self.shell.ESC_MAGIC
2153 print 'Alias\t\tSystem Command\n'+'-'*30
2153 print 'Alias\t\tSystem Command\n'+'-'*30
2154 atab = self.shell.alias_table
2154 atab = self.shell.alias_table
2155 aliases = atab.keys()
2155 aliases = atab.keys()
2156 aliases.sort()
2156 aliases.sort()
2157 for alias in aliases:
2157 for alias in aliases:
2158 print prechar+alias+'\t\t'+atab[alias][1]
2158 print prechar+alias+'\t\t'+atab[alias][1]
2159 print '-'*30+'\nTotal number of aliases:',len(aliases)
2159 print '-'*30+'\nTotal number of aliases:',len(aliases)
2160 return
2160 return
2161 try:
2161 try:
2162 alias,cmd = par.split(None,1)
2162 alias,cmd = par.split(None,1)
2163 except:
2163 except:
2164 print OInspect.getdoc(self.magic_alias)
2164 print OInspect.getdoc(self.magic_alias)
2165 else:
2165 else:
2166 nargs = cmd.count('%s')
2166 nargs = cmd.count('%s')
2167 if nargs>0 and cmd.find('%l')>=0:
2167 if nargs>0 and cmd.find('%l')>=0:
2168 error('The %s and %l specifiers are mutually exclusive '
2168 error('The %s and %l specifiers are mutually exclusive '
2169 'in alias definitions.')
2169 'in alias definitions.')
2170 else: # all looks OK
2170 else: # all looks OK
2171 self.shell.alias_table[alias] = (nargs,cmd)
2171 self.shell.alias_table[alias] = (nargs,cmd)
2172 self.shell.alias_table_validate(verbose=1)
2172 self.shell.alias_table_validate(verbose=1)
2173 # end magic_alias
2173 # end magic_alias
2174
2174
2175 def magic_unalias(self, parameter_s = ''):
2175 def magic_unalias(self, parameter_s = ''):
2176 """Remove an alias"""
2176 """Remove an alias"""
2177
2177
2178 aname = parameter_s.strip()
2178 aname = parameter_s.strip()
2179 if aname in self.shell.alias_table:
2179 if aname in self.shell.alias_table:
2180 del self.shell.alias_table[aname]
2180 del self.shell.alias_table[aname]
2181
2181
2182 def magic_rehash(self, parameter_s = ''):
2182 def magic_rehash(self, parameter_s = ''):
2183 """Update the alias table with all entries in $PATH.
2183 """Update the alias table with all entries in $PATH.
2184
2184
2185 This version does no checks on execute permissions or whether the
2185 This version does no checks on execute permissions or whether the
2186 contents of $PATH are truly files (instead of directories or something
2186 contents of $PATH are truly files (instead of directories or something
2187 else). For such a safer (but slower) version, use %rehashx."""
2187 else). For such a safer (but slower) version, use %rehashx."""
2188
2188
2189 # This function (and rehashx) manipulate the alias_table directly
2189 # This function (and rehashx) manipulate the alias_table directly
2190 # rather than calling magic_alias, for speed reasons. A rehash on a
2190 # rather than calling magic_alias, for speed reasons. A rehash on a
2191 # typical Linux box involves several thousand entries, so efficiency
2191 # typical Linux box involves several thousand entries, so efficiency
2192 # here is a top concern.
2192 # here is a top concern.
2193
2193
2194 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2194 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2195 alias_table = self.shell.alias_table
2195 alias_table = self.shell.alias_table
2196 for pdir in path:
2196 for pdir in path:
2197 for ff in os.listdir(pdir):
2197 for ff in os.listdir(pdir):
2198 # each entry in the alias table must be (N,name), where
2198 # each entry in the alias table must be (N,name), where
2199 # N is the number of positional arguments of the alias.
2199 # N is the number of positional arguments of the alias.
2200 alias_table[ff] = (0,ff)
2200 alias_table[ff] = (0,ff)
2201 # Make sure the alias table doesn't contain keywords or builtins
2201 # Make sure the alias table doesn't contain keywords or builtins
2202 self.shell.alias_table_validate()
2202 self.shell.alias_table_validate()
2203 # Call again init_auto_alias() so we get 'rm -i' and other modified
2203 # Call again init_auto_alias() so we get 'rm -i' and other modified
2204 # aliases since %rehash will probably clobber them
2204 # aliases since %rehash will probably clobber them
2205 self.shell.init_auto_alias()
2205 self.shell.init_auto_alias()
2206
2206
2207 def magic_rehashx(self, parameter_s = ''):
2207 def magic_rehashx(self, parameter_s = ''):
2208 """Update the alias table with all executable files in $PATH.
2208 """Update the alias table with all executable files in $PATH.
2209
2209
2210 This version explicitly checks that every entry in $PATH is a file
2210 This version explicitly checks that every entry in $PATH is a file
2211 with execute access (os.X_OK), so it is much slower than %rehash.
2211 with execute access (os.X_OK), so it is much slower than %rehash.
2212
2212
2213 Under Windows, it checks executability as a match agains a
2213 Under Windows, it checks executability as a match agains a
2214 '|'-separated string of extensions, stored in the IPython config
2214 '|'-separated string of extensions, stored in the IPython config
2215 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2215 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2216
2216
2217 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2217 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2218 alias_table = self.shell.alias_table
2218 alias_table = self.shell.alias_table
2219
2219
2220 if os.name == 'posix':
2220 if os.name == 'posix':
2221 isexec = lambda fname:os.path.isfile(fname) and \
2221 isexec = lambda fname:os.path.isfile(fname) and \
2222 os.access(fname,os.X_OK)
2222 os.access(fname,os.X_OK)
2223 else:
2223 else:
2224
2224
2225 try:
2225 try:
2226 winext = os.environ['pathext'].replace(';','|').replace('.','')
2226 winext = os.environ['pathext'].replace(';','|').replace('.','')
2227 except KeyError:
2227 except KeyError:
2228 winext = 'exe|com|bat'
2228 winext = 'exe|com|bat'
2229
2229
2230 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2230 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2231 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2231 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2232 savedir = os.getcwd()
2232 savedir = os.getcwd()
2233 try:
2233 try:
2234 # write the whole loop for posix/Windows so we don't have an if in
2234 # write the whole loop for posix/Windows so we don't have an if in
2235 # the innermost part
2235 # the innermost part
2236 if os.name == 'posix':
2236 if os.name == 'posix':
2237 for pdir in path:
2237 for pdir in path:
2238 os.chdir(pdir)
2238 os.chdir(pdir)
2239 for ff in os.listdir(pdir):
2239 for ff in os.listdir(pdir):
2240 if isexec(ff):
2240 if isexec(ff):
2241 # each entry in the alias table must be (N,name),
2241 # each entry in the alias table must be (N,name),
2242 # where N is the number of positional arguments of the
2242 # where N is the number of positional arguments of the
2243 # alias.
2243 # alias.
2244 alias_table[ff] = (0,ff)
2244 alias_table[ff] = (0,ff)
2245 else:
2245 else:
2246 for pdir in path:
2246 for pdir in path:
2247 os.chdir(pdir)
2247 os.chdir(pdir)
2248 for ff in os.listdir(pdir):
2248 for ff in os.listdir(pdir):
2249 if isexec(ff):
2249 if isexec(ff):
2250 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2250 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2251 # Make sure the alias table doesn't contain keywords or builtins
2251 # Make sure the alias table doesn't contain keywords or builtins
2252 self.shell.alias_table_validate()
2252 self.shell.alias_table_validate()
2253 # Call again init_auto_alias() so we get 'rm -i' and other
2253 # Call again init_auto_alias() so we get 'rm -i' and other
2254 # modified aliases since %rehashx will probably clobber them
2254 # modified aliases since %rehashx will probably clobber them
2255 self.shell.init_auto_alias()
2255 self.shell.init_auto_alias()
2256 finally:
2256 finally:
2257 os.chdir(savedir)
2257 os.chdir(savedir)
2258
2258
2259 def magic_pwd(self, parameter_s = ''):
2259 def magic_pwd(self, parameter_s = ''):
2260 """Return the current working directory path."""
2260 """Return the current working directory path."""
2261 return os.getcwd()
2261 return os.getcwd()
2262
2262
2263 def magic_cd(self, parameter_s=''):
2263 def magic_cd(self, parameter_s=''):
2264 """Change the current working directory.
2264 """Change the current working directory.
2265
2265
2266 This command automatically maintains an internal list of directories
2266 This command automatically maintains an internal list of directories
2267 you visit during your IPython session, in the variable _dh. The
2267 you visit during your IPython session, in the variable _dh. The
2268 command %dhist shows this history nicely formatted.
2268 command %dhist shows this history nicely formatted.
2269
2269
2270 Usage:
2270 Usage:
2271
2271
2272 cd 'dir': changes to directory 'dir'.
2272 cd 'dir': changes to directory 'dir'.
2273
2273
2274 cd -: changes to the last visited directory.
2274 cd -: changes to the last visited directory.
2275
2275
2276 cd -<n>: changes to the n-th directory in the directory history.
2276 cd -<n>: changes to the n-th directory in the directory history.
2277
2277
2278 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2278 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2279 (note: cd <bookmark_name> is enough if there is no
2279 (note: cd <bookmark_name> is enough if there is no
2280 directory <bookmark_name>, but a bookmark with the name exists.)
2280 directory <bookmark_name>, but a bookmark with the name exists.)
2281
2281
2282 Options:
2282 Options:
2283
2283
2284 -q: quiet. Do not print the working directory after the cd command is
2284 -q: quiet. Do not print the working directory after the cd command is
2285 executed. By default IPython's cd command does print this directory,
2285 executed. By default IPython's cd command does print this directory,
2286 since the default prompts do not display path information.
2286 since the default prompts do not display path information.
2287
2287
2288 Note that !cd doesn't work for this purpose because the shell where
2288 Note that !cd doesn't work for this purpose because the shell where
2289 !command runs is immediately discarded after executing 'command'."""
2289 !command runs is immediately discarded after executing 'command'."""
2290
2290
2291 parameter_s = parameter_s.strip()
2291 parameter_s = parameter_s.strip()
2292 bkms = self.shell.persist.get("bookmarks",{})
2292 bkms = self.shell.persist.get("bookmarks",{})
2293
2293
2294 numcd = re.match(r'(-)(\d+)$',parameter_s)
2294 numcd = re.match(r'(-)(\d+)$',parameter_s)
2295 # jump in directory history by number
2295 # jump in directory history by number
2296 if numcd:
2296 if numcd:
2297 nn = int(numcd.group(2))
2297 nn = int(numcd.group(2))
2298 try:
2298 try:
2299 ps = self.shell.user_ns['_dh'][nn]
2299 ps = self.shell.user_ns['_dh'][nn]
2300 except IndexError:
2300 except IndexError:
2301 print 'The requested directory does not exist in history.'
2301 print 'The requested directory does not exist in history.'
2302 return
2302 return
2303 else:
2303 else:
2304 opts = {}
2304 opts = {}
2305 else:
2305 else:
2306 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2306 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2307 # jump to previous
2307 # jump to previous
2308 if ps == '-':
2308 if ps == '-':
2309 try:
2309 try:
2310 ps = self.shell.user_ns['_dh'][-2]
2310 ps = self.shell.user_ns['_dh'][-2]
2311 except IndexError:
2311 except IndexError:
2312 print 'No previous directory to change to.'
2312 print 'No previous directory to change to.'
2313 return
2313 return
2314 # jump to bookmark
2314 # jump to bookmark
2315 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2315 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2316 if bkms.has_key(ps):
2316 if bkms.has_key(ps):
2317 target = bkms[ps]
2317 target = bkms[ps]
2318 print '(bookmark:%s) -> %s' % (ps,target)
2318 print '(bookmark:%s) -> %s' % (ps,target)
2319 ps = target
2319 ps = target
2320 else:
2320 else:
2321 if bkms:
2321 if bkms:
2322 error("Bookmark '%s' not found. "
2322 error("Bookmark '%s' not found. "
2323 "Use '%%bookmark -l' to see your bookmarks." % ps)
2323 "Use '%%bookmark -l' to see your bookmarks." % ps)
2324 else:
2324 else:
2325 print "Bookmarks not set - use %bookmark <bookmarkname>"
2325 print "Bookmarks not set - use %bookmark <bookmarkname>"
2326 return
2326 return
2327
2327
2328 # at this point ps should point to the target dir
2328 # at this point ps should point to the target dir
2329 if ps:
2329 if ps:
2330 try:
2330 try:
2331 os.chdir(os.path.expanduser(ps))
2331 os.chdir(os.path.expanduser(ps))
2332 except OSError:
2332 except OSError:
2333 print sys.exc_info()[1]
2333 print sys.exc_info()[1]
2334 else:
2334 else:
2335 self.shell.user_ns['_dh'].append(os.getcwd())
2335 self.shell.user_ns['_dh'].append(os.getcwd())
2336 else:
2336 else:
2337 os.chdir(self.shell.home_dir)
2337 os.chdir(self.shell.home_dir)
2338 self.shell.user_ns['_dh'].append(os.getcwd())
2338 self.shell.user_ns['_dh'].append(os.getcwd())
2339 if not 'q' in opts:
2339 if not 'q' in opts:
2340 print self.shell.user_ns['_dh'][-1]
2340 print self.shell.user_ns['_dh'][-1]
2341
2341
2342 def magic_dhist(self, parameter_s=''):
2342 def magic_dhist(self, parameter_s=''):
2343 """Print your history of visited directories.
2343 """Print your history of visited directories.
2344
2344
2345 %dhist -> print full history\\
2345 %dhist -> print full history\\
2346 %dhist n -> print last n entries only\\
2346 %dhist n -> print last n entries only\\
2347 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2347 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2348
2348
2349 This history is automatically maintained by the %cd command, and
2349 This history is automatically maintained by the %cd command, and
2350 always available as the global list variable _dh. You can use %cd -<n>
2350 always available as the global list variable _dh. You can use %cd -<n>
2351 to go to directory number <n>."""
2351 to go to directory number <n>."""
2352
2352
2353 dh = self.shell.user_ns['_dh']
2353 dh = self.shell.user_ns['_dh']
2354 if parameter_s:
2354 if parameter_s:
2355 try:
2355 try:
2356 args = map(int,parameter_s.split())
2356 args = map(int,parameter_s.split())
2357 except:
2357 except:
2358 self.arg_err(Magic.magic_dhist)
2358 self.arg_err(Magic.magic_dhist)
2359 return
2359 return
2360 if len(args) == 1:
2360 if len(args) == 1:
2361 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2361 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2362 elif len(args) == 2:
2362 elif len(args) == 2:
2363 ini,fin = args
2363 ini,fin = args
2364 else:
2364 else:
2365 self.arg_err(Magic.magic_dhist)
2365 self.arg_err(Magic.magic_dhist)
2366 return
2366 return
2367 else:
2367 else:
2368 ini,fin = 0,len(dh)
2368 ini,fin = 0,len(dh)
2369 nlprint(dh,
2369 nlprint(dh,
2370 header = 'Directory history (kept in _dh)',
2370 header = 'Directory history (kept in _dh)',
2371 start=ini,stop=fin)
2371 start=ini,stop=fin)
2372
2372
2373 def magic_env(self, parameter_s=''):
2373 def magic_env(self, parameter_s=''):
2374 """List environment variables."""
2374 """List environment variables."""
2375
2375
2376 return os.environ.data
2376 return os.environ.data
2377
2377
2378 def magic_pushd(self, parameter_s=''):
2378 def magic_pushd(self, parameter_s=''):
2379 """Place the current dir on stack and change directory.
2379 """Place the current dir on stack and change directory.
2380
2380
2381 Usage:\\
2381 Usage:\\
2382 %pushd ['dirname']
2382 %pushd ['dirname']
2383
2383
2384 %pushd with no arguments does a %pushd to your home directory.
2384 %pushd with no arguments does a %pushd to your home directory.
2385 """
2385 """
2386 if parameter_s == '': parameter_s = '~'
2386 if parameter_s == '': parameter_s = '~'
2387 dir_s = self.shell.dir_stack
2387 dir_s = self.shell.dir_stack
2388 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2388 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2389 os.path.expanduser(self.shell.dir_stack[0]):
2389 os.path.expanduser(self.shell.dir_stack[0]):
2390 try:
2390 try:
2391 self.magic_cd(parameter_s)
2391 self.magic_cd(parameter_s)
2392 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2392 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2393 self.magic_dirs()
2393 self.magic_dirs()
2394 except:
2394 except:
2395 print 'Invalid directory'
2395 print 'Invalid directory'
2396 else:
2396 else:
2397 print 'You are already there!'
2397 print 'You are already there!'
2398
2398
2399 def magic_popd(self, parameter_s=''):
2399 def magic_popd(self, parameter_s=''):
2400 """Change to directory popped off the top of the stack.
2400 """Change to directory popped off the top of the stack.
2401 """
2401 """
2402 if len (self.shell.dir_stack) > 1:
2402 if len (self.shell.dir_stack) > 1:
2403 self.shell.dir_stack.pop(0)
2403 self.shell.dir_stack.pop(0)
2404 self.magic_cd(self.shell.dir_stack[0])
2404 self.magic_cd(self.shell.dir_stack[0])
2405 print self.shell.dir_stack[0]
2405 print self.shell.dir_stack[0]
2406 else:
2406 else:
2407 print "You can't remove the starting directory from the stack:",\
2407 print "You can't remove the starting directory from the stack:",\
2408 self.shell.dir_stack
2408 self.shell.dir_stack
2409
2409
2410 def magic_dirs(self, parameter_s=''):
2410 def magic_dirs(self, parameter_s=''):
2411 """Return the current directory stack."""
2411 """Return the current directory stack."""
2412
2412
2413 return self.shell.dir_stack[:]
2413 return self.shell.dir_stack[:]
2414
2414
2415 def magic_sc(self, parameter_s=''):
2415 def magic_sc(self, parameter_s=''):
2416 """Shell capture - execute a shell command and capture its output.
2416 """Shell capture - execute a shell command and capture its output.
2417
2417
2418 %sc [options] varname=command
2418 %sc [options] varname=command
2419
2419
2420 IPython will run the given command using commands.getoutput(), and
2420 IPython will run the given command using commands.getoutput(), and
2421 will then update the user's interactive namespace with a variable
2421 will then update the user's interactive namespace with a variable
2422 called varname, containing the value of the call. Your command can
2422 called varname, containing the value of the call. Your command can
2423 contain shell wildcards, pipes, etc.
2423 contain shell wildcards, pipes, etc.
2424
2424
2425 The '=' sign in the syntax is mandatory, and the variable name you
2425 The '=' sign in the syntax is mandatory, and the variable name you
2426 supply must follow Python's standard conventions for valid names.
2426 supply must follow Python's standard conventions for valid names.
2427
2427
2428 Options:
2428 Options:
2429
2429
2430 -l: list output. Split the output on newlines into a list before
2430 -l: list output. Split the output on newlines into a list before
2431 assigning it to the given variable. By default the output is stored
2431 assigning it to the given variable. By default the output is stored
2432 as a single string.
2432 as a single string.
2433
2433
2434 -v: verbose. Print the contents of the variable.
2434 -v: verbose. Print the contents of the variable.
2435
2435
2436 In most cases you should not need to split as a list, because the
2436 In most cases you should not need to split as a list, because the
2437 returned value is a special type of string which can automatically
2437 returned value is a special type of string which can automatically
2438 provide its contents either as a list (split on newlines) or as a
2438 provide its contents either as a list (split on newlines) or as a
2439 space-separated string. These are convenient, respectively, either
2439 space-separated string. These are convenient, respectively, either
2440 for sequential processing or to be passed to a shell command.
2440 for sequential processing or to be passed to a shell command.
2441
2441
2442 For example:
2442 For example:
2443
2443
2444 # Capture into variable a
2444 # Capture into variable a
2445 In [9]: sc a=ls *py
2445 In [9]: sc a=ls *py
2446
2446
2447 # a is a string with embedded newlines
2447 # a is a string with embedded newlines
2448 In [10]: a
2448 In [10]: a
2449 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2449 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2450
2450
2451 # which can be seen as a list:
2451 # which can be seen as a list:
2452 In [11]: a.l
2452 In [11]: a.l
2453 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2453 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2454
2454
2455 # or as a whitespace-separated string:
2455 # or as a whitespace-separated string:
2456 In [12]: a.s
2456 In [12]: a.s
2457 Out[12]: 'setup.py win32_manual_post_install.py'
2457 Out[12]: 'setup.py win32_manual_post_install.py'
2458
2458
2459 # a.s is useful to pass as a single command line:
2459 # a.s is useful to pass as a single command line:
2460 In [13]: !wc -l $a.s
2460 In [13]: !wc -l $a.s
2461 146 setup.py
2461 146 setup.py
2462 130 win32_manual_post_install.py
2462 130 win32_manual_post_install.py
2463 276 total
2463 276 total
2464
2464
2465 # while the list form is useful to loop over:
2465 # while the list form is useful to loop over:
2466 In [14]: for f in a.l:
2466 In [14]: for f in a.l:
2467 ....: !wc -l $f
2467 ....: !wc -l $f
2468 ....:
2468 ....:
2469 146 setup.py
2469 146 setup.py
2470 130 win32_manual_post_install.py
2470 130 win32_manual_post_install.py
2471
2471
2472 Similiarly, the lists returned by the -l option are also special, in
2472 Similiarly, the lists returned by the -l option are also special, in
2473 the sense that you can equally invoke the .s attribute on them to
2473 the sense that you can equally invoke the .s attribute on them to
2474 automatically get a whitespace-separated string from their contents:
2474 automatically get a whitespace-separated string from their contents:
2475
2475
2476 In [1]: sc -l b=ls *py
2476 In [1]: sc -l b=ls *py
2477
2477
2478 In [2]: b
2478 In [2]: b
2479 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2479 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2480
2480
2481 In [3]: b.s
2481 In [3]: b.s
2482 Out[3]: 'setup.py win32_manual_post_install.py'
2482 Out[3]: 'setup.py win32_manual_post_install.py'
2483
2483
2484 In summary, both the lists and strings used for ouptut capture have
2484 In summary, both the lists and strings used for ouptut capture have
2485 the following special attributes:
2485 the following special attributes:
2486
2486
2487 .l (or .list) : value as list.
2487 .l (or .list) : value as list.
2488 .n (or .nlstr): value as newline-separated string.
2488 .n (or .nlstr): value as newline-separated string.
2489 .s (or .spstr): value as space-separated string.
2489 .s (or .spstr): value as space-separated string.
2490 """
2490 """
2491
2491
2492 opts,args = self.parse_options(parameter_s,'lv')
2492 opts,args = self.parse_options(parameter_s,'lv')
2493 # Try to get a variable name and command to run
2493 # Try to get a variable name and command to run
2494 try:
2494 try:
2495 # the variable name must be obtained from the parse_options
2495 # the variable name must be obtained from the parse_options
2496 # output, which uses shlex.split to strip options out.
2496 # output, which uses shlex.split to strip options out.
2497 var,_ = args.split('=',1)
2497 var,_ = args.split('=',1)
2498 var = var.strip()
2498 var = var.strip()
2499 # But the the command has to be extracted from the original input
2499 # But the the command has to be extracted from the original input
2500 # parameter_s, not on what parse_options returns, to avoid the
2500 # parameter_s, not on what parse_options returns, to avoid the
2501 # quote stripping which shlex.split performs on it.
2501 # quote stripping which shlex.split performs on it.
2502 _,cmd = parameter_s.split('=',1)
2502 _,cmd = parameter_s.split('=',1)
2503 except ValueError:
2503 except ValueError:
2504 var,cmd = '',''
2504 var,cmd = '',''
2505 if not var:
2505 if not var:
2506 error('you must specify a variable to assign the command to.')
2506 error('you must specify a variable to assign the command to.')
2507 return
2507 return
2508 # If all looks ok, proceed
2508 # If all looks ok, proceed
2509 out,err = self.shell.getoutputerror(cmd)
2509 out,err = self.shell.getoutputerror(cmd)
2510 if err:
2510 if err:
2511 print >> Term.cerr,err
2511 print >> Term.cerr,err
2512 if opts.has_key('l'):
2512 if opts.has_key('l'):
2513 out = SList(out.split('\n'))
2513 out = SList(out.split('\n'))
2514 else:
2514 else:
2515 out = LSString(out)
2515 out = LSString(out)
2516 if opts.has_key('v'):
2516 if opts.has_key('v'):
2517 print '%s ==\n%s' % (var,pformat(out))
2517 print '%s ==\n%s' % (var,pformat(out))
2518 self.shell.user_ns.update({var:out})
2518 self.shell.user_ns.update({var:out})
2519
2519
2520 def magic_sx(self, parameter_s=''):
2520 def magic_sx(self, parameter_s=''):
2521 """Shell execute - run a shell command and capture its output.
2521 """Shell execute - run a shell command and capture its output.
2522
2522
2523 %sx command
2523 %sx command
2524
2524
2525 IPython will run the given command using commands.getoutput(), and
2525 IPython will run the given command using commands.getoutput(), and
2526 return the result formatted as a list (split on '\\n'). Since the
2526 return the result formatted as a list (split on '\\n'). Since the
2527 output is _returned_, it will be stored in ipython's regular output
2527 output is _returned_, it will be stored in ipython's regular output
2528 cache Out[N] and in the '_N' automatic variables.
2528 cache Out[N] and in the '_N' automatic variables.
2529
2529
2530 Notes:
2530 Notes:
2531
2531
2532 1) If an input line begins with '!!', then %sx is automatically
2532 1) If an input line begins with '!!', then %sx is automatically
2533 invoked. That is, while:
2533 invoked. That is, while:
2534 !ls
2534 !ls
2535 causes ipython to simply issue system('ls'), typing
2535 causes ipython to simply issue system('ls'), typing
2536 !!ls
2536 !!ls
2537 is a shorthand equivalent to:
2537 is a shorthand equivalent to:
2538 %sx ls
2538 %sx ls
2539
2539
2540 2) %sx differs from %sc in that %sx automatically splits into a list,
2540 2) %sx differs from %sc in that %sx automatically splits into a list,
2541 like '%sc -l'. The reason for this is to make it as easy as possible
2541 like '%sc -l'. The reason for this is to make it as easy as possible
2542 to process line-oriented shell output via further python commands.
2542 to process line-oriented shell output via further python commands.
2543 %sc is meant to provide much finer control, but requires more
2543 %sc is meant to provide much finer control, but requires more
2544 typing.
2544 typing.
2545
2545
2546 3) Just like %sc -l, this is a list with special attributes:
2546 3) Just like %sc -l, this is a list with special attributes:
2547
2547
2548 .l (or .list) : value as list.
2548 .l (or .list) : value as list.
2549 .n (or .nlstr): value as newline-separated string.
2549 .n (or .nlstr): value as newline-separated string.
2550 .s (or .spstr): value as whitespace-separated string.
2550 .s (or .spstr): value as whitespace-separated string.
2551
2551
2552 This is very useful when trying to use such lists as arguments to
2552 This is very useful when trying to use such lists as arguments to
2553 system commands."""
2553 system commands."""
2554
2554
2555 if parameter_s:
2555 if parameter_s:
2556 out,err = self.shell.getoutputerror(parameter_s)
2556 out,err = self.shell.getoutputerror(parameter_s)
2557 if err:
2557 if err:
2558 print >> Term.cerr,err
2558 print >> Term.cerr,err
2559 return SList(out.split('\n'))
2559 return SList(out.split('\n'))
2560
2560
2561 def magic_bg(self, parameter_s=''):
2561 def magic_bg(self, parameter_s=''):
2562 """Run a job in the background, in a separate thread.
2562 """Run a job in the background, in a separate thread.
2563
2563
2564 For example,
2564 For example,
2565
2565
2566 %bg myfunc(x,y,z=1)
2566 %bg myfunc(x,y,z=1)
2567
2567
2568 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2568 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2569 execution starts, a message will be printed indicating the job
2569 execution starts, a message will be printed indicating the job
2570 number. If your job number is 5, you can use
2570 number. If your job number is 5, you can use
2571
2571
2572 myvar = jobs.result(5) or myvar = jobs[5].result
2572 myvar = jobs.result(5) or myvar = jobs[5].result
2573
2573
2574 to assign this result to variable 'myvar'.
2574 to assign this result to variable 'myvar'.
2575
2575
2576 IPython has a job manager, accessible via the 'jobs' object. You can
2576 IPython has a job manager, accessible via the 'jobs' object. You can
2577 type jobs? to get more information about it, and use jobs.<TAB> to see
2577 type jobs? to get more information about it, and use jobs.<TAB> to see
2578 its attributes. All attributes not starting with an underscore are
2578 its attributes. All attributes not starting with an underscore are
2579 meant for public use.
2579 meant for public use.
2580
2580
2581 In particular, look at the jobs.new() method, which is used to create
2581 In particular, look at the jobs.new() method, which is used to create
2582 new jobs. This magic %bg function is just a convenience wrapper
2582 new jobs. This magic %bg function is just a convenience wrapper
2583 around jobs.new(), for expression-based jobs. If you want to create a
2583 around jobs.new(), for expression-based jobs. If you want to create a
2584 new job with an explicit function object and arguments, you must call
2584 new job with an explicit function object and arguments, you must call
2585 jobs.new() directly.
2585 jobs.new() directly.
2586
2586
2587 The jobs.new docstring also describes in detail several important
2587 The jobs.new docstring also describes in detail several important
2588 caveats associated with a thread-based model for background job
2588 caveats associated with a thread-based model for background job
2589 execution. Type jobs.new? for details.
2589 execution. Type jobs.new? for details.
2590
2590
2591 You can check the status of all jobs with jobs.status().
2591 You can check the status of all jobs with jobs.status().
2592
2592
2593 The jobs variable is set by IPython into the Python builtin namespace.
2593 The jobs variable is set by IPython into the Python builtin namespace.
2594 If you ever declare a variable named 'jobs', you will shadow this
2594 If you ever declare a variable named 'jobs', you will shadow this
2595 name. You can either delete your global jobs variable to regain
2595 name. You can either delete your global jobs variable to regain
2596 access to the job manager, or make a new name and assign it manually
2596 access to the job manager, or make a new name and assign it manually
2597 to the manager (stored in IPython's namespace). For example, to
2597 to the manager (stored in IPython's namespace). For example, to
2598 assign the job manager to the Jobs name, use:
2598 assign the job manager to the Jobs name, use:
2599
2599
2600 Jobs = __builtins__.jobs"""
2600 Jobs = __builtins__.jobs"""
2601
2601
2602 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2602 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2603
2603
2604 def magic_store(self, parameter_s=''):
2604 def magic_store(self, parameter_s=''):
2605 """Lightweight persistence for python variables.
2605 """Lightweight persistence for python variables.
2606
2606
2607 Example:
2607 Example:
2608
2608
2609 ville@badger[~]|1> A = ['hello',10,'world']\\
2609 ville@badger[~]|1> A = ['hello',10,'world']\\
2610 ville@badger[~]|2> %store A\\
2610 ville@badger[~]|2> %store A\\
2611 ville@badger[~]|3> Exit
2611 ville@badger[~]|3> Exit
2612
2612
2613 (IPython session is closed and started again...)
2613 (IPython session is closed and started again...)
2614
2614
2615 ville@badger:~$ ipython -p pysh\\
2615 ville@badger:~$ ipython -p pysh\\
2616 ville@badger[~]|1> print A
2616 ville@badger[~]|1> print A
2617
2617
2618 ['hello', 10, 'world']
2618 ['hello', 10, 'world']
2619
2619
2620 Usage:
2620 Usage:
2621
2621
2622 %store - Show list of all variables and their current values\\
2622 %store - Show list of all variables and their current values\\
2623 %store <var> - Store the *current* value of the variable to disk\\
2623 %store <var> - Store the *current* value of the variable to disk\\
2624 %store -d <var> - Remove the variable and its value from storage\\
2624 %store -d <var> - Remove the variable and its value from storage\\
2625 %store -r - Remove all variables from storage
2625 %store -r - Remove all variables from storage
2626
2626
2627 It should be noted that if you change the value of a variable, you
2627 It should be noted that if you change the value of a variable, you
2628 need to %store it again if you want to persist the new value.
2628 need to %store it again if you want to persist the new value.
2629
2629
2630 Note also that the variables will need to be pickleable; most basic
2630 Note also that the variables will need to be pickleable; most basic
2631 python types can be safely %stored.
2631 python types can be safely %stored.
2632 """
2632 """
2633
2633
2634 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2634 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2635 # delete
2635 # delete
2636 if opts.has_key('d'):
2636 if opts.has_key('d'):
2637 try:
2637 try:
2638 todel = args[0]
2638 todel = args[0]
2639 except IndexError:
2639 except IndexError:
2640 error('You must provide the variable to forget')
2640 error('You must provide the variable to forget')
2641 else:
2641 else:
2642 try:
2642 try:
2643 del self.shell.persist['S:' + todel]
2643 del self.shell.persist['S:' + todel]
2644 except:
2644 except:
2645 error("Can't delete variable '%s'" % todel)
2645 error("Can't delete variable '%s'" % todel)
2646 # reset
2646 # reset
2647 elif opts.has_key('r'):
2647 elif opts.has_key('r'):
2648 for k in self.shell.persist.keys():
2648 for k in self.shell.persist.keys():
2649 if k.startswith('S:'):
2649 if k.startswith('S:'):
2650 del self.shell.persist[k]
2650 del self.shell.persist[k]
2651
2651
2652 # run without arguments -> list variables & values
2652 # run without arguments -> list variables & values
2653 elif not args:
2653 elif not args:
2654 vars = [v[2:] for v in self.shell.persist.keys()
2654 vars = [v[2:] for v in self.shell.persist.keys()
2655 if v.startswith('S:')]
2655 if v.startswith('S:')]
2656 vars.sort()
2656 vars.sort()
2657 if vars:
2657 if vars:
2658 size = max(map(len,vars))
2658 size = max(map(len,vars))
2659 else:
2659 else:
2660 size = 0
2660 size = 0
2661
2661
2662 print 'Stored variables and their in-memory values:'
2662 print 'Stored variables and their in-memory values:'
2663 fmt = '%-'+str(size)+'s -> %s'
2663 fmt = '%-'+str(size)+'s -> %s'
2664 get = self.shell.user_ns.get
2664 get = self.shell.user_ns.get
2665 for var in vars:
2665 for var in vars:
2666 # print 30 first characters from every var
2666 # print 30 first characters from every var
2667 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2667 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2668
2668
2669 # default action - store the variable
2669 # default action - store the variable
2670 else:
2670 else:
2671 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2671 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2672 self.shell.persist[ 'S:' + args[0] ] = pickled
2672 self.shell.persist[ 'S:' + args[0] ] = pickled
2673 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2673 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2674
2674
2675 def magic_bookmark(self, parameter_s=''):
2675 def magic_bookmark(self, parameter_s=''):
2676 """Manage IPython's bookmark system.
2676 """Manage IPython's bookmark system.
2677
2677
2678 %bookmark <name> - set bookmark to current dir
2678 %bookmark <name> - set bookmark to current dir
2679 %bookmark <name> <dir> - set bookmark to <dir>
2679 %bookmark <name> <dir> - set bookmark to <dir>
2680 %bookmark -l - list all bookmarks
2680 %bookmark -l - list all bookmarks
2681 %bookmark -d <name> - remove bookmark
2681 %bookmark -d <name> - remove bookmark
2682 %bookmark -r - remove all bookmarks
2682 %bookmark -r - remove all bookmarks
2683
2683
2684 You can later on access a bookmarked folder with:
2684 You can later on access a bookmarked folder with:
2685 %cd -b <name>
2685 %cd -b <name>
2686 or simply '%cd <name>' if there is no directory called <name> AND
2686 or simply '%cd <name>' if there is no directory called <name> AND
2687 there is such a bookmark defined.
2687 there is such a bookmark defined.
2688
2688
2689 Your bookmarks persist through IPython sessions, but they are
2689 Your bookmarks persist through IPython sessions, but they are
2690 associated with each profile."""
2690 associated with each profile."""
2691
2691
2692 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2692 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2693 if len(args) > 2:
2693 if len(args) > 2:
2694 error('You can only give at most two arguments')
2694 error('You can only give at most two arguments')
2695 return
2695 return
2696
2696
2697 bkms = self.shell.persist.get('bookmarks',{})
2697 bkms = self.shell.persist.get('bookmarks',{})
2698
2698
2699 if opts.has_key('d'):
2699 if opts.has_key('d'):
2700 try:
2700 try:
2701 todel = args[0]
2701 todel = args[0]
2702 except IndexError:
2702 except IndexError:
2703 error('You must provide a bookmark to delete')
2703 error('You must provide a bookmark to delete')
2704 else:
2704 else:
2705 try:
2705 try:
2706 del bkms[todel]
2706 del bkms[todel]
2707 except:
2707 except:
2708 error("Can't delete bookmark '%s'" % todel)
2708 error("Can't delete bookmark '%s'" % todel)
2709 elif opts.has_key('r'):
2709 elif opts.has_key('r'):
2710 bkms = {}
2710 bkms = {}
2711 elif opts.has_key('l'):
2711 elif opts.has_key('l'):
2712 bks = bkms.keys()
2712 bks = bkms.keys()
2713 bks.sort()
2713 bks.sort()
2714 if bks:
2714 if bks:
2715 size = max(map(len,bks))
2715 size = max(map(len,bks))
2716 else:
2716 else:
2717 size = 0
2717 size = 0
2718 fmt = '%-'+str(size)+'s -> %s'
2718 fmt = '%-'+str(size)+'s -> %s'
2719 print 'Current bookmarks:'
2719 print 'Current bookmarks:'
2720 for bk in bks:
2720 for bk in bks:
2721 print fmt % (bk,bkms[bk])
2721 print fmt % (bk,bkms[bk])
2722 else:
2722 else:
2723 if not args:
2723 if not args:
2724 error("You must specify the bookmark name")
2724 error("You must specify the bookmark name")
2725 elif len(args)==1:
2725 elif len(args)==1:
2726 bkms[args[0]] = os.getcwd()
2726 bkms[args[0]] = os.getcwd()
2727 elif len(args)==2:
2727 elif len(args)==2:
2728 bkms[args[0]] = args[1]
2728 bkms[args[0]] = args[1]
2729 self.shell.persist['bookmarks'] = bkms
2729 self.shell.persist['bookmarks'] = bkms
2730
2730
2731 def magic_pycat(self, parameter_s=''):
2731 def magic_pycat(self, parameter_s=''):
2732 """Show a syntax-highlighted file through a pager.
2732 """Show a syntax-highlighted file through a pager.
2733
2733
2734 This magic is similar to the cat utility, but it will assume the file
2734 This magic is similar to the cat utility, but it will assume the file
2735 to be Python source and will show it with syntax highlighting. """
2735 to be Python source and will show it with syntax highlighting. """
2736
2736
2737 filename = get_py_filename(parameter_s)
2737 filename = get_py_filename(parameter_s)
2738 page(self.shell.pycolorize(file_read(filename)),
2738 page(self.shell.pycolorize(file_read(filename)),
2739 screen_lines=self.shell.rc.screen_length)
2739 screen_lines=self.shell.rc.screen_length)
2740
2740
2741 # end Magic
2741 # end Magic
@@ -1,583 +1,583 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Classes for handling input/output prompts.
3 Classes for handling input/output prompts.
4
4
5 $Id: Prompts.py 994 2006-01-08 08:29:44Z fperez $"""
5 $Id: Prompts.py 1005 2006-01-12 08:39:26Z fperez $"""
6
6
7 #*****************************************************************************
7 #*****************************************************************************
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 from IPython import Release
14 from IPython import Release
15 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 __license__ = Release.license
16 __license__ = Release.license
17 __version__ = Release.version
17 __version__ = Release.version
18
18
19 #****************************************************************************
19 #****************************************************************************
20 # Required modules
20 # Required modules
21 import __builtin__
21 import __builtin__
22 import os
22 import os
23 import socket
23 import socket
24 import sys
24 import sys
25 import time
25 import time
26 from pprint import pprint,pformat
26 from pprint import pprint,pformat
27
27
28 # IPython's own
28 # IPython's own
29 from IPython import ColorANSI
29 from IPython import ColorANSI
30 from IPython.Itpl import ItplNS
30 from IPython.Itpl import ItplNS
31 from IPython.Struct import Struct
31 from IPython.ipstruct import Struct
32 from IPython.macro import Macro
32 from IPython.macro import Macro
33 from IPython.genutils import *
33 from IPython.genutils import *
34
34
35 #****************************************************************************
35 #****************************************************************************
36 #Color schemes for Prompts.
36 #Color schemes for Prompts.
37
37
38 PromptColors = ColorANSI.ColorSchemeTable()
38 PromptColors = ColorANSI.ColorSchemeTable()
39 InputColors = ColorANSI.InputTermColors # just a shorthand
39 InputColors = ColorANSI.InputTermColors # just a shorthand
40 Colors = ColorANSI.TermColors # just a shorthand
40 Colors = ColorANSI.TermColors # just a shorthand
41
41
42 PromptColors.add_scheme(ColorANSI.ColorScheme(
42 PromptColors.add_scheme(ColorANSI.ColorScheme(
43 'NoColor',
43 'NoColor',
44 in_prompt = InputColors.NoColor, # Input prompt
44 in_prompt = InputColors.NoColor, # Input prompt
45 in_number = InputColors.NoColor, # Input prompt number
45 in_number = InputColors.NoColor, # Input prompt number
46 in_prompt2 = InputColors.NoColor, # Continuation prompt
46 in_prompt2 = InputColors.NoColor, # Continuation prompt
47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
48
48
49 out_prompt = Colors.NoColor, # Output prompt
49 out_prompt = Colors.NoColor, # Output prompt
50 out_number = Colors.NoColor, # Output prompt number
50 out_number = Colors.NoColor, # Output prompt number
51
51
52 normal = Colors.NoColor # color off (usu. Colors.Normal)
52 normal = Colors.NoColor # color off (usu. Colors.Normal)
53 ))
53 ))
54
54
55 # make some schemes as instances so we can copy them for modification easily:
55 # make some schemes as instances so we can copy them for modification easily:
56 __PColLinux = ColorANSI.ColorScheme(
56 __PColLinux = ColorANSI.ColorScheme(
57 'Linux',
57 'Linux',
58 in_prompt = InputColors.Green,
58 in_prompt = InputColors.Green,
59 in_number = InputColors.LightGreen,
59 in_number = InputColors.LightGreen,
60 in_prompt2 = InputColors.Green,
60 in_prompt2 = InputColors.Green,
61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
62
62
63 out_prompt = Colors.Red,
63 out_prompt = Colors.Red,
64 out_number = Colors.LightRed,
64 out_number = Colors.LightRed,
65
65
66 normal = Colors.Normal
66 normal = Colors.Normal
67 )
67 )
68 # Don't forget to enter it into the table!
68 # Don't forget to enter it into the table!
69 PromptColors.add_scheme(__PColLinux)
69 PromptColors.add_scheme(__PColLinux)
70
70
71 # Slightly modified Linux for light backgrounds
71 # Slightly modified Linux for light backgrounds
72 __PColLightBG = __PColLinux.copy('LightBG')
72 __PColLightBG = __PColLinux.copy('LightBG')
73
73
74 __PColLightBG.colors.update(
74 __PColLightBG.colors.update(
75 in_prompt = InputColors.Blue,
75 in_prompt = InputColors.Blue,
76 in_number = InputColors.LightBlue,
76 in_number = InputColors.LightBlue,
77 in_prompt2 = InputColors.Blue
77 in_prompt2 = InputColors.Blue
78 )
78 )
79 PromptColors.add_scheme(__PColLightBG)
79 PromptColors.add_scheme(__PColLightBG)
80
80
81 del Colors,InputColors
81 del Colors,InputColors
82
82
83 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
84 def multiple_replace(dict, text):
84 def multiple_replace(dict, text):
85 """ Replace in 'text' all occurences of any key in the given
85 """ Replace in 'text' all occurences of any key in the given
86 dictionary by its corresponding value. Returns the new string."""
86 dictionary by its corresponding value. Returns the new string."""
87
87
88 # Function by Xavier Defrang, originally found at:
88 # Function by Xavier Defrang, originally found at:
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
90
90
91 # Create a regular expression from the dictionary keys
91 # Create a regular expression from the dictionary keys
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
93 # For each match, look-up corresponding value in dictionary
93 # For each match, look-up corresponding value in dictionary
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
95
95
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97 # Special characters that can be used in prompt templates, mainly bash-like
97 # Special characters that can be used in prompt templates, mainly bash-like
98
98
99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
100 # never be expanded out into '~'. Basically anything which can never be a
100 # never be expanded out into '~'. Basically anything which can never be a
101 # reasonable directory name will do, we just want the $HOME -> '~' operation
101 # reasonable directory name will do, we just want the $HOME -> '~' operation
102 # to become a no-op. We pre-compute $HOME here so it's not done on every
102 # to become a no-op. We pre-compute $HOME here so it's not done on every
103 # prompt call.
103 # prompt call.
104
104
105 # FIXME:
105 # FIXME:
106
106
107 # - This should be turned into a class which does proper namespace management,
107 # - This should be turned into a class which does proper namespace management,
108 # since the prompt specials need to be evaluated in a certain namespace.
108 # since the prompt specials need to be evaluated in a certain namespace.
109 # Currently it's just globals, which need to be managed manually by code
109 # Currently it's just globals, which need to be managed manually by code
110 # below.
110 # below.
111
111
112 # - I also need to split up the color schemes from the prompt specials
112 # - I also need to split up the color schemes from the prompt specials
113 # somehow. I don't have a clean design for that quite yet.
113 # somehow. I don't have a clean design for that quite yet.
114
114
115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
116
116
117 # We precompute a few more strings here for the prompt_specials, which are
117 # We precompute a few more strings here for the prompt_specials, which are
118 # fixed once ipython starts. This reduces the runtime overhead of computing
118 # fixed once ipython starts. This reduces the runtime overhead of computing
119 # prompt strings.
119 # prompt strings.
120 USER = os.environ.get("USER")
120 USER = os.environ.get("USER")
121 HOSTNAME = socket.gethostname()
121 HOSTNAME = socket.gethostname()
122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
124
124
125 prompt_specials_color = {
125 prompt_specials_color = {
126 # Prompt/history count
126 # Prompt/history count
127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 # Prompt/history count, with the actual digits replaced by dots. Used
129 # Prompt/history count, with the actual digits replaced by dots. Used
130 # mainly in continuation prompts (prompt_in2)
130 # mainly in continuation prompts (prompt_in2)
131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
132 # Current working directory
132 # Current working directory
133 '\\w': '${os.getcwd()}',
133 '\\w': '${os.getcwd()}',
134 # Current time
134 # Current time
135 '\\t' : '${time.strftime("%H:%M:%S")}',
135 '\\t' : '${time.strftime("%H:%M:%S")}',
136 # Basename of current working directory.
136 # Basename of current working directory.
137 # (use os.sep to make this portable across OSes)
137 # (use os.sep to make this portable across OSes)
138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
139 # These X<N> are an extension to the normal bash prompts. They return
139 # These X<N> are an extension to the normal bash prompts. They return
140 # N terms of the path, after replacing $HOME with '~'
140 # N terms of the path, after replacing $HOME with '~'
141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
142 '\\X1': '${self.cwd_filt(1)}',
142 '\\X1': '${self.cwd_filt(1)}',
143 '\\X2': '${self.cwd_filt(2)}',
143 '\\X2': '${self.cwd_filt(2)}',
144 '\\X3': '${self.cwd_filt(3)}',
144 '\\X3': '${self.cwd_filt(3)}',
145 '\\X4': '${self.cwd_filt(4)}',
145 '\\X4': '${self.cwd_filt(4)}',
146 '\\X5': '${self.cwd_filt(5)}',
146 '\\X5': '${self.cwd_filt(5)}',
147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
148 # N+1 in the list. Somewhat like %cN in tcsh.
148 # N+1 in the list. Somewhat like %cN in tcsh.
149 '\\Y0': '${self.cwd_filt2(0)}',
149 '\\Y0': '${self.cwd_filt2(0)}',
150 '\\Y1': '${self.cwd_filt2(1)}',
150 '\\Y1': '${self.cwd_filt2(1)}',
151 '\\Y2': '${self.cwd_filt2(2)}',
151 '\\Y2': '${self.cwd_filt2(2)}',
152 '\\Y3': '${self.cwd_filt2(3)}',
152 '\\Y3': '${self.cwd_filt2(3)}',
153 '\\Y4': '${self.cwd_filt2(4)}',
153 '\\Y4': '${self.cwd_filt2(4)}',
154 '\\Y5': '${self.cwd_filt2(5)}',
154 '\\Y5': '${self.cwd_filt2(5)}',
155 # Hostname up to first .
155 # Hostname up to first .
156 '\\h': HOSTNAME_SHORT,
156 '\\h': HOSTNAME_SHORT,
157 # Full hostname
157 # Full hostname
158 '\\H': HOSTNAME,
158 '\\H': HOSTNAME,
159 # Username of current user
159 # Username of current user
160 '\\u': USER,
160 '\\u': USER,
161 # Escaped '\'
161 # Escaped '\'
162 '\\\\': '\\',
162 '\\\\': '\\',
163 # Newline
163 # Newline
164 '\\n': '\n',
164 '\\n': '\n',
165 # Carriage return
165 # Carriage return
166 '\\r': '\r',
166 '\\r': '\r',
167 # Release version
167 # Release version
168 '\\v': __version__,
168 '\\v': __version__,
169 # Root symbol ($ or #)
169 # Root symbol ($ or #)
170 '\\$': ROOT_SYMBOL,
170 '\\$': ROOT_SYMBOL,
171 }
171 }
172
172
173 # A copy of the prompt_specials dictionary but with all color escapes removed,
173 # A copy of the prompt_specials dictionary but with all color escapes removed,
174 # so we can correctly compute the prompt length for the auto_rewrite method.
174 # so we can correctly compute the prompt length for the auto_rewrite method.
175 prompt_specials_nocolor = prompt_specials_color.copy()
175 prompt_specials_nocolor = prompt_specials_color.copy()
176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
178
178
179 # Add in all the InputTermColors color escapes as valid prompt characters.
179 # Add in all the InputTermColors color escapes as valid prompt characters.
180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
181 # with a color name which may begin with a letter used by any other of the
181 # with a color name which may begin with a letter used by any other of the
182 # allowed specials. This of course means that \\C will never be allowed for
182 # allowed specials. This of course means that \\C will never be allowed for
183 # anything else.
183 # anything else.
184 input_colors = ColorANSI.InputTermColors
184 input_colors = ColorANSI.InputTermColors
185 for _color in dir(input_colors):
185 for _color in dir(input_colors):
186 if _color[0] != '_':
186 if _color[0] != '_':
187 c_name = '\\C_'+_color
187 c_name = '\\C_'+_color
188 prompt_specials_color[c_name] = getattr(input_colors,_color)
188 prompt_specials_color[c_name] = getattr(input_colors,_color)
189 prompt_specials_nocolor[c_name] = ''
189 prompt_specials_nocolor[c_name] = ''
190
190
191 # we default to no color for safety. Note that prompt_specials is a global
191 # we default to no color for safety. Note that prompt_specials is a global
192 # variable used by all prompt objects.
192 # variable used by all prompt objects.
193 prompt_specials = prompt_specials_nocolor
193 prompt_specials = prompt_specials_nocolor
194
194
195 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
196 def str_safe(arg):
196 def str_safe(arg):
197 """Convert to a string, without ever raising an exception.
197 """Convert to a string, without ever raising an exception.
198
198
199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
200 error message."""
200 error message."""
201
201
202 try:
202 try:
203 out = str(arg)
203 out = str(arg)
204 except UnicodeError:
204 except UnicodeError:
205 try:
205 try:
206 out = arg.encode('utf_8','replace')
206 out = arg.encode('utf_8','replace')
207 except Exception,msg:
207 except Exception,msg:
208 # let's keep this little duplication here, so that the most common
208 # let's keep this little duplication here, so that the most common
209 # case doesn't suffer from a double try wrapping.
209 # case doesn't suffer from a double try wrapping.
210 out = '<ERROR: %s>' % msg
210 out = '<ERROR: %s>' % msg
211 except Exception,msg:
211 except Exception,msg:
212 out = '<ERROR: %s>' % msg
212 out = '<ERROR: %s>' % msg
213 return out
213 return out
214
214
215 class BasePrompt:
215 class BasePrompt:
216 """Interactive prompt similar to Mathematica's."""
216 """Interactive prompt similar to Mathematica's."""
217 def __init__(self,cache,sep,prompt,pad_left=False):
217 def __init__(self,cache,sep,prompt,pad_left=False):
218
218
219 # Hack: we access information about the primary prompt through the
219 # Hack: we access information about the primary prompt through the
220 # cache argument. We need this, because we want the secondary prompt
220 # cache argument. We need this, because we want the secondary prompt
221 # to be aligned with the primary one. Color table info is also shared
221 # to be aligned with the primary one. Color table info is also shared
222 # by all prompt classes through the cache. Nice OO spaghetti code!
222 # by all prompt classes through the cache. Nice OO spaghetti code!
223 self.cache = cache
223 self.cache = cache
224 self.sep = sep
224 self.sep = sep
225
225
226 # regexp to count the number of spaces at the end of a prompt
226 # regexp to count the number of spaces at the end of a prompt
227 # expression, useful for prompt auto-rewriting
227 # expression, useful for prompt auto-rewriting
228 self.rspace = re.compile(r'(\s*)$')
228 self.rspace = re.compile(r'(\s*)$')
229 # Flag to left-pad prompt strings to match the length of the primary
229 # Flag to left-pad prompt strings to match the length of the primary
230 # prompt
230 # prompt
231 self.pad_left = pad_left
231 self.pad_left = pad_left
232 # Set template to create each actual prompt (where numbers change)
232 # Set template to create each actual prompt (where numbers change)
233 self.p_template = prompt
233 self.p_template = prompt
234 self.set_p_str()
234 self.set_p_str()
235
235
236 def set_p_str(self):
236 def set_p_str(self):
237 """ Set the interpolating prompt strings.
237 """ Set the interpolating prompt strings.
238
238
239 This must be called every time the color settings change, because the
239 This must be called every time the color settings change, because the
240 prompt_specials global may have changed."""
240 prompt_specials global may have changed."""
241
241
242 import os,time # needed in locals for prompt string handling
242 import os,time # needed in locals for prompt string handling
243 loc = locals()
243 loc = locals()
244 self.p_str = ItplNS('%s%s%s' %
244 self.p_str = ItplNS('%s%s%s' %
245 ('${self.sep}${self.col_p}',
245 ('${self.sep}${self.col_p}',
246 multiple_replace(prompt_specials, self.p_template),
246 multiple_replace(prompt_specials, self.p_template),
247 '${self.col_norm}'),self.cache.user_ns,loc)
247 '${self.col_norm}'),self.cache.user_ns,loc)
248
248
249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
250 self.p_template),
250 self.p_template),
251 self.cache.user_ns,loc)
251 self.cache.user_ns,loc)
252
252
253 def write(self,msg): # dbg
253 def write(self,msg): # dbg
254 sys.stdout.write(msg)
254 sys.stdout.write(msg)
255 return ''
255 return ''
256
256
257 def __str__(self):
257 def __str__(self):
258 """Return a string form of the prompt.
258 """Return a string form of the prompt.
259
259
260 This for is useful for continuation and output prompts, since it is
260 This for is useful for continuation and output prompts, since it is
261 left-padded to match lengths with the primary one (if the
261 left-padded to match lengths with the primary one (if the
262 self.pad_left attribute is set)."""
262 self.pad_left attribute is set)."""
263
263
264 out_str = str_safe(self.p_str)
264 out_str = str_safe(self.p_str)
265 if self.pad_left:
265 if self.pad_left:
266 # We must find the amount of padding required to match lengths,
266 # We must find the amount of padding required to match lengths,
267 # taking the color escapes (which are invisible on-screen) into
267 # taking the color escapes (which are invisible on-screen) into
268 # account.
268 # account.
269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
271 return format % out_str
271 return format % out_str
272 else:
272 else:
273 return out_str
273 return out_str
274
274
275 # these path filters are put in as methods so that we can control the
275 # these path filters are put in as methods so that we can control the
276 # namespace where the prompt strings get evaluated
276 # namespace where the prompt strings get evaluated
277 def cwd_filt(self,depth):
277 def cwd_filt(self,depth):
278 """Return the last depth elements of the current working directory.
278 """Return the last depth elements of the current working directory.
279
279
280 $HOME is always replaced with '~'.
280 $HOME is always replaced with '~'.
281 If depth==0, the full path is returned."""
281 If depth==0, the full path is returned."""
282
282
283 cwd = os.getcwd().replace(HOME,"~")
283 cwd = os.getcwd().replace(HOME,"~")
284 out = os.sep.join(cwd.split(os.sep)[-depth:])
284 out = os.sep.join(cwd.split(os.sep)[-depth:])
285 if out:
285 if out:
286 return out
286 return out
287 else:
287 else:
288 return os.sep
288 return os.sep
289
289
290 def cwd_filt2(self,depth):
290 def cwd_filt2(self,depth):
291 """Return the last depth elements of the current working directory.
291 """Return the last depth elements of the current working directory.
292
292
293 $HOME is always replaced with '~'.
293 $HOME is always replaced with '~'.
294 If depth==0, the full path is returned."""
294 If depth==0, the full path is returned."""
295
295
296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
297 if '~' in cwd and len(cwd) == depth+1:
297 if '~' in cwd and len(cwd) == depth+1:
298 depth += 1
298 depth += 1
299 out = os.sep.join(cwd[-depth:])
299 out = os.sep.join(cwd[-depth:])
300 if out:
300 if out:
301 return out
301 return out
302 else:
302 else:
303 return os.sep
303 return os.sep
304
304
305 class Prompt1(BasePrompt):
305 class Prompt1(BasePrompt):
306 """Input interactive prompt similar to Mathematica's."""
306 """Input interactive prompt similar to Mathematica's."""
307
307
308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
310
310
311 def set_colors(self):
311 def set_colors(self):
312 self.set_p_str()
312 self.set_p_str()
313 Colors = self.cache.color_table.active_colors # shorthand
313 Colors = self.cache.color_table.active_colors # shorthand
314 self.col_p = Colors.in_prompt
314 self.col_p = Colors.in_prompt
315 self.col_num = Colors.in_number
315 self.col_num = Colors.in_number
316 self.col_norm = Colors.in_normal
316 self.col_norm = Colors.in_normal
317 # We need a non-input version of these escapes for the '--->'
317 # We need a non-input version of these escapes for the '--->'
318 # auto-call prompts used in the auto_rewrite() method.
318 # auto-call prompts used in the auto_rewrite() method.
319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
320 self.col_norm_ni = Colors.normal
320 self.col_norm_ni = Colors.normal
321
321
322 def __str__(self):
322 def __str__(self):
323 self.cache.prompt_count += 1
323 self.cache.prompt_count += 1
324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
325 return str_safe(self.p_str)
325 return str_safe(self.p_str)
326
326
327 def auto_rewrite(self):
327 def auto_rewrite(self):
328 """Print a string of the form '--->' which lines up with the previous
328 """Print a string of the form '--->' which lines up with the previous
329 input string. Useful for systems which re-write the user input when
329 input string. Useful for systems which re-write the user input when
330 handling automatically special syntaxes."""
330 handling automatically special syntaxes."""
331
331
332 curr = str(self.cache.last_prompt)
332 curr = str(self.cache.last_prompt)
333 nrspaces = len(self.rspace.search(curr).group())
333 nrspaces = len(self.rspace.search(curr).group())
334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
335 ' '*nrspaces,self.col_norm_ni)
335 ' '*nrspaces,self.col_norm_ni)
336
336
337 class PromptOut(BasePrompt):
337 class PromptOut(BasePrompt):
338 """Output interactive prompt similar to Mathematica's."""
338 """Output interactive prompt similar to Mathematica's."""
339
339
340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
342 if not self.p_template:
342 if not self.p_template:
343 self.__str__ = lambda: ''
343 self.__str__ = lambda: ''
344
344
345 def set_colors(self):
345 def set_colors(self):
346 self.set_p_str()
346 self.set_p_str()
347 Colors = self.cache.color_table.active_colors # shorthand
347 Colors = self.cache.color_table.active_colors # shorthand
348 self.col_p = Colors.out_prompt
348 self.col_p = Colors.out_prompt
349 self.col_num = Colors.out_number
349 self.col_num = Colors.out_number
350 self.col_norm = Colors.normal
350 self.col_norm = Colors.normal
351
351
352 class Prompt2(BasePrompt):
352 class Prompt2(BasePrompt):
353 """Interactive continuation prompt."""
353 """Interactive continuation prompt."""
354
354
355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
356 self.cache = cache
356 self.cache = cache
357 self.p_template = prompt
357 self.p_template = prompt
358 self.pad_left = pad_left
358 self.pad_left = pad_left
359 self.set_p_str()
359 self.set_p_str()
360
360
361 def set_p_str(self):
361 def set_p_str(self):
362 import os,time # needed in locals for prompt string handling
362 import os,time # needed in locals for prompt string handling
363 loc = locals()
363 loc = locals()
364 self.p_str = ItplNS('%s%s%s' %
364 self.p_str = ItplNS('%s%s%s' %
365 ('${self.col_p2}',
365 ('${self.col_p2}',
366 multiple_replace(prompt_specials, self.p_template),
366 multiple_replace(prompt_specials, self.p_template),
367 '$self.col_norm'),
367 '$self.col_norm'),
368 self.cache.user_ns,loc)
368 self.cache.user_ns,loc)
369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
370 self.p_template),
370 self.p_template),
371 self.cache.user_ns,loc)
371 self.cache.user_ns,loc)
372
372
373 def set_colors(self):
373 def set_colors(self):
374 self.set_p_str()
374 self.set_p_str()
375 Colors = self.cache.color_table.active_colors
375 Colors = self.cache.color_table.active_colors
376 self.col_p2 = Colors.in_prompt2
376 self.col_p2 = Colors.in_prompt2
377 self.col_norm = Colors.in_normal
377 self.col_norm = Colors.in_normal
378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
379 # updated their prompt_in2 definitions. Remove eventually.
379 # updated their prompt_in2 definitions. Remove eventually.
380 self.col_p = Colors.out_prompt
380 self.col_p = Colors.out_prompt
381 self.col_num = Colors.out_number
381 self.col_num = Colors.out_number
382
382
383 #-----------------------------------------------------------------------------
383 #-----------------------------------------------------------------------------
384 class CachedOutput:
384 class CachedOutput:
385 """Class for printing output from calculations while keeping a cache of
385 """Class for printing output from calculations while keeping a cache of
386 reults. It dynamically creates global variables prefixed with _ which
386 reults. It dynamically creates global variables prefixed with _ which
387 contain these results.
387 contain these results.
388
388
389 Meant to be used as a sys.displayhook replacement, providing numbered
389 Meant to be used as a sys.displayhook replacement, providing numbered
390 prompts and cache services.
390 prompts and cache services.
391
391
392 Initialize with initial and final values for cache counter (this defines
392 Initialize with initial and final values for cache counter (this defines
393 the maximum size of the cache."""
393 the maximum size of the cache."""
394
394
395 def __init__(self,shell,cache_size,Pprint,
395 def __init__(self,shell,cache_size,Pprint,
396 colors='NoColor',input_sep='\n',
396 colors='NoColor',input_sep='\n',
397 output_sep='\n',output_sep2='',
397 output_sep='\n',output_sep2='',
398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
399
399
400 cache_size_min = 20
400 cache_size_min = 20
401 if cache_size <= 0:
401 if cache_size <= 0:
402 self.do_full_cache = 0
402 self.do_full_cache = 0
403 cache_size = 0
403 cache_size = 0
404 elif cache_size < cache_size_min:
404 elif cache_size < cache_size_min:
405 self.do_full_cache = 0
405 self.do_full_cache = 0
406 cache_size = 0
406 cache_size = 0
407 warn('caching was disabled (min value for cache size is %s).' %
407 warn('caching was disabled (min value for cache size is %s).' %
408 cache_size_min,level=3)
408 cache_size_min,level=3)
409 else:
409 else:
410 self.do_full_cache = 1
410 self.do_full_cache = 1
411
411
412 self.cache_size = cache_size
412 self.cache_size = cache_size
413 self.input_sep = input_sep
413 self.input_sep = input_sep
414
414
415 # we need a reference to the user-level namespace
415 # we need a reference to the user-level namespace
416 self.shell = shell
416 self.shell = shell
417 self.user_ns = shell.user_ns
417 self.user_ns = shell.user_ns
418 # and to the user's input
418 # and to the user's input
419 self.input_hist = shell.input_hist
419 self.input_hist = shell.input_hist
420 # and to the user's logger, for logging output
420 # and to the user's logger, for logging output
421 self.logger = shell.logger
421 self.logger = shell.logger
422
422
423 # Set input prompt strings and colors
423 # Set input prompt strings and colors
424 if cache_size == 0:
424 if cache_size == 0:
425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
430
430
431 self.color_table = PromptColors
431 self.color_table = PromptColors
432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
433 pad_left=pad_left)
433 pad_left=pad_left)
434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
436 pad_left=pad_left)
436 pad_left=pad_left)
437 self.set_colors(colors)
437 self.set_colors(colors)
438
438
439 # other more normal stuff
439 # other more normal stuff
440 # b/c each call to the In[] prompt raises it by 1, even the first.
440 # b/c each call to the In[] prompt raises it by 1, even the first.
441 self.prompt_count = 0
441 self.prompt_count = 0
442 self.cache_count = 1
442 self.cache_count = 1
443 # Store the last prompt string each time, we need it for aligning
443 # Store the last prompt string each time, we need it for aligning
444 # continuation and auto-rewrite prompts
444 # continuation and auto-rewrite prompts
445 self.last_prompt = ''
445 self.last_prompt = ''
446 self.entries = [None] # output counter starts at 1 for the user
446 self.entries = [None] # output counter starts at 1 for the user
447 self.Pprint = Pprint
447 self.Pprint = Pprint
448 self.output_sep = output_sep
448 self.output_sep = output_sep
449 self.output_sep2 = output_sep2
449 self.output_sep2 = output_sep2
450 self._,self.__,self.___ = '','',''
450 self._,self.__,self.___ = '','',''
451 self.pprint_types = map(type,[(),[],{}])
451 self.pprint_types = map(type,[(),[],{}])
452
452
453 # these are deliberately global:
453 # these are deliberately global:
454 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
454 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
455 self.user_ns.update(to_user_ns)
455 self.user_ns.update(to_user_ns)
456
456
457 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
457 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
458 if p_str is None:
458 if p_str is None:
459 if self.do_full_cache:
459 if self.do_full_cache:
460 return cache_def
460 return cache_def
461 else:
461 else:
462 return no_cache_def
462 return no_cache_def
463 else:
463 else:
464 return p_str
464 return p_str
465
465
466 def set_colors(self,colors):
466 def set_colors(self,colors):
467 """Set the active color scheme and configure colors for the three
467 """Set the active color scheme and configure colors for the three
468 prompt subsystems."""
468 prompt subsystems."""
469
469
470 # FIXME: the prompt_specials global should be gobbled inside this
470 # FIXME: the prompt_specials global should be gobbled inside this
471 # class instead. Do it when cleaning up the whole 3-prompt system.
471 # class instead. Do it when cleaning up the whole 3-prompt system.
472 global prompt_specials
472 global prompt_specials
473 if colors.lower()=='nocolor':
473 if colors.lower()=='nocolor':
474 prompt_specials = prompt_specials_nocolor
474 prompt_specials = prompt_specials_nocolor
475 else:
475 else:
476 prompt_specials = prompt_specials_color
476 prompt_specials = prompt_specials_color
477
477
478 self.color_table.set_active_scheme(colors)
478 self.color_table.set_active_scheme(colors)
479 self.prompt1.set_colors()
479 self.prompt1.set_colors()
480 self.prompt2.set_colors()
480 self.prompt2.set_colors()
481 self.prompt_out.set_colors()
481 self.prompt_out.set_colors()
482
482
483 def __call__(self,arg=None):
483 def __call__(self,arg=None):
484 """Printing with history cache management.
484 """Printing with history cache management.
485
485
486 This is invoked everytime the interpreter needs to print, and is
486 This is invoked everytime the interpreter needs to print, and is
487 activated by setting the variable sys.displayhook to it."""
487 activated by setting the variable sys.displayhook to it."""
488
488
489 # If something injected a '_' variable in __builtin__, delete
489 # If something injected a '_' variable in __builtin__, delete
490 # ipython's automatic one so we don't clobber that. gettext() in
490 # ipython's automatic one so we don't clobber that. gettext() in
491 # particular uses _, so we need to stay away from it.
491 # particular uses _, so we need to stay away from it.
492 if '_' in __builtin__.__dict__:
492 if '_' in __builtin__.__dict__:
493 try:
493 try:
494 del self.user_ns['_']
494 del self.user_ns['_']
495 except KeyError:
495 except KeyError:
496 pass
496 pass
497 if arg is not None:
497 if arg is not None:
498 cout_write = Term.cout.write # fast lookup
498 cout_write = Term.cout.write # fast lookup
499 # first handle the cache and counters
499 # first handle the cache and counters
500 # but avoid recursive reference when displaying _oh/Out
500 # but avoid recursive reference when displaying _oh/Out
501 if arg is not self.user_ns['_oh']:
501 if arg is not self.user_ns['_oh']:
502 self.update(arg)
502 self.update(arg)
503 # do not print output if input ends in ';'
503 # do not print output if input ends in ';'
504 if self.input_hist[self.prompt_count].endswith(';\n'):
504 if self.input_hist[self.prompt_count].endswith(';\n'):
505 return
505 return
506 # don't use print, puts an extra space
506 # don't use print, puts an extra space
507 cout_write(self.output_sep)
507 cout_write(self.output_sep)
508 if self.do_full_cache:
508 if self.do_full_cache:
509 cout_write(str(self.prompt_out))
509 cout_write(str(self.prompt_out))
510
510
511 if isinstance(arg,Macro):
511 if isinstance(arg,Macro):
512 print 'Executing Macro...'
512 print 'Executing Macro...'
513 # in case the macro takes a long time to execute
513 # in case the macro takes a long time to execute
514 Term.cout.flush()
514 Term.cout.flush()
515 self.shell.runlines(arg.value)
515 self.shell.runlines(arg.value)
516 return None
516 return None
517
517
518 # and now call a possibly user-defined print mechanism
518 # and now call a possibly user-defined print mechanism
519 self.display(arg)
519 self.display(arg)
520 if self.logger.log_output:
520 if self.logger.log_output:
521 self.logger.log_write(repr(arg),'output')
521 self.logger.log_write(repr(arg),'output')
522 cout_write(self.output_sep2)
522 cout_write(self.output_sep2)
523 Term.cout.flush()
523 Term.cout.flush()
524
524
525 def _display(self,arg):
525 def _display(self,arg):
526 """Default printer method, uses pprint.
526 """Default printer method, uses pprint.
527
527
528 This can be over-ridden by the users to implement special formatting
528 This can be over-ridden by the users to implement special formatting
529 of certain types of output."""
529 of certain types of output."""
530
530
531 if self.Pprint:
531 if self.Pprint:
532 out = pformat(arg)
532 out = pformat(arg)
533 if '\n' in out:
533 if '\n' in out:
534 # So that multi-line strings line up with the left column of
534 # So that multi-line strings line up with the left column of
535 # the screen, instead of having the output prompt mess up
535 # the screen, instead of having the output prompt mess up
536 # their first line.
536 # their first line.
537 Term.cout.write('\n')
537 Term.cout.write('\n')
538 print >>Term.cout, out
538 print >>Term.cout, out
539 else:
539 else:
540 print >>Term.cout, arg
540 print >>Term.cout, arg
541
541
542 # Assign the default display method:
542 # Assign the default display method:
543 display = _display
543 display = _display
544
544
545 def update(self,arg):
545 def update(self,arg):
546 #print '***cache_count', self.cache_count # dbg
546 #print '***cache_count', self.cache_count # dbg
547 if self.cache_count >= self.cache_size and self.do_full_cache:
547 if self.cache_count >= self.cache_size and self.do_full_cache:
548 self.flush()
548 self.flush()
549 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
549 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
550 # we cause buggy behavior for things like gettext).
550 # we cause buggy behavior for things like gettext).
551 if '_' not in __builtin__.__dict__:
551 if '_' not in __builtin__.__dict__:
552 self.___ = self.__
552 self.___ = self.__
553 self.__ = self._
553 self.__ = self._
554 self._ = arg
554 self._ = arg
555 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
555 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
556
556
557 # hackish access to top-level namespace to create _1,_2... dynamically
557 # hackish access to top-level namespace to create _1,_2... dynamically
558 to_main = {}
558 to_main = {}
559 if self.do_full_cache:
559 if self.do_full_cache:
560 self.cache_count += 1
560 self.cache_count += 1
561 self.entries.append(arg)
561 self.entries.append(arg)
562 new_result = '_'+`self.prompt_count`
562 new_result = '_'+`self.prompt_count`
563 to_main[new_result] = self.entries[-1]
563 to_main[new_result] = self.entries[-1]
564 self.user_ns.update(to_main)
564 self.user_ns.update(to_main)
565 self.user_ns['_oh'][self.prompt_count] = arg
565 self.user_ns['_oh'][self.prompt_count] = arg
566
566
567 def flush(self):
567 def flush(self):
568 if not self.do_full_cache:
568 if not self.do_full_cache:
569 raise ValueError,"You shouldn't have reached the cache flush "\
569 raise ValueError,"You shouldn't have reached the cache flush "\
570 "if full caching is not enabled!"
570 "if full caching is not enabled!"
571 warn('Output cache limit (currently '+\
571 warn('Output cache limit (currently '+\
572 `self.cache_count`+' entries) hit.\n'
572 `self.cache_count`+' entries) hit.\n'
573 'Flushing cache and resetting history counter...\n'
573 'Flushing cache and resetting history counter...\n'
574 'The only history variables available will be _,__,___ and _1\n'
574 'The only history variables available will be _,__,___ and _1\n'
575 'with the current result.')
575 'with the current result.')
576 # delete auto-generated vars from global namespace
576 # delete auto-generated vars from global namespace
577 for n in range(1,self.prompt_count + 1):
577 for n in range(1,self.prompt_count + 1):
578 key = '_'+`n`
578 key = '_'+`n`
579 try:
579 try:
580 del self.user_ns[key]
580 del self.user_ns[key]
581 except: pass
581 except: pass
582 self.prompt_count = 1
582 self.prompt_count = 1
583 self.cache_count = 1
583 self.cache_count = 1
@@ -1,939 +1,939 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Shell classes.
2 """IPython Shell classes.
3
3
4 All the matplotlib support code was co-developed with John Hunter,
4 All the matplotlib support code was co-developed with John Hunter,
5 matplotlib's author.
5 matplotlib's author.
6
6
7 $Id: Shell.py 1002 2006-01-11 22:18:29Z fperez $"""
7 $Id: Shell.py 1005 2006-01-12 08:39:26Z fperez $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 from IPython import Release
16 from IPython import Release
17 __author__ = '%s <%s>' % Release.authors['Fernando']
17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __license__ = Release.license
18 __license__ = Release.license
19
19
20 # Code begins
20 # Code begins
21 import __main__
21 import __main__
22 import __builtin__
22 import __builtin__
23 import os
23 import os
24 import sys
24 import sys
25 import signal
25 import signal
26 import time
26 import time
27 import threading
27 import threading
28
28
29 import IPython
29 import IPython
30 from IPython import ultraTB
30 from IPython import ultraTB
31 from IPython.genutils import Term,warn,error,flag_calls
31 from IPython.genutils import Term,warn,error,flag_calls
32 from IPython.iplib import InteractiveShell
32 from IPython.iplib import InteractiveShell
33 from IPython.ipmaker import make_IPython
33 from IPython.ipmaker import make_IPython
34 from IPython.Magic import Magic
34 from IPython.Magic import Magic
35 from IPython.Struct import Struct
35 from IPython.ipstruct import Struct
36
36
37 # global flag to pass around information about Ctrl-C without exceptions
37 # global flag to pass around information about Ctrl-C without exceptions
38 KBINT = False
38 KBINT = False
39
39
40 # global flag to turn on/off Tk support.
40 # global flag to turn on/off Tk support.
41 USE_TK = False
41 USE_TK = False
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # This class is trivial now, but I want to have it in to publish a clean
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
45 # interface. Later when the internals are reorganized, code that uses this
46 # shouldn't have to change.
46 # shouldn't have to change.
47
47
48 class IPShell:
48 class IPShell:
49 """Create an IPython instance."""
49 """Create an IPython instance."""
50
50
51 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
51 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
52 debug=1,shell_class=InteractiveShell):
52 debug=1,shell_class=InteractiveShell):
53 self.IP = make_IPython(argv,user_ns=user_ns,user_global_ns=user_global_ns,
53 self.IP = make_IPython(argv,user_ns=user_ns,user_global_ns=user_global_ns,
54 debug=debug,shell_class=shell_class)
54 debug=debug,shell_class=shell_class)
55
55
56 def mainloop(self,sys_exit=0,banner=None):
56 def mainloop(self,sys_exit=0,banner=None):
57 self.IP.mainloop(banner)
57 self.IP.mainloop(banner)
58 if sys_exit:
58 if sys_exit:
59 sys.exit()
59 sys.exit()
60
60
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62 class IPShellEmbed:
62 class IPShellEmbed:
63 """Allow embedding an IPython shell into a running program.
63 """Allow embedding an IPython shell into a running program.
64
64
65 Instances of this class are callable, with the __call__ method being an
65 Instances of this class are callable, with the __call__ method being an
66 alias to the embed() method of an InteractiveShell instance.
66 alias to the embed() method of an InteractiveShell instance.
67
67
68 Usage (see also the example-embed.py file for a running example):
68 Usage (see also the example-embed.py file for a running example):
69
69
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71
71
72 - argv: list containing valid command-line options for IPython, as they
72 - argv: list containing valid command-line options for IPython, as they
73 would appear in sys.argv[1:].
73 would appear in sys.argv[1:].
74
74
75 For example, the following command-line options:
75 For example, the following command-line options:
76
76
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78
78
79 would be passed in the argv list as:
79 would be passed in the argv list as:
80
80
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82
82
83 - banner: string which gets printed every time the interpreter starts.
83 - banner: string which gets printed every time the interpreter starts.
84
84
85 - exit_msg: string which gets printed every time the interpreter exits.
85 - exit_msg: string which gets printed every time the interpreter exits.
86
86
87 - rc_override: a dict or Struct of configuration options such as those
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
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
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
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
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
92 embeddable instances configured in any way you want without editing any
93 global files (thus keeping your interactive IPython configuration
93 global files (thus keeping your interactive IPython configuration
94 unchanged).
94 unchanged).
95
95
96 Then the ipshell instance can be called anywhere inside your code:
96 Then the ipshell instance can be called anywhere inside your code:
97
97
98 ipshell(header='') -> Opens up an IPython shell.
98 ipshell(header='') -> Opens up an IPython shell.
99
99
100 - header: string printed by the IPython shell upon startup. This can let
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
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
102 that 'banner' gets prepended to all calls, so header is used for
103 location-specific information.
103 location-specific information.
104
104
105 For more details, see the __call__ method below.
105 For more details, see the __call__ method below.
106
106
107 When the IPython shell is exited with Ctrl-D, normal program execution
107 When the IPython shell is exited with Ctrl-D, normal program execution
108 resumes.
108 resumes.
109
109
110 This functionality was inspired by a posting on comp.lang.python by cmkl
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
111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 by the IDL stop/continue commands."""
112 by the IDL stop/continue commands."""
113
113
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 """Note that argv here is a string, NOT a list."""
115 """Note that argv here is a string, NOT a list."""
116 self.set_banner(banner)
116 self.set_banner(banner)
117 self.set_exit_msg(exit_msg)
117 self.set_exit_msg(exit_msg)
118 self.set_dummy_mode(0)
118 self.set_dummy_mode(0)
119
119
120 # sys.displayhook is a global, we need to save the user's original
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.
121 # Don't rely on __displayhook__, as the user may have changed that.
122 self.sys_displayhook_ori = sys.displayhook
122 self.sys_displayhook_ori = sys.displayhook
123
123
124 # save readline completer status
124 # save readline completer status
125 try:
125 try:
126 #print 'Save completer',sys.ipcompleter # dbg
126 #print 'Save completer',sys.ipcompleter # dbg
127 self.sys_ipcompleter_ori = sys.ipcompleter
127 self.sys_ipcompleter_ori = sys.ipcompleter
128 except:
128 except:
129 pass # not nested with IPython
129 pass # not nested with IPython
130
130
131 # FIXME. Passing user_ns breaks namespace handling.
131 # FIXME. Passing user_ns breaks namespace handling.
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134
134
135 # copy our own displayhook also
135 # copy our own displayhook also
136 self.sys_displayhook_embed = sys.displayhook
136 self.sys_displayhook_embed = sys.displayhook
137 # and leave the system's display hook clean
137 # and leave the system's display hook clean
138 sys.displayhook = self.sys_displayhook_ori
138 sys.displayhook = self.sys_displayhook_ori
139 # don't use the ipython crash handler so that user exceptions aren't
139 # don't use the ipython crash handler so that user exceptions aren't
140 # trapped
140 # trapped
141 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
141 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
142 mode = self.IP.rc.xmode,
142 mode = self.IP.rc.xmode,
143 call_pdb = self.IP.rc.pdb)
143 call_pdb = self.IP.rc.pdb)
144 self.restore_system_completer()
144 self.restore_system_completer()
145
145
146 def restore_system_completer(self):
146 def restore_system_completer(self):
147 """Restores the readline completer which was in place.
147 """Restores the readline completer which was in place.
148
148
149 This allows embedded IPython within IPython not to disrupt the
149 This allows embedded IPython within IPython not to disrupt the
150 parent's completion.
150 parent's completion.
151 """
151 """
152
152
153 try:
153 try:
154 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
154 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
155 sys.ipcompleter = self.sys_ipcompleter_ori
155 sys.ipcompleter = self.sys_ipcompleter_ori
156 except:
156 except:
157 pass
157 pass
158
158
159 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
159 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
160 """Activate the interactive interpreter.
160 """Activate the interactive interpreter.
161
161
162 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
162 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
163 the interpreter shell with the given local and global namespaces, and
163 the interpreter shell with the given local and global namespaces, and
164 optionally print a header string at startup.
164 optionally print a header string at startup.
165
165
166 The shell can be globally activated/deactivated using the
166 The shell can be globally activated/deactivated using the
167 set/get_dummy_mode methods. This allows you to turn off a shell used
167 set/get_dummy_mode methods. This allows you to turn off a shell used
168 for debugging globally.
168 for debugging globally.
169
169
170 However, *each* time you call the shell you can override the current
170 However, *each* time you call the shell you can override the current
171 state of dummy_mode with the optional keyword parameter 'dummy'. For
171 state of dummy_mode with the optional keyword parameter 'dummy'. For
172 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
172 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
173 can still have a specific call work by making it as IPShell(dummy=0).
173 can still have a specific call work by making it as IPShell(dummy=0).
174
174
175 The optional keyword parameter dummy controls whether the call
175 The optional keyword parameter dummy controls whether the call
176 actually does anything. """
176 actually does anything. """
177
177
178 # Allow the dummy parameter to override the global __dummy_mode
178 # Allow the dummy parameter to override the global __dummy_mode
179 if dummy or (dummy != 0 and self.__dummy_mode):
179 if dummy or (dummy != 0 and self.__dummy_mode):
180 return
180 return
181
181
182 # Set global subsystems (display,completions) to our values
182 # Set global subsystems (display,completions) to our values
183 sys.displayhook = self.sys_displayhook_embed
183 sys.displayhook = self.sys_displayhook_embed
184 if self.IP.has_readline:
184 if self.IP.has_readline:
185 self.IP.readline.set_completer(self.IP.Completer.complete)
185 self.IP.readline.set_completer(self.IP.Completer.complete)
186
186
187 if self.banner and header:
187 if self.banner and header:
188 format = '%s\n%s\n'
188 format = '%s\n%s\n'
189 else:
189 else:
190 format = '%s%s\n'
190 format = '%s%s\n'
191 banner = format % (self.banner,header)
191 banner = format % (self.banner,header)
192
192
193 # Call the embedding code with a stack depth of 1 so it can skip over
193 # Call the embedding code with a stack depth of 1 so it can skip over
194 # our call and get the original caller's namespaces.
194 # our call and get the original caller's namespaces.
195 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
195 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
196
196
197 if self.exit_msg:
197 if self.exit_msg:
198 print self.exit_msg
198 print self.exit_msg
199
199
200 # Restore global systems (display, completion)
200 # Restore global systems (display, completion)
201 sys.displayhook = self.sys_displayhook_ori
201 sys.displayhook = self.sys_displayhook_ori
202 self.restore_system_completer()
202 self.restore_system_completer()
203
203
204 def set_dummy_mode(self,dummy):
204 def set_dummy_mode(self,dummy):
205 """Sets the embeddable shell's dummy mode parameter.
205 """Sets the embeddable shell's dummy mode parameter.
206
206
207 set_dummy_mode(dummy): dummy = 0 or 1.
207 set_dummy_mode(dummy): dummy = 0 or 1.
208
208
209 This parameter is persistent and makes calls to the embeddable shell
209 This parameter is persistent and makes calls to the embeddable shell
210 silently return without performing any action. This allows you to
210 silently return without performing any action. This allows you to
211 globally activate or deactivate a shell you're using with a single call.
211 globally activate or deactivate a shell you're using with a single call.
212
212
213 If you need to manually"""
213 If you need to manually"""
214
214
215 if dummy not in [0,1,False,True]:
215 if dummy not in [0,1,False,True]:
216 raise ValueError,'dummy parameter must be boolean'
216 raise ValueError,'dummy parameter must be boolean'
217 self.__dummy_mode = dummy
217 self.__dummy_mode = dummy
218
218
219 def get_dummy_mode(self):
219 def get_dummy_mode(self):
220 """Return the current value of the dummy mode parameter.
220 """Return the current value of the dummy mode parameter.
221 """
221 """
222 return self.__dummy_mode
222 return self.__dummy_mode
223
223
224 def set_banner(self,banner):
224 def set_banner(self,banner):
225 """Sets the global banner.
225 """Sets the global banner.
226
226
227 This banner gets prepended to every header printed when the shell
227 This banner gets prepended to every header printed when the shell
228 instance is called."""
228 instance is called."""
229
229
230 self.banner = banner
230 self.banner = banner
231
231
232 def set_exit_msg(self,exit_msg):
232 def set_exit_msg(self,exit_msg):
233 """Sets the global exit_msg.
233 """Sets the global exit_msg.
234
234
235 This exit message gets printed upon exiting every time the embedded
235 This exit message gets printed upon exiting every time the embedded
236 shell is called. It is None by default. """
236 shell is called. It is None by default. """
237
237
238 self.exit_msg = exit_msg
238 self.exit_msg = exit_msg
239
239
240 #-----------------------------------------------------------------------------
240 #-----------------------------------------------------------------------------
241 def sigint_handler (signum,stack_frame):
241 def sigint_handler (signum,stack_frame):
242 """Sigint handler for threaded apps.
242 """Sigint handler for threaded apps.
243
243
244 This is a horrible hack to pass information about SIGINT _without_ using
244 This is a horrible hack to pass information about SIGINT _without_ using
245 exceptions, since I haven't been able to properly manage cross-thread
245 exceptions, since I haven't been able to properly manage cross-thread
246 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
246 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
247 that's my understanding from a c.l.py thread where this was discussed)."""
247 that's my understanding from a c.l.py thread where this was discussed)."""
248
248
249 global KBINT
249 global KBINT
250
250
251 print '\nKeyboardInterrupt - Press <Enter> to continue.',
251 print '\nKeyboardInterrupt - Press <Enter> to continue.',
252 Term.cout.flush()
252 Term.cout.flush()
253 # Set global flag so that runsource can know that Ctrl-C was hit
253 # Set global flag so that runsource can know that Ctrl-C was hit
254 KBINT = True
254 KBINT = True
255
255
256 class MTInteractiveShell(InteractiveShell):
256 class MTInteractiveShell(InteractiveShell):
257 """Simple multi-threaded shell."""
257 """Simple multi-threaded shell."""
258
258
259 # Threading strategy taken from:
259 # Threading strategy taken from:
260 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
260 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
261 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
261 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
262 # from the pygtk mailing list, to avoid lockups with system calls.
262 # from the pygtk mailing list, to avoid lockups with system calls.
263
263
264 # class attribute to indicate whether the class supports threads or not.
264 # class attribute to indicate whether the class supports threads or not.
265 # Subclasses with thread support should override this as needed.
265 # Subclasses with thread support should override this as needed.
266 isthreaded = True
266 isthreaded = True
267
267
268 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
268 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
269 user_ns=None,user_global_ns=None,banner2='',**kw):
269 user_ns=None,user_global_ns=None,banner2='',**kw):
270 """Similar to the normal InteractiveShell, but with threading control"""
270 """Similar to the normal InteractiveShell, but with threading control"""
271
271
272 InteractiveShell.__init__(self,name,usage,rc,user_ns,
272 InteractiveShell.__init__(self,name,usage,rc,user_ns,
273 user_global_ns,banner2)
273 user_global_ns,banner2)
274
274
275 # Locking control variable
275 # Locking control variable
276 self.thread_ready = threading.Condition()
276 self.thread_ready = threading.Condition()
277
277
278 # Stuff to do at closing time
278 # Stuff to do at closing time
279 self._kill = False
279 self._kill = False
280 on_kill = kw.get('on_kill')
280 on_kill = kw.get('on_kill')
281 if on_kill is None:
281 if on_kill is None:
282 on_kill = []
282 on_kill = []
283 # Check that all things to kill are callable:
283 # Check that all things to kill are callable:
284 for t in on_kill:
284 for t in on_kill:
285 if not callable(t):
285 if not callable(t):
286 raise TypeError,'on_kill must be a list of callables'
286 raise TypeError,'on_kill must be a list of callables'
287 self.on_kill = on_kill
287 self.on_kill = on_kill
288
288
289 def runsource(self, source, filename="<input>", symbol="single"):
289 def runsource(self, source, filename="<input>", symbol="single"):
290 """Compile and run some source in the interpreter.
290 """Compile and run some source in the interpreter.
291
291
292 Modified version of code.py's runsource(), to handle threading issues.
292 Modified version of code.py's runsource(), to handle threading issues.
293 See the original for full docstring details."""
293 See the original for full docstring details."""
294
294
295 global KBINT
295 global KBINT
296
296
297 # If Ctrl-C was typed, we reset the flag and return right away
297 # If Ctrl-C was typed, we reset the flag and return right away
298 if KBINT:
298 if KBINT:
299 KBINT = False
299 KBINT = False
300 return False
300 return False
301
301
302 try:
302 try:
303 code = self.compile(source, filename, symbol)
303 code = self.compile(source, filename, symbol)
304 except (OverflowError, SyntaxError, ValueError):
304 except (OverflowError, SyntaxError, ValueError):
305 # Case 1
305 # Case 1
306 self.showsyntaxerror(filename)
306 self.showsyntaxerror(filename)
307 return False
307 return False
308
308
309 if code is None:
309 if code is None:
310 # Case 2
310 # Case 2
311 return True
311 return True
312
312
313 # Case 3
313 # Case 3
314 # Store code in self, so the execution thread can handle it
314 # Store code in self, so the execution thread can handle it
315 self.thread_ready.acquire()
315 self.thread_ready.acquire()
316 self.code_to_run = code
316 self.code_to_run = code
317 self.thread_ready.wait() # Wait until processed in timeout interval
317 self.thread_ready.wait() # Wait until processed in timeout interval
318 self.thread_ready.release()
318 self.thread_ready.release()
319
319
320 return False
320 return False
321
321
322 def runcode(self):
322 def runcode(self):
323 """Execute a code object.
323 """Execute a code object.
324
324
325 Multithreaded wrapper around IPython's runcode()."""
325 Multithreaded wrapper around IPython's runcode()."""
326
326
327 # lock thread-protected stuff
327 # lock thread-protected stuff
328 self.thread_ready.acquire()
328 self.thread_ready.acquire()
329
329
330 # Install sigint handler
330 # Install sigint handler
331 try:
331 try:
332 signal.signal(signal.SIGINT, sigint_handler)
332 signal.signal(signal.SIGINT, sigint_handler)
333 except SystemError:
333 except SystemError:
334 # This happens under Windows, which seems to have all sorts
334 # This happens under Windows, which seems to have all sorts
335 # of problems with signal handling. Oh well...
335 # of problems with signal handling. Oh well...
336 pass
336 pass
337
337
338 if self._kill:
338 if self._kill:
339 print >>Term.cout, 'Closing threads...',
339 print >>Term.cout, 'Closing threads...',
340 Term.cout.flush()
340 Term.cout.flush()
341 for tokill in self.on_kill:
341 for tokill in self.on_kill:
342 tokill()
342 tokill()
343 print >>Term.cout, 'Done.'
343 print >>Term.cout, 'Done.'
344
344
345 # Run pending code by calling parent class
345 # Run pending code by calling parent class
346 if self.code_to_run is not None:
346 if self.code_to_run is not None:
347 self.thread_ready.notify()
347 self.thread_ready.notify()
348 InteractiveShell.runcode(self,self.code_to_run)
348 InteractiveShell.runcode(self,self.code_to_run)
349
349
350 # We're done with thread-protected variables
350 # We're done with thread-protected variables
351 self.thread_ready.release()
351 self.thread_ready.release()
352 # This MUST return true for gtk threading to work
352 # This MUST return true for gtk threading to work
353 return True
353 return True
354
354
355 def kill (self):
355 def kill (self):
356 """Kill the thread, returning when it has been shut down."""
356 """Kill the thread, returning when it has been shut down."""
357 self.thread_ready.acquire()
357 self.thread_ready.acquire()
358 self._kill = True
358 self._kill = True
359 self.thread_ready.release()
359 self.thread_ready.release()
360
360
361 class MatplotlibShellBase:
361 class MatplotlibShellBase:
362 """Mixin class to provide the necessary modifications to regular IPython
362 """Mixin class to provide the necessary modifications to regular IPython
363 shell classes for matplotlib support.
363 shell classes for matplotlib support.
364
364
365 Given Python's MRO, this should be used as the FIRST class in the
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."""
366 inheritance hierarchy, so that it overrides the relevant methods."""
367
367
368 def _matplotlib_config(self,name):
368 def _matplotlib_config(self,name):
369 """Return various items needed to setup the user's shell with matplotlib"""
369 """Return various items needed to setup the user's shell with matplotlib"""
370
370
371 # Initialize matplotlib to interactive mode always
371 # Initialize matplotlib to interactive mode always
372 import matplotlib
372 import matplotlib
373 from matplotlib import backends
373 from matplotlib import backends
374 matplotlib.interactive(True)
374 matplotlib.interactive(True)
375
375
376 def use(arg):
376 def use(arg):
377 """IPython wrapper for matplotlib's backend switcher.
377 """IPython wrapper for matplotlib's backend switcher.
378
378
379 In interactive use, we can not allow switching to a different
379 In interactive use, we can not allow switching to a different
380 interactive backend, since thread conflicts will most likely crash
380 interactive backend, since thread conflicts will most likely crash
381 the python interpreter. This routine does a safety check first,
381 the python interpreter. This routine does a safety check first,
382 and refuses to perform a dangerous switch. It still allows
382 and refuses to perform a dangerous switch. It still allows
383 switching to non-interactive backends."""
383 switching to non-interactive backends."""
384
384
385 if arg in backends.interactive_bk and arg != self.mpl_backend:
385 if arg in backends.interactive_bk and arg != self.mpl_backend:
386 m=('invalid matplotlib backend switch.\n'
386 m=('invalid matplotlib backend switch.\n'
387 'This script attempted to switch to the interactive '
387 'This script attempted to switch to the interactive '
388 'backend: `%s`\n'
388 'backend: `%s`\n'
389 'Your current choice of interactive backend is: `%s`\n\n'
389 'Your current choice of interactive backend is: `%s`\n\n'
390 'Switching interactive matplotlib backends at runtime\n'
390 'Switching interactive matplotlib backends at runtime\n'
391 'would crash the python interpreter, '
391 'would crash the python interpreter, '
392 'and IPython has blocked it.\n\n'
392 'and IPython has blocked it.\n\n'
393 'You need to either change your choice of matplotlib backend\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'
394 'by editing your .matplotlibrc file, or run this script as a \n'
395 'standalone file from the command line, not using IPython.\n' %
395 'standalone file from the command line, not using IPython.\n' %
396 (arg,self.mpl_backend) )
396 (arg,self.mpl_backend) )
397 raise RuntimeError, m
397 raise RuntimeError, m
398 else:
398 else:
399 self.mpl_use(arg)
399 self.mpl_use(arg)
400 self.mpl_use._called = True
400 self.mpl_use._called = True
401
401
402 self.matplotlib = matplotlib
402 self.matplotlib = matplotlib
403 self.mpl_backend = matplotlib.rcParams['backend']
403 self.mpl_backend = matplotlib.rcParams['backend']
404
404
405 # we also need to block switching of interactive backends by use()
405 # we also need to block switching of interactive backends by use()
406 self.mpl_use = matplotlib.use
406 self.mpl_use = matplotlib.use
407 self.mpl_use._called = False
407 self.mpl_use._called = False
408 # overwrite the original matplotlib.use with our wrapper
408 # overwrite the original matplotlib.use with our wrapper
409 matplotlib.use = use
409 matplotlib.use = use
410
410
411
411
412 # This must be imported last in the matplotlib series, after
412 # This must be imported last in the matplotlib series, after
413 # backend/interactivity choices have been made
413 # backend/interactivity choices have been made
414 try:
414 try:
415 import matplotlib.pylab as pylab
415 import matplotlib.pylab as pylab
416 self.pylab = pylab
416 self.pylab = pylab
417 self.pylab_name = 'pylab'
417 self.pylab_name = 'pylab'
418 except ImportError:
418 except ImportError:
419 import matplotlib.matlab as matlab
419 import matplotlib.matlab as matlab
420 self.pylab = matlab
420 self.pylab = matlab
421 self.pylab_name = 'matlab'
421 self.pylab_name = 'matlab'
422
422
423 self.pylab.show._needmain = False
423 self.pylab.show._needmain = False
424 # We need to detect at runtime whether show() is called by the user.
424 # We need to detect at runtime whether show() is called by the user.
425 # For this, we wrap it into a decorator which adds a 'called' flag.
425 # For this, we wrap it into a decorator which adds a 'called' flag.
426 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
426 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
427
427
428 # Build a user namespace initialized with matplotlib/matlab features.
428 # Build a user namespace initialized with matplotlib/matlab features.
429 user_ns = {'__name__':'__main__',
429 user_ns = {'__name__':'__main__',
430 '__builtins__' : __builtin__ }
430 '__builtins__' : __builtin__ }
431
431
432 # Be careful not to remove the final \n in the code string below, or
432 # Be careful not to remove the final \n in the code string below, or
433 # things will break badly with py22 (I think it's a python bug, 2.3 is
433 # things will break badly with py22 (I think it's a python bug, 2.3 is
434 # OK).
434 # OK).
435 pname = self.pylab_name # Python can't interpolate dotted var names
435 pname = self.pylab_name # Python can't interpolate dotted var names
436 exec ("import matplotlib\n"
436 exec ("import matplotlib\n"
437 "import matplotlib.%(pname)s as %(pname)s\n"
437 "import matplotlib.%(pname)s as %(pname)s\n"
438 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
438 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
439
439
440 # Build matplotlib info banner
440 # Build matplotlib info banner
441 b="""
441 b="""
442 Welcome to pylab, a matplotlib-based Python environment.
442 Welcome to pylab, a matplotlib-based Python environment.
443 For more information, type 'help(pylab)'.
443 For more information, type 'help(pylab)'.
444 """
444 """
445 return user_ns,b
445 return user_ns,b
446
446
447 def mplot_exec(self,fname,*where,**kw):
447 def mplot_exec(self,fname,*where,**kw):
448 """Execute a matplotlib script.
448 """Execute a matplotlib script.
449
449
450 This is a call to execfile(), but wrapped in safeties to properly
450 This is a call to execfile(), but wrapped in safeties to properly
451 handle interactive rendering and backend switching."""
451 handle interactive rendering and backend switching."""
452
452
453 #print '*** Matplotlib runner ***' # dbg
453 #print '*** Matplotlib runner ***' # dbg
454 # turn off rendering until end of script
454 # turn off rendering until end of script
455 isInteractive = self.matplotlib.rcParams['interactive']
455 isInteractive = self.matplotlib.rcParams['interactive']
456 self.matplotlib.interactive(False)
456 self.matplotlib.interactive(False)
457 self.safe_execfile(fname,*where,**kw)
457 self.safe_execfile(fname,*where,**kw)
458 self.matplotlib.interactive(isInteractive)
458 self.matplotlib.interactive(isInteractive)
459 # make rendering call now, if the user tried to do it
459 # make rendering call now, if the user tried to do it
460 if self.pylab.draw_if_interactive.called:
460 if self.pylab.draw_if_interactive.called:
461 self.pylab.draw()
461 self.pylab.draw()
462 self.pylab.draw_if_interactive.called = False
462 self.pylab.draw_if_interactive.called = False
463
463
464 # if a backend switch was performed, reverse it now
464 # if a backend switch was performed, reverse it now
465 if self.mpl_use._called:
465 if self.mpl_use._called:
466 self.matplotlib.rcParams['backend'] = self.mpl_backend
466 self.matplotlib.rcParams['backend'] = self.mpl_backend
467
467
468 def magic_run(self,parameter_s=''):
468 def magic_run(self,parameter_s=''):
469 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
469 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
470
470
471 # Fix the docstring so users see the original as well
471 # Fix the docstring so users see the original as well
472 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
472 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
473 "\n *** Modified %run for Matplotlib,"
473 "\n *** Modified %run for Matplotlib,"
474 " with proper interactive handling ***")
474 " with proper interactive handling ***")
475
475
476 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
476 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
477 # and multithreaded. Note that these are meant for internal use, the IPShell*
477 # and multithreaded. Note that these are meant for internal use, the IPShell*
478 # classes below are the ones meant for public consumption.
478 # classes below are the ones meant for public consumption.
479
479
480 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
480 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
481 """Single-threaded shell with matplotlib support."""
481 """Single-threaded shell with matplotlib support."""
482
482
483 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
483 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
484 user_ns=None,user_global_ns=None,**kw):
484 user_ns=None,user_global_ns=None,**kw):
485 user_ns,b2 = self._matplotlib_config(name)
485 user_ns,b2 = self._matplotlib_config(name)
486 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
486 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
487 banner2=b2,**kw)
487 banner2=b2,**kw)
488
488
489 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
489 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
490 """Multi-threaded shell with matplotlib support."""
490 """Multi-threaded shell with matplotlib support."""
491
491
492 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
492 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
493 user_ns=None,user_global_ns=None, **kw):
493 user_ns=None,user_global_ns=None, **kw):
494 user_ns,b2 = self._matplotlib_config(name)
494 user_ns,b2 = self._matplotlib_config(name)
495 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
495 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
496 banner2=b2,**kw)
496 banner2=b2,**kw)
497
497
498 #-----------------------------------------------------------------------------
498 #-----------------------------------------------------------------------------
499 # Utility functions for the different GUI enabled IPShell* classes.
499 # Utility functions for the different GUI enabled IPShell* classes.
500
500
501 def get_tk():
501 def get_tk():
502 """Tries to import Tkinter and returns a withdrawn Tkinter root
502 """Tries to import Tkinter and returns a withdrawn Tkinter root
503 window. If Tkinter is already imported or not available, this
503 window. If Tkinter is already imported or not available, this
504 returns None. This function calls `hijack_tk` underneath.
504 returns None. This function calls `hijack_tk` underneath.
505 """
505 """
506 if not USE_TK or sys.modules.has_key('Tkinter'):
506 if not USE_TK or sys.modules.has_key('Tkinter'):
507 return None
507 return None
508 else:
508 else:
509 try:
509 try:
510 import Tkinter
510 import Tkinter
511 except ImportError:
511 except ImportError:
512 return None
512 return None
513 else:
513 else:
514 hijack_tk()
514 hijack_tk()
515 r = Tkinter.Tk()
515 r = Tkinter.Tk()
516 r.withdraw()
516 r.withdraw()
517 return r
517 return r
518
518
519 def hijack_tk():
519 def hijack_tk():
520 """Modifies Tkinter's mainloop with a dummy so when a module calls
520 """Modifies Tkinter's mainloop with a dummy so when a module calls
521 mainloop, it does not block.
521 mainloop, it does not block.
522
522
523 """
523 """
524 def misc_mainloop(self, n=0):
524 def misc_mainloop(self, n=0):
525 pass
525 pass
526 def tkinter_mainloop(n=0):
526 def tkinter_mainloop(n=0):
527 pass
527 pass
528
528
529 import Tkinter
529 import Tkinter
530 Tkinter.Misc.mainloop = misc_mainloop
530 Tkinter.Misc.mainloop = misc_mainloop
531 Tkinter.mainloop = tkinter_mainloop
531 Tkinter.mainloop = tkinter_mainloop
532
532
533 def update_tk(tk):
533 def update_tk(tk):
534 """Updates the Tkinter event loop. This is typically called from
534 """Updates the Tkinter event loop. This is typically called from
535 the respective WX or GTK mainloops.
535 the respective WX or GTK mainloops.
536 """
536 """
537 if tk:
537 if tk:
538 tk.update()
538 tk.update()
539
539
540 def hijack_wx():
540 def hijack_wx():
541 """Modifies wxPython's MainLoop with a dummy so user code does not
541 """Modifies wxPython's MainLoop with a dummy so user code does not
542 block IPython. The hijacked mainloop function is returned.
542 block IPython. The hijacked mainloop function is returned.
543 """
543 """
544 def dummy_mainloop(*args, **kw):
544 def dummy_mainloop(*args, **kw):
545 pass
545 pass
546 import wxPython
546 import wxPython
547 ver = wxPython.__version__
547 ver = wxPython.__version__
548 orig_mainloop = None
548 orig_mainloop = None
549 if ver[:3] >= '2.5':
549 if ver[:3] >= '2.5':
550 import wx
550 import wx
551 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
551 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
552 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
552 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
553 else: raise AttributeError('Could not find wx core module')
553 else: raise AttributeError('Could not find wx core module')
554 orig_mainloop = core.PyApp_MainLoop
554 orig_mainloop = core.PyApp_MainLoop
555 core.PyApp_MainLoop = dummy_mainloop
555 core.PyApp_MainLoop = dummy_mainloop
556 elif ver[:3] == '2.4':
556 elif ver[:3] == '2.4':
557 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
557 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
558 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
558 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
559 else:
559 else:
560 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
560 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
561 return orig_mainloop
561 return orig_mainloop
562
562
563 def hijack_gtk():
563 def hijack_gtk():
564 """Modifies pyGTK's mainloop with a dummy so user code does not
564 """Modifies pyGTK's mainloop with a dummy so user code does not
565 block IPython. This function returns the original `gtk.mainloop`
565 block IPython. This function returns the original `gtk.mainloop`
566 function that has been hijacked.
566 function that has been hijacked.
567 """
567 """
568 def dummy_mainloop(*args, **kw):
568 def dummy_mainloop(*args, **kw):
569 pass
569 pass
570 import gtk
570 import gtk
571 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
571 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
572 else: orig_mainloop = gtk.mainloop
572 else: orig_mainloop = gtk.mainloop
573 gtk.mainloop = dummy_mainloop
573 gtk.mainloop = dummy_mainloop
574 gtk.main = dummy_mainloop
574 gtk.main = dummy_mainloop
575 return orig_mainloop
575 return orig_mainloop
576
576
577 #-----------------------------------------------------------------------------
577 #-----------------------------------------------------------------------------
578 # The IPShell* classes below are the ones meant to be run by external code as
578 # The IPShell* classes below are the ones meant to be run by external code as
579 # IPython instances. Note that unless a specific threading strategy is
579 # IPython instances. Note that unless a specific threading strategy is
580 # desired, the factory function start() below should be used instead (it
580 # desired, the factory function start() below should be used instead (it
581 # selects the proper threaded class).
581 # selects the proper threaded class).
582
582
583 class IPShellGTK(threading.Thread):
583 class IPShellGTK(threading.Thread):
584 """Run a gtk mainloop() in a separate thread.
584 """Run a gtk mainloop() in a separate thread.
585
585
586 Python commands can be passed to the thread where they will be executed.
586 Python commands can be passed to the thread where they will be executed.
587 This is implemented by periodically checking for passed code using a
587 This is implemented by periodically checking for passed code using a
588 GTK timeout callback."""
588 GTK timeout callback."""
589
589
590 TIMEOUT = 100 # Millisecond interval between timeouts.
590 TIMEOUT = 100 # Millisecond interval between timeouts.
591
591
592 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
592 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
593 debug=1,shell_class=MTInteractiveShell):
593 debug=1,shell_class=MTInteractiveShell):
594
594
595 import gtk
595 import gtk
596
596
597 self.gtk = gtk
597 self.gtk = gtk
598 self.gtk_mainloop = hijack_gtk()
598 self.gtk_mainloop = hijack_gtk()
599
599
600 # Allows us to use both Tk and GTK.
600 # Allows us to use both Tk and GTK.
601 self.tk = get_tk()
601 self.tk = get_tk()
602
602
603 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
603 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
604 else: mainquit = self.gtk.mainquit
604 else: mainquit = self.gtk.mainquit
605
605
606 self.IP = make_IPython(argv,user_ns=user_ns,
606 self.IP = make_IPython(argv,user_ns=user_ns,
607 user_global_ns=user_global_ns,
607 user_global_ns=user_global_ns,
608 debug=debug,
608 debug=debug,
609 shell_class=shell_class,
609 shell_class=shell_class,
610 on_kill=[mainquit])
610 on_kill=[mainquit])
611
611
612 # HACK: slot for banner in self; it will be passed to the mainloop
612 # HACK: slot for banner in self; it will be passed to the mainloop
613 # method only and .run() needs it. The actual value will be set by
613 # method only and .run() needs it. The actual value will be set by
614 # .mainloop().
614 # .mainloop().
615 self._banner = None
615 self._banner = None
616
616
617 threading.Thread.__init__(self)
617 threading.Thread.__init__(self)
618
618
619 def run(self):
619 def run(self):
620 self.IP.mainloop(self._banner)
620 self.IP.mainloop(self._banner)
621 self.IP.kill()
621 self.IP.kill()
622
622
623 def mainloop(self,sys_exit=0,banner=None):
623 def mainloop(self,sys_exit=0,banner=None):
624
624
625 self._banner = banner
625 self._banner = banner
626
626
627 if self.gtk.pygtk_version >= (2,4,0):
627 if self.gtk.pygtk_version >= (2,4,0):
628 import gobject
628 import gobject
629 gobject.idle_add(self.on_timer)
629 gobject.idle_add(self.on_timer)
630 else:
630 else:
631 self.gtk.idle_add(self.on_timer)
631 self.gtk.idle_add(self.on_timer)
632
632
633 if sys.platform != 'win32':
633 if sys.platform != 'win32':
634 try:
634 try:
635 if self.gtk.gtk_version[0] >= 2:
635 if self.gtk.gtk_version[0] >= 2:
636 self.gtk.threads_init()
636 self.gtk.threads_init()
637 except AttributeError:
637 except AttributeError:
638 pass
638 pass
639 except RuntimeError:
639 except RuntimeError:
640 error('Your pyGTK likely has not been compiled with '
640 error('Your pyGTK likely has not been compiled with '
641 'threading support.\n'
641 'threading support.\n'
642 'The exception printout is below.\n'
642 'The exception printout is below.\n'
643 'You can either rebuild pyGTK with threads, or '
643 'You can either rebuild pyGTK with threads, or '
644 'try using \n'
644 'try using \n'
645 'matplotlib with a different backend (like Tk or WX).\n'
645 'matplotlib with a different backend (like Tk or WX).\n'
646 'Note that matplotlib will most likely not work in its '
646 'Note that matplotlib will most likely not work in its '
647 'current state!')
647 'current state!')
648 self.IP.InteractiveTB()
648 self.IP.InteractiveTB()
649 self.start()
649 self.start()
650 self.gtk.threads_enter()
650 self.gtk.threads_enter()
651 self.gtk_mainloop()
651 self.gtk_mainloop()
652 self.gtk.threads_leave()
652 self.gtk.threads_leave()
653 self.join()
653 self.join()
654
654
655 def on_timer(self):
655 def on_timer(self):
656 """Called when GTK is idle.
656 """Called when GTK is idle.
657
657
658 Must return True always, otherwise GTK stops calling it"""
658 Must return True always, otherwise GTK stops calling it"""
659
659
660 update_tk(self.tk)
660 update_tk(self.tk)
661 self.IP.runcode()
661 self.IP.runcode()
662 time.sleep(0.01)
662 time.sleep(0.01)
663 return True
663 return True
664
664
665 class IPShellWX(threading.Thread):
665 class IPShellWX(threading.Thread):
666 """Run a wx mainloop() in a separate thread.
666 """Run a wx mainloop() in a separate thread.
667
667
668 Python commands can be passed to the thread where they will be executed.
668 Python commands can be passed to the thread where they will be executed.
669 This is implemented by periodically checking for passed code using a
669 This is implemented by periodically checking for passed code using a
670 GTK timeout callback."""
670 GTK timeout callback."""
671
671
672 TIMEOUT = 100 # Millisecond interval between timeouts.
672 TIMEOUT = 100 # Millisecond interval between timeouts.
673
673
674 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
674 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
675 debug=1,shell_class=MTInteractiveShell):
675 debug=1,shell_class=MTInteractiveShell):
676
676
677 self.IP = make_IPython(argv,user_ns=user_ns,
677 self.IP = make_IPython(argv,user_ns=user_ns,
678 user_global_ns=user_global_ns,
678 user_global_ns=user_global_ns,
679 debug=debug,
679 debug=debug,
680 shell_class=shell_class,
680 shell_class=shell_class,
681 on_kill=[self.wxexit])
681 on_kill=[self.wxexit])
682
682
683 wantedwxversion=self.IP.rc.wxversion
683 wantedwxversion=self.IP.rc.wxversion
684 if wantedwxversion!="0":
684 if wantedwxversion!="0":
685 try:
685 try:
686 import wxversion
686 import wxversion
687 except ImportError:
687 except ImportError:
688 error('The wxversion module is needed for WX version selection')
688 error('The wxversion module is needed for WX version selection')
689 else:
689 else:
690 try:
690 try:
691 wxversion.select(wantedwxversion)
691 wxversion.select(wantedwxversion)
692 except:
692 except:
693 self.IP.InteractiveTB()
693 self.IP.InteractiveTB()
694 error('Requested wxPython version %s could not be loaded' %
694 error('Requested wxPython version %s could not be loaded' %
695 wantedwxversion)
695 wantedwxversion)
696
696
697 import wxPython.wx as wx
697 import wxPython.wx as wx
698
698
699 threading.Thread.__init__(self)
699 threading.Thread.__init__(self)
700 self.wx = wx
700 self.wx = wx
701 self.wx_mainloop = hijack_wx()
701 self.wx_mainloop = hijack_wx()
702
702
703 # Allows us to use both Tk and GTK.
703 # Allows us to use both Tk and GTK.
704 self.tk = get_tk()
704 self.tk = get_tk()
705
705
706
706
707 # HACK: slot for banner in self; it will be passed to the mainloop
707 # HACK: slot for banner in self; it will be passed to the mainloop
708 # method only and .run() needs it. The actual value will be set by
708 # method only and .run() needs it. The actual value will be set by
709 # .mainloop().
709 # .mainloop().
710 self._banner = None
710 self._banner = None
711
711
712 self.app = None
712 self.app = None
713
713
714 def wxexit(self, *args):
714 def wxexit(self, *args):
715 if self.app is not None:
715 if self.app is not None:
716 self.app.agent.timer.Stop()
716 self.app.agent.timer.Stop()
717 self.app.ExitMainLoop()
717 self.app.ExitMainLoop()
718
718
719 def run(self):
719 def run(self):
720 self.IP.mainloop(self._banner)
720 self.IP.mainloop(self._banner)
721 self.IP.kill()
721 self.IP.kill()
722
722
723 def mainloop(self,sys_exit=0,banner=None):
723 def mainloop(self,sys_exit=0,banner=None):
724
724
725 self._banner = banner
725 self._banner = banner
726
726
727 self.start()
727 self.start()
728
728
729 class TimerAgent(self.wx.wxMiniFrame):
729 class TimerAgent(self.wx.wxMiniFrame):
730 wx = self.wx
730 wx = self.wx
731 IP = self.IP
731 IP = self.IP
732 tk = self.tk
732 tk = self.tk
733 def __init__(self, parent, interval):
733 def __init__(self, parent, interval):
734 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
734 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
735 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
735 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
736 size=(100, 100),style=style)
736 size=(100, 100),style=style)
737 self.Show(False)
737 self.Show(False)
738 self.interval = interval
738 self.interval = interval
739 self.timerId = self.wx.wxNewId()
739 self.timerId = self.wx.wxNewId()
740
740
741 def StartWork(self):
741 def StartWork(self):
742 self.timer = self.wx.wxTimer(self, self.timerId)
742 self.timer = self.wx.wxTimer(self, self.timerId)
743 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
743 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
744 self.timer.Start(self.interval)
744 self.timer.Start(self.interval)
745
745
746 def OnTimer(self, event):
746 def OnTimer(self, event):
747 update_tk(self.tk)
747 update_tk(self.tk)
748 self.IP.runcode()
748 self.IP.runcode()
749
749
750 class App(self.wx.wxApp):
750 class App(self.wx.wxApp):
751 wx = self.wx
751 wx = self.wx
752 TIMEOUT = self.TIMEOUT
752 TIMEOUT = self.TIMEOUT
753 def OnInit(self):
753 def OnInit(self):
754 'Create the main window and insert the custom frame'
754 'Create the main window and insert the custom frame'
755 self.agent = TimerAgent(None, self.TIMEOUT)
755 self.agent = TimerAgent(None, self.TIMEOUT)
756 self.agent.Show(self.wx.false)
756 self.agent.Show(self.wx.false)
757 self.agent.StartWork()
757 self.agent.StartWork()
758 return self.wx.true
758 return self.wx.true
759
759
760 self.app = App(redirect=False)
760 self.app = App(redirect=False)
761 self.wx_mainloop(self.app)
761 self.wx_mainloop(self.app)
762 self.join()
762 self.join()
763
763
764
764
765 class IPShellQt(threading.Thread):
765 class IPShellQt(threading.Thread):
766 """Run a Qt event loop in a separate thread.
766 """Run a Qt event loop in a separate thread.
767
767
768 Python commands can be passed to the thread where they will be executed.
768 Python commands can be passed to the thread where they will be executed.
769 This is implemented by periodically checking for passed code using a
769 This is implemented by periodically checking for passed code using a
770 Qt timer / slot."""
770 Qt timer / slot."""
771
771
772 TIMEOUT = 100 # Millisecond interval between timeouts.
772 TIMEOUT = 100 # Millisecond interval between timeouts.
773
773
774 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
774 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
775 debug=0,shell_class=MTInteractiveShell):
775 debug=0,shell_class=MTInteractiveShell):
776
776
777 import qt
777 import qt
778
778
779 class newQApplication:
779 class newQApplication:
780 def __init__( self ):
780 def __init__( self ):
781 self.QApplication = qt.QApplication
781 self.QApplication = qt.QApplication
782
782
783 def __call__( *args, **kwargs ):
783 def __call__( *args, **kwargs ):
784 return qt.qApp
784 return qt.qApp
785
785
786 def exec_loop( *args, **kwargs ):
786 def exec_loop( *args, **kwargs ):
787 pass
787 pass
788
788
789 def __getattr__( self, name ):
789 def __getattr__( self, name ):
790 return getattr( self.QApplication, name )
790 return getattr( self.QApplication, name )
791
791
792 qt.QApplication = newQApplication()
792 qt.QApplication = newQApplication()
793
793
794 # Allows us to use both Tk and QT.
794 # Allows us to use both Tk and QT.
795 self.tk = get_tk()
795 self.tk = get_tk()
796
796
797 self.IP = make_IPython(argv,user_ns=user_ns,
797 self.IP = make_IPython(argv,user_ns=user_ns,
798 user_global_ns=user_global_ns,
798 user_global_ns=user_global_ns,
799 debug=debug,
799 debug=debug,
800 shell_class=shell_class,
800 shell_class=shell_class,
801 on_kill=[qt.qApp.exit])
801 on_kill=[qt.qApp.exit])
802
802
803 # HACK: slot for banner in self; it will be passed to the mainloop
803 # HACK: slot for banner in self; it will be passed to the mainloop
804 # method only and .run() needs it. The actual value will be set by
804 # method only and .run() needs it. The actual value will be set by
805 # .mainloop().
805 # .mainloop().
806 self._banner = None
806 self._banner = None
807
807
808 threading.Thread.__init__(self)
808 threading.Thread.__init__(self)
809
809
810 def run(self):
810 def run(self):
811 self.IP.mainloop(self._banner)
811 self.IP.mainloop(self._banner)
812 self.IP.kill()
812 self.IP.kill()
813
813
814 def mainloop(self,sys_exit=0,banner=None):
814 def mainloop(self,sys_exit=0,banner=None):
815
815
816 import qt
816 import qt
817
817
818 self._banner = banner
818 self._banner = banner
819
819
820 if qt.QApplication.startingUp():
820 if qt.QApplication.startingUp():
821 a = qt.QApplication.QApplication(sys.argv)
821 a = qt.QApplication.QApplication(sys.argv)
822 self.timer = qt.QTimer()
822 self.timer = qt.QTimer()
823 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
823 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
824
824
825 self.start()
825 self.start()
826 self.timer.start( self.TIMEOUT, True )
826 self.timer.start( self.TIMEOUT, True )
827 while True:
827 while True:
828 if self.IP._kill: break
828 if self.IP._kill: break
829 qt.qApp.exec_loop()
829 qt.qApp.exec_loop()
830 self.join()
830 self.join()
831
831
832 def on_timer(self):
832 def on_timer(self):
833 update_tk(self.tk)
833 update_tk(self.tk)
834 result = self.IP.runcode()
834 result = self.IP.runcode()
835 self.timer.start( self.TIMEOUT, True )
835 self.timer.start( self.TIMEOUT, True )
836 return result
836 return result
837
837
838 # A set of matplotlib public IPython shell classes, for single-threaded
838 # A set of matplotlib public IPython shell classes, for single-threaded
839 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
839 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
840 class IPShellMatplotlib(IPShell):
840 class IPShellMatplotlib(IPShell):
841 """Subclass IPShell with MatplotlibShell as the internal shell.
841 """Subclass IPShell with MatplotlibShell as the internal shell.
842
842
843 Single-threaded class, meant for the Tk* and FLTK* backends.
843 Single-threaded class, meant for the Tk* and FLTK* backends.
844
844
845 Having this on a separate class simplifies the external driver code."""
845 Having this on a separate class simplifies the external driver code."""
846
846
847 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
847 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
848 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
848 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
849 shell_class=MatplotlibShell)
849 shell_class=MatplotlibShell)
850
850
851 class IPShellMatplotlibGTK(IPShellGTK):
851 class IPShellMatplotlibGTK(IPShellGTK):
852 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
852 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
853
853
854 Multi-threaded class, meant for the GTK* backends."""
854 Multi-threaded class, meant for the GTK* backends."""
855
855
856 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
856 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
857 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
857 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
858 shell_class=MatplotlibMTShell)
858 shell_class=MatplotlibMTShell)
859
859
860 class IPShellMatplotlibWX(IPShellWX):
860 class IPShellMatplotlibWX(IPShellWX):
861 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
861 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
862
862
863 Multi-threaded class, meant for the WX* backends."""
863 Multi-threaded class, meant for the WX* backends."""
864
864
865 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
865 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
866 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
866 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
867 shell_class=MatplotlibMTShell)
867 shell_class=MatplotlibMTShell)
868
868
869 class IPShellMatplotlibQt(IPShellQt):
869 class IPShellMatplotlibQt(IPShellQt):
870 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
870 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
871
871
872 Multi-threaded class, meant for the Qt* backends."""
872 Multi-threaded class, meant for the Qt* backends."""
873
873
874 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
874 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
875 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
875 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
876 shell_class=MatplotlibMTShell)
876 shell_class=MatplotlibMTShell)
877
877
878 #-----------------------------------------------------------------------------
878 #-----------------------------------------------------------------------------
879 # Factory functions to actually start the proper thread-aware shell
879 # Factory functions to actually start the proper thread-aware shell
880
880
881 def _matplotlib_shell_class():
881 def _matplotlib_shell_class():
882 """Factory function to handle shell class selection for matplotlib.
882 """Factory function to handle shell class selection for matplotlib.
883
883
884 The proper shell class to use depends on the matplotlib backend, since
884 The proper shell class to use depends on the matplotlib backend, since
885 each backend requires a different threading strategy."""
885 each backend requires a different threading strategy."""
886
886
887 try:
887 try:
888 import matplotlib
888 import matplotlib
889 except ImportError:
889 except ImportError:
890 error('matplotlib could NOT be imported! Starting normal IPython.')
890 error('matplotlib could NOT be imported! Starting normal IPython.')
891 sh_class = IPShell
891 sh_class = IPShell
892 else:
892 else:
893 backend = matplotlib.rcParams['backend']
893 backend = matplotlib.rcParams['backend']
894 if backend.startswith('GTK'):
894 if backend.startswith('GTK'):
895 sh_class = IPShellMatplotlibGTK
895 sh_class = IPShellMatplotlibGTK
896 elif backend.startswith('WX'):
896 elif backend.startswith('WX'):
897 sh_class = IPShellMatplotlibWX
897 sh_class = IPShellMatplotlibWX
898 elif backend.startswith('Qt'):
898 elif backend.startswith('Qt'):
899 sh_class = IPShellMatplotlibQt
899 sh_class = IPShellMatplotlibQt
900 else:
900 else:
901 sh_class = IPShellMatplotlib
901 sh_class = IPShellMatplotlib
902 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
902 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
903 return sh_class
903 return sh_class
904
904
905 # This is the one which should be called by external code.
905 # This is the one which should be called by external code.
906 def start():
906 def start():
907 """Return a running shell instance, dealing with threading options.
907 """Return a running shell instance, dealing with threading options.
908
908
909 This is a factory function which will instantiate the proper IPython shell
909 This is a factory function which will instantiate the proper IPython shell
910 based on the user's threading choice. Such a selector is needed because
910 based on the user's threading choice. Such a selector is needed because
911 different GUI toolkits require different thread handling details."""
911 different GUI toolkits require different thread handling details."""
912
912
913 global USE_TK
913 global USE_TK
914 # Crude sys.argv hack to extract the threading options.
914 # Crude sys.argv hack to extract the threading options.
915 argv = sys.argv
915 argv = sys.argv
916 if len(argv) > 1:
916 if len(argv) > 1:
917 if len(argv) > 2:
917 if len(argv) > 2:
918 arg2 = argv[2]
918 arg2 = argv[2]
919 if arg2.endswith('-tk'):
919 if arg2.endswith('-tk'):
920 USE_TK = True
920 USE_TK = True
921 arg1 = argv[1]
921 arg1 = argv[1]
922 if arg1.endswith('-gthread'):
922 if arg1.endswith('-gthread'):
923 shell = IPShellGTK
923 shell = IPShellGTK
924 elif arg1.endswith( '-qthread' ):
924 elif arg1.endswith( '-qthread' ):
925 shell = IPShellQt
925 shell = IPShellQt
926 elif arg1.endswith('-wthread'):
926 elif arg1.endswith('-wthread'):
927 shell = IPShellWX
927 shell = IPShellWX
928 elif arg1.endswith('-pylab'):
928 elif arg1.endswith('-pylab'):
929 shell = _matplotlib_shell_class()
929 shell = _matplotlib_shell_class()
930 else:
930 else:
931 shell = IPShell
931 shell = IPShell
932 else:
932 else:
933 shell = IPShell
933 shell = IPShell
934 return shell()
934 return shell()
935
935
936 # Some aliases for backwards compatibility
936 # Some aliases for backwards compatibility
937 IPythonShell = IPShell
937 IPythonShell = IPShell
938 IPythonShellEmbed = IPShellEmbed
938 IPythonShellEmbed = IPShellEmbed
939 #************************ End of file <Shell.py> ***************************
939 #************************ End of file <Shell.py> ***************************
@@ -1,64 +1,64 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 One of Python's nicest features is its interactive interpreter. This allows
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
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
7 typical in most programming languages. However, the interpreter supplied with
8 the standard Python distribution is fairly primitive (and IDLE isn't really
8 the standard Python distribution is fairly primitive (and IDLE isn't really
9 much better).
9 much better).
10
10
11 IPython tries to:
11 IPython tries to:
12
12
13 i - provide an efficient environment for interactive work in Python
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
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
15 Python prompt, and adds many features to make interactive work much more
16 efficient.
16 efficient.
17
17
18 ii - offer a flexible framework so that it can be used as the base
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
19 environment for other projects and problems where Python can be the
20 underlying language. Specifically scientific environments like Mathematica,
20 underlying language. Specifically scientific environments like Mathematica,
21 IDL and Mathcad inspired its design, but similar ideas can be useful in many
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
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
23 (due to its dynamic and introspective features), and with suitable libraries
24 entire systems could be built leveraging Python's power.
24 entire systems could be built leveraging Python's power.
25
25
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
27
27
28 IPython requires Python 2.2 or newer.
28 IPython requires Python 2.2 or newer.
29
29
30 $Id: __init__.py 998 2006-01-09 06:57:40Z fperez $"""
30 $Id: __init__.py 1005 2006-01-12 08:39:26Z fperez $"""
31
31
32 #*****************************************************************************
32 #*****************************************************************************
33 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
33 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
34 #
34 #
35 # Distributed under the terms of the BSD License. The full license is in
35 # Distributed under the terms of the BSD License. The full license is in
36 # the file COPYING, distributed as part of this software.
36 # the file COPYING, distributed as part of this software.
37 #*****************************************************************************
37 #*****************************************************************************
38
38
39 # Enforce proper version requirements
39 # Enforce proper version requirements
40 import sys
40 import sys
41 if sys.version[0:3] < '2.3':
41 if sys.version[0:3] < '2.3':
42 raise ImportError, 'Python Version 2.3 or above is required.'
42 raise ImportError, 'Python Version 2.3 or above is required.'
43
43
44 # Define what gets imported with a 'from IPython import *'
44 # Define what gets imported with a 'from IPython import *'
45 __all__ = ['deep_reload','genutils','ultraTB','DPyGetOpt','Itpl','hooks',
45 __all__ = ['deep_reload','genutils','ipstruct','ultraTB','DPyGetOpt',
46 'ConfigLoader','OutputTrap','Release','Struct','Shell']
46 'Itpl','hooks','ConfigLoader','OutputTrap','Release','Shell']
47
47
48 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
48 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
49 # access to them via IPython.<name>
49 # access to them via IPython.<name>
50 glob,loc = globals(),locals()
50 glob,loc = globals(),locals()
51 for name in __all__:
51 for name in __all__:
52 __import__(name,glob,loc,[])
52 __import__(name,glob,loc,[])
53
53
54 # Release data
54 # Release data
55 from IPython import Release # do it explicitly so pydoc can see it - pydoc bug
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>' % \
56 __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
57 ( Release.authors['Fernando'] + Release.authors['Janko'] + \
57 ( Release.authors['Fernando'] + Release.authors['Janko'] + \
58 Release.authors['Nathan'] )
58 Release.authors['Nathan'] )
59 __license__ = Release.license
59 __license__ = Release.license
60 __version__ = Release.version
60 __version__ = Release.version
61 __revision__ = Release.revision
61 __revision__ = Release.revision
62
62
63 # Namespace cleanup
63 # Namespace cleanup
64 del name,glob,loc
64 del name,glob,loc
@@ -1,2165 +1,2165 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or newer.
5 Requires Python 2.1 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 1002 2006-01-11 22:18:29Z fperez $
9 $Id: iplib.py 1005 2006-01-12 08:39:26Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import tempfile
58 import tempfile
59 import traceback
59 import traceback
60 import types
60 import types
61
61
62 from pprint import pprint, pformat
62 from pprint import pprint, pformat
63
63
64 # IPython's own modules
64 # IPython's own modules
65 import IPython
65 import IPython
66 from IPython import OInspect,PyColorize,ultraTB
66 from IPython import OInspect,PyColorize,ultraTB
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 from IPython.FakeModule import FakeModule
68 from IPython.FakeModule import FakeModule
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 from IPython.Logger import Logger
70 from IPython.Logger import Logger
71 from IPython.Magic import Magic
71 from IPython.Magic import Magic
72 from IPython.Prompts import CachedOutput
72 from IPython.Prompts import CachedOutput
73 from IPython.Struct import Struct
73 from IPython.ipstruct import Struct
74 from IPython.background_jobs import BackgroundJobManager
74 from IPython.background_jobs import BackgroundJobManager
75 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.usage import cmd_line_usage,interactive_usage
76 from IPython.genutils import *
76 from IPython.genutils import *
77
77
78 # Globals
78 # Globals
79
79
80 # store the builtin raw_input globally, and use this always, in case user code
80 # store the builtin raw_input globally, and use this always, in case user code
81 # overwrites it (like wx.py.PyShell does)
81 # overwrites it (like wx.py.PyShell does)
82 raw_input_original = raw_input
82 raw_input_original = raw_input
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 ini_spaces_re = re.compile(r'^(\s+)')
85 ini_spaces_re = re.compile(r'^(\s+)')
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87
87
88
88
89 #****************************************************************************
89 #****************************************************************************
90 # Some utility function definitions
90 # Some utility function definitions
91
91
92 def softspace(file, newvalue):
92 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
93 """Copied from code.py, to remove the dependency"""
94 oldvalue = 0
94 oldvalue = 0
95 try:
95 try:
96 oldvalue = file.softspace
96 oldvalue = file.softspace
97 except AttributeError:
97 except AttributeError:
98 pass
98 pass
99 try:
99 try:
100 file.softspace = newvalue
100 file.softspace = newvalue
101 except (AttributeError, TypeError):
101 except (AttributeError, TypeError):
102 # "attribute-less object" or "read-only attributes"
102 # "attribute-less object" or "read-only attributes"
103 pass
103 pass
104 return oldvalue
104 return oldvalue
105
105
106
106
107 #****************************************************************************
107 #****************************************************************************
108 # Local use exceptions
108 # Local use exceptions
109 class SpaceInInput(exceptions.Exception): pass
109 class SpaceInInput(exceptions.Exception): pass
110
110
111
111
112 #****************************************************************************
112 #****************************************************************************
113 # Local use classes
113 # Local use classes
114 class Bunch: pass
114 class Bunch: pass
115
115
116 class Undefined: pass
116 class Undefined: pass
117
117
118 class InputList(list):
118 class InputList(list):
119 """Class to store user input.
119 """Class to store user input.
120
120
121 It's basically a list, but slices return a string instead of a list, thus
121 It's basically a list, but slices return a string instead of a list, thus
122 allowing things like (assuming 'In' is an instance):
122 allowing things like (assuming 'In' is an instance):
123
123
124 exec In[4:7]
124 exec In[4:7]
125
125
126 or
126 or
127
127
128 exec In[5:9] + In[14] + In[21:25]"""
128 exec In[5:9] + In[14] + In[21:25]"""
129
129
130 def __getslice__(self,i,j):
130 def __getslice__(self,i,j):
131 return ''.join(list.__getslice__(self,i,j))
131 return ''.join(list.__getslice__(self,i,j))
132
132
133 class SyntaxTB(ultraTB.ListTB):
133 class SyntaxTB(ultraTB.ListTB):
134 """Extension which holds some state: the last exception value"""
134 """Extension which holds some state: the last exception value"""
135
135
136 def __init__(self,color_scheme = 'NoColor'):
136 def __init__(self,color_scheme = 'NoColor'):
137 ultraTB.ListTB.__init__(self,color_scheme)
137 ultraTB.ListTB.__init__(self,color_scheme)
138 self.last_syntax_error = None
138 self.last_syntax_error = None
139
139
140 def __call__(self, etype, value, elist):
140 def __call__(self, etype, value, elist):
141 self.last_syntax_error = value
141 self.last_syntax_error = value
142 ultraTB.ListTB.__call__(self,etype,value,elist)
142 ultraTB.ListTB.__call__(self,etype,value,elist)
143
143
144 def clear_err_state(self):
144 def clear_err_state(self):
145 """Return the current error state and clear it"""
145 """Return the current error state and clear it"""
146 e = self.last_syntax_error
146 e = self.last_syntax_error
147 self.last_syntax_error = None
147 self.last_syntax_error = None
148 return e
148 return e
149
149
150 #****************************************************************************
150 #****************************************************************************
151 # Main IPython class
151 # Main IPython class
152
152
153 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
153 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
154 # until a full rewrite is made. I've cleaned all cross-class uses of
154 # until a full rewrite is made. I've cleaned all cross-class uses of
155 # attributes and methods, but too much user code out there relies on the
155 # attributes and methods, but too much user code out there relies on the
156 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
156 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
157 #
157 #
158 # But at least now, all the pieces have been separated and we could, in
158 # But at least now, all the pieces have been separated and we could, in
159 # principle, stop using the mixin. This will ease the transition to the
159 # principle, stop using the mixin. This will ease the transition to the
160 # chainsaw branch.
160 # chainsaw branch.
161
161
162 # For reference, the following is the list of 'self.foo' uses in the Magic
162 # For reference, the following is the list of 'self.foo' uses in the Magic
163 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
163 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
164 # class, to prevent clashes.
164 # class, to prevent clashes.
165
165
166 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
166 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
167 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
167 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
168 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
168 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
169 # 'self.value']
169 # 'self.value']
170
170
171 class InteractiveShell(object,Magic):
171 class InteractiveShell(object,Magic):
172 """An enhanced console for Python."""
172 """An enhanced console for Python."""
173
173
174 # class attribute to indicate whether the class supports threads or not.
174 # class attribute to indicate whether the class supports threads or not.
175 # Subclasses with thread support should override this as needed.
175 # Subclasses with thread support should override this as needed.
176 isthreaded = False
176 isthreaded = False
177
177
178 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
178 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
179 user_ns = None,user_global_ns=None,banner2='',
179 user_ns = None,user_global_ns=None,banner2='',
180 custom_exceptions=((),None),embedded=False):
180 custom_exceptions=((),None),embedded=False):
181
181
182 # some minimal strict typechecks. For some core data structures, I
182 # some minimal strict typechecks. For some core data structures, I
183 # want actual basic python types, not just anything that looks like
183 # want actual basic python types, not just anything that looks like
184 # one. This is especially true for namespaces.
184 # one. This is especially true for namespaces.
185 for ns in (user_ns,user_global_ns):
185 for ns in (user_ns,user_global_ns):
186 if ns is not None and type(ns) != types.DictType:
186 if ns is not None and type(ns) != types.DictType:
187 raise TypeError,'namespace must be a dictionary'
187 raise TypeError,'namespace must be a dictionary'
188
188
189 # Job manager (for jobs run as background threads)
189 # Job manager (for jobs run as background threads)
190 self.jobs = BackgroundJobManager()
190 self.jobs = BackgroundJobManager()
191
191
192 # track which builtins we add, so we can clean up later
192 # track which builtins we add, so we can clean up later
193 self.builtins_added = {}
193 self.builtins_added = {}
194 # This method will add the necessary builtins for operation, but
194 # This method will add the necessary builtins for operation, but
195 # tracking what it did via the builtins_added dict.
195 # tracking what it did via the builtins_added dict.
196 self.add_builtins()
196 self.add_builtins()
197
197
198 # Do the intuitively correct thing for quit/exit: we remove the
198 # Do the intuitively correct thing for quit/exit: we remove the
199 # builtins if they exist, and our own magics will deal with this
199 # builtins if they exist, and our own magics will deal with this
200 try:
200 try:
201 del __builtin__.exit, __builtin__.quit
201 del __builtin__.exit, __builtin__.quit
202 except AttributeError:
202 except AttributeError:
203 pass
203 pass
204
204
205 # Store the actual shell's name
205 # Store the actual shell's name
206 self.name = name
206 self.name = name
207
207
208 # We need to know whether the instance is meant for embedding, since
208 # We need to know whether the instance is meant for embedding, since
209 # global/local namespaces need to be handled differently in that case
209 # global/local namespaces need to be handled differently in that case
210 self.embedded = embedded
210 self.embedded = embedded
211
211
212 # command compiler
212 # command compiler
213 self.compile = codeop.CommandCompiler()
213 self.compile = codeop.CommandCompiler()
214
214
215 # User input buffer
215 # User input buffer
216 self.buffer = []
216 self.buffer = []
217
217
218 # Default name given in compilation of code
218 # Default name given in compilation of code
219 self.filename = '<ipython console>'
219 self.filename = '<ipython console>'
220
220
221 # Make an empty namespace, which extension writers can rely on both
221 # Make an empty namespace, which extension writers can rely on both
222 # existing and NEVER being used by ipython itself. This gives them a
222 # existing and NEVER being used by ipython itself. This gives them a
223 # convenient location for storing additional information and state
223 # convenient location for storing additional information and state
224 # their extensions may require, without fear of collisions with other
224 # their extensions may require, without fear of collisions with other
225 # ipython names that may develop later.
225 # ipython names that may develop later.
226 self.meta = Bunch()
226 self.meta = Bunch()
227
227
228 # Create the namespace where the user will operate. user_ns is
228 # Create the namespace where the user will operate. user_ns is
229 # normally the only one used, and it is passed to the exec calls as
229 # normally the only one used, and it is passed to the exec calls as
230 # the locals argument. But we do carry a user_global_ns namespace
230 # the locals argument. But we do carry a user_global_ns namespace
231 # given as the exec 'globals' argument, This is useful in embedding
231 # given as the exec 'globals' argument, This is useful in embedding
232 # situations where the ipython shell opens in a context where the
232 # situations where the ipython shell opens in a context where the
233 # distinction between locals and globals is meaningful.
233 # distinction between locals and globals is meaningful.
234
234
235 # FIXME. For some strange reason, __builtins__ is showing up at user
235 # FIXME. For some strange reason, __builtins__ is showing up at user
236 # level as a dict instead of a module. This is a manual fix, but I
236 # level as a dict instead of a module. This is a manual fix, but I
237 # should really track down where the problem is coming from. Alex
237 # should really track down where the problem is coming from. Alex
238 # Schmolck reported this problem first.
238 # Schmolck reported this problem first.
239
239
240 # A useful post by Alex Martelli on this topic:
240 # A useful post by Alex Martelli on this topic:
241 # Re: inconsistent value from __builtins__
241 # Re: inconsistent value from __builtins__
242 # Von: Alex Martelli <aleaxit@yahoo.com>
242 # Von: Alex Martelli <aleaxit@yahoo.com>
243 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
243 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
244 # Gruppen: comp.lang.python
244 # Gruppen: comp.lang.python
245
245
246 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
246 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
247 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
247 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
248 # > <type 'dict'>
248 # > <type 'dict'>
249 # > >>> print type(__builtins__)
249 # > >>> print type(__builtins__)
250 # > <type 'module'>
250 # > <type 'module'>
251 # > Is this difference in return value intentional?
251 # > Is this difference in return value intentional?
252
252
253 # Well, it's documented that '__builtins__' can be either a dictionary
253 # Well, it's documented that '__builtins__' can be either a dictionary
254 # or a module, and it's been that way for a long time. Whether it's
254 # or a module, and it's been that way for a long time. Whether it's
255 # intentional (or sensible), I don't know. In any case, the idea is
255 # intentional (or sensible), I don't know. In any case, the idea is
256 # that if you need to access the built-in namespace directly, you
256 # that if you need to access the built-in namespace directly, you
257 # should start with "import __builtin__" (note, no 's') which will
257 # should start with "import __builtin__" (note, no 's') which will
258 # definitely give you a module. Yeah, it's somewhatΒ confusing:-(.
258 # definitely give you a module. Yeah, it's somewhatΒ confusing:-(.
259
259
260 if user_ns is None:
260 if user_ns is None:
261 # Set __name__ to __main__ to better match the behavior of the
261 # Set __name__ to __main__ to better match the behavior of the
262 # normal interpreter.
262 # normal interpreter.
263 user_ns = {'__name__' :'__main__',
263 user_ns = {'__name__' :'__main__',
264 '__builtins__' : __builtin__,
264 '__builtins__' : __builtin__,
265 }
265 }
266
266
267 if user_global_ns is None:
267 if user_global_ns is None:
268 user_global_ns = {}
268 user_global_ns = {}
269
269
270 # Assign namespaces
270 # Assign namespaces
271 # This is the namespace where all normal user variables live
271 # This is the namespace where all normal user variables live
272 self.user_ns = user_ns
272 self.user_ns = user_ns
273 # Embedded instances require a separate namespace for globals.
273 # Embedded instances require a separate namespace for globals.
274 # Normally this one is unused by non-embedded instances.
274 # Normally this one is unused by non-embedded instances.
275 self.user_global_ns = user_global_ns
275 self.user_global_ns = user_global_ns
276 # A namespace to keep track of internal data structures to prevent
276 # A namespace to keep track of internal data structures to prevent
277 # them from cluttering user-visible stuff. Will be updated later
277 # them from cluttering user-visible stuff. Will be updated later
278 self.internal_ns = {}
278 self.internal_ns = {}
279
279
280 # Namespace of system aliases. Each entry in the alias
280 # Namespace of system aliases. Each entry in the alias
281 # table must be a 2-tuple of the form (N,name), where N is the number
281 # table must be a 2-tuple of the form (N,name), where N is the number
282 # of positional arguments of the alias.
282 # of positional arguments of the alias.
283 self.alias_table = {}
283 self.alias_table = {}
284
284
285 # A table holding all the namespaces IPython deals with, so that
285 # A table holding all the namespaces IPython deals with, so that
286 # introspection facilities can search easily.
286 # introspection facilities can search easily.
287 self.ns_table = {'user':user_ns,
287 self.ns_table = {'user':user_ns,
288 'user_global':user_global_ns,
288 'user_global':user_global_ns,
289 'alias':self.alias_table,
289 'alias':self.alias_table,
290 'internal':self.internal_ns,
290 'internal':self.internal_ns,
291 'builtin':__builtin__.__dict__
291 'builtin':__builtin__.__dict__
292 }
292 }
293
293
294 # The user namespace MUST have a pointer to the shell itself.
294 # The user namespace MUST have a pointer to the shell itself.
295 self.user_ns[name] = self
295 self.user_ns[name] = self
296
296
297 # We need to insert into sys.modules something that looks like a
297 # We need to insert into sys.modules something that looks like a
298 # module but which accesses the IPython namespace, for shelve and
298 # module but which accesses the IPython namespace, for shelve and
299 # pickle to work interactively. Normally they rely on getting
299 # pickle to work interactively. Normally they rely on getting
300 # everything out of __main__, but for embedding purposes each IPython
300 # everything out of __main__, but for embedding purposes each IPython
301 # instance has its own private namespace, so we can't go shoving
301 # instance has its own private namespace, so we can't go shoving
302 # everything into __main__.
302 # everything into __main__.
303
303
304 # note, however, that we should only do this for non-embedded
304 # note, however, that we should only do this for non-embedded
305 # ipythons, which really mimic the __main__.__dict__ with their own
305 # ipythons, which really mimic the __main__.__dict__ with their own
306 # namespace. Embedded instances, on the other hand, should not do
306 # namespace. Embedded instances, on the other hand, should not do
307 # this because they need to manage the user local/global namespaces
307 # this because they need to manage the user local/global namespaces
308 # only, but they live within a 'normal' __main__ (meaning, they
308 # only, but they live within a 'normal' __main__ (meaning, they
309 # shouldn't overtake the execution environment of the script they're
309 # shouldn't overtake the execution environment of the script they're
310 # embedded in).
310 # embedded in).
311
311
312 if not embedded:
312 if not embedded:
313 try:
313 try:
314 main_name = self.user_ns['__name__']
314 main_name = self.user_ns['__name__']
315 except KeyError:
315 except KeyError:
316 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
316 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
317 else:
317 else:
318 #print "pickle hack in place" # dbg
318 #print "pickle hack in place" # dbg
319 #print 'main_name:',main_name # dbg
319 #print 'main_name:',main_name # dbg
320 sys.modules[main_name] = FakeModule(self.user_ns)
320 sys.modules[main_name] = FakeModule(self.user_ns)
321
321
322 # List of input with multi-line handling.
322 # List of input with multi-line handling.
323 # Fill its zero entry, user counter starts at 1
323 # Fill its zero entry, user counter starts at 1
324 self.input_hist = InputList(['\n'])
324 self.input_hist = InputList(['\n'])
325
325
326 # list of visited directories
326 # list of visited directories
327 try:
327 try:
328 self.dir_hist = [os.getcwd()]
328 self.dir_hist = [os.getcwd()]
329 except IOError, e:
329 except IOError, e:
330 self.dir_hist = []
330 self.dir_hist = []
331
331
332 # dict of output history
332 # dict of output history
333 self.output_hist = {}
333 self.output_hist = {}
334
334
335 # dict of things NOT to alias (keywords, builtins and some magics)
335 # dict of things NOT to alias (keywords, builtins and some magics)
336 no_alias = {}
336 no_alias = {}
337 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
337 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
338 for key in keyword.kwlist + no_alias_magics:
338 for key in keyword.kwlist + no_alias_magics:
339 no_alias[key] = 1
339 no_alias[key] = 1
340 no_alias.update(__builtin__.__dict__)
340 no_alias.update(__builtin__.__dict__)
341 self.no_alias = no_alias
341 self.no_alias = no_alias
342
342
343 # make global variables for user access to these
343 # make global variables for user access to these
344 self.user_ns['_ih'] = self.input_hist
344 self.user_ns['_ih'] = self.input_hist
345 self.user_ns['_oh'] = self.output_hist
345 self.user_ns['_oh'] = self.output_hist
346 self.user_ns['_dh'] = self.dir_hist
346 self.user_ns['_dh'] = self.dir_hist
347
347
348 # user aliases to input and output histories
348 # user aliases to input and output histories
349 self.user_ns['In'] = self.input_hist
349 self.user_ns['In'] = self.input_hist
350 self.user_ns['Out'] = self.output_hist
350 self.user_ns['Out'] = self.output_hist
351
351
352 # Object variable to store code object waiting execution. This is
352 # Object variable to store code object waiting execution. This is
353 # used mainly by the multithreaded shells, but it can come in handy in
353 # used mainly by the multithreaded shells, but it can come in handy in
354 # other situations. No need to use a Queue here, since it's a single
354 # other situations. No need to use a Queue here, since it's a single
355 # item which gets cleared once run.
355 # item which gets cleared once run.
356 self.code_to_run = None
356 self.code_to_run = None
357
357
358 # escapes for automatic behavior on the command line
358 # escapes for automatic behavior on the command line
359 self.ESC_SHELL = '!'
359 self.ESC_SHELL = '!'
360 self.ESC_HELP = '?'
360 self.ESC_HELP = '?'
361 self.ESC_MAGIC = '%'
361 self.ESC_MAGIC = '%'
362 self.ESC_QUOTE = ','
362 self.ESC_QUOTE = ','
363 self.ESC_QUOTE2 = ';'
363 self.ESC_QUOTE2 = ';'
364 self.ESC_PAREN = '/'
364 self.ESC_PAREN = '/'
365
365
366 # And their associated handlers
366 # And their associated handlers
367 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
367 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
368 self.ESC_QUOTE : self.handle_auto,
368 self.ESC_QUOTE : self.handle_auto,
369 self.ESC_QUOTE2 : self.handle_auto,
369 self.ESC_QUOTE2 : self.handle_auto,
370 self.ESC_MAGIC : self.handle_magic,
370 self.ESC_MAGIC : self.handle_magic,
371 self.ESC_HELP : self.handle_help,
371 self.ESC_HELP : self.handle_help,
372 self.ESC_SHELL : self.handle_shell_escape,
372 self.ESC_SHELL : self.handle_shell_escape,
373 }
373 }
374
374
375 # class initializations
375 # class initializations
376 Magic.__init__(self,self)
376 Magic.__init__(self,self)
377
377
378 # Python source parser/formatter for syntax highlighting
378 # Python source parser/formatter for syntax highlighting
379 pyformat = PyColorize.Parser().format
379 pyformat = PyColorize.Parser().format
380 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
380 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
381
381
382 # hooks holds pointers used for user-side customizations
382 # hooks holds pointers used for user-side customizations
383 self.hooks = Struct()
383 self.hooks = Struct()
384
384
385 # Set all default hooks, defined in the IPython.hooks module.
385 # Set all default hooks, defined in the IPython.hooks module.
386 hooks = IPython.hooks
386 hooks = IPython.hooks
387 for hook_name in hooks.__all__:
387 for hook_name in hooks.__all__:
388 self.set_hook(hook_name,getattr(hooks,hook_name))
388 self.set_hook(hook_name,getattr(hooks,hook_name))
389
389
390 # Flag to mark unconditional exit
390 # Flag to mark unconditional exit
391 self.exit_now = False
391 self.exit_now = False
392
392
393 self.usage_min = """\
393 self.usage_min = """\
394 An enhanced console for Python.
394 An enhanced console for Python.
395 Some of its features are:
395 Some of its features are:
396 - Readline support if the readline library is present.
396 - Readline support if the readline library is present.
397 - Tab completion in the local namespace.
397 - Tab completion in the local namespace.
398 - Logging of input, see command-line options.
398 - Logging of input, see command-line options.
399 - System shell escape via ! , eg !ls.
399 - System shell escape via ! , eg !ls.
400 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
400 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
401 - Keeps track of locally defined variables via %who, %whos.
401 - Keeps track of locally defined variables via %who, %whos.
402 - Show object information with a ? eg ?x or x? (use ?? for more info).
402 - Show object information with a ? eg ?x or x? (use ?? for more info).
403 """
403 """
404 if usage: self.usage = usage
404 if usage: self.usage = usage
405 else: self.usage = self.usage_min
405 else: self.usage = self.usage_min
406
406
407 # Storage
407 # Storage
408 self.rc = rc # This will hold all configuration information
408 self.rc = rc # This will hold all configuration information
409 self.pager = 'less'
409 self.pager = 'less'
410 # temporary files used for various purposes. Deleted at exit.
410 # temporary files used for various purposes. Deleted at exit.
411 self.tempfiles = []
411 self.tempfiles = []
412
412
413 # Keep track of readline usage (later set by init_readline)
413 # Keep track of readline usage (later set by init_readline)
414 self.has_readline = False
414 self.has_readline = False
415
415
416 # template for logfile headers. It gets resolved at runtime by the
416 # template for logfile headers. It gets resolved at runtime by the
417 # logstart method.
417 # logstart method.
418 self.loghead_tpl = \
418 self.loghead_tpl = \
419 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
419 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
420 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
420 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
421 #log# opts = %s
421 #log# opts = %s
422 #log# args = %s
422 #log# args = %s
423 #log# It is safe to make manual edits below here.
423 #log# It is safe to make manual edits below here.
424 #log#-----------------------------------------------------------------------
424 #log#-----------------------------------------------------------------------
425 """
425 """
426 # for pushd/popd management
426 # for pushd/popd management
427 try:
427 try:
428 self.home_dir = get_home_dir()
428 self.home_dir = get_home_dir()
429 except HomeDirError,msg:
429 except HomeDirError,msg:
430 fatal(msg)
430 fatal(msg)
431
431
432 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
432 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
433
433
434 # Functions to call the underlying shell.
434 # Functions to call the underlying shell.
435
435
436 # utility to expand user variables via Itpl
436 # utility to expand user variables via Itpl
437 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
437 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
438 self.user_ns))
438 self.user_ns))
439 # The first is similar to os.system, but it doesn't return a value,
439 # The first is similar to os.system, but it doesn't return a value,
440 # and it allows interpolation of variables in the user's namespace.
440 # and it allows interpolation of variables in the user's namespace.
441 self.system = lambda cmd: shell(self.var_expand(cmd),
441 self.system = lambda cmd: shell(self.var_expand(cmd),
442 header='IPython system call: ',
442 header='IPython system call: ',
443 verbose=self.rc.system_verbose)
443 verbose=self.rc.system_verbose)
444 # These are for getoutput and getoutputerror:
444 # These are for getoutput and getoutputerror:
445 self.getoutput = lambda cmd: \
445 self.getoutput = lambda cmd: \
446 getoutput(self.var_expand(cmd),
446 getoutput(self.var_expand(cmd),
447 header='IPython system call: ',
447 header='IPython system call: ',
448 verbose=self.rc.system_verbose)
448 verbose=self.rc.system_verbose)
449 self.getoutputerror = lambda cmd: \
449 self.getoutputerror = lambda cmd: \
450 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
450 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
451 self.user_ns)),
451 self.user_ns)),
452 header='IPython system call: ',
452 header='IPython system call: ',
453 verbose=self.rc.system_verbose)
453 verbose=self.rc.system_verbose)
454
454
455 # RegExp for splitting line contents into pre-char//first
455 # RegExp for splitting line contents into pre-char//first
456 # word-method//rest. For clarity, each group in on one line.
456 # word-method//rest. For clarity, each group in on one line.
457
457
458 # WARNING: update the regexp if the above escapes are changed, as they
458 # WARNING: update the regexp if the above escapes are changed, as they
459 # are hardwired in.
459 # are hardwired in.
460
460
461 # Don't get carried away with trying to make the autocalling catch too
461 # Don't get carried away with trying to make the autocalling catch too
462 # much: it's better to be conservative rather than to trigger hidden
462 # much: it's better to be conservative rather than to trigger hidden
463 # evals() somewhere and end up causing side effects.
463 # evals() somewhere and end up causing side effects.
464
464
465 self.line_split = re.compile(r'^([\s*,;/])'
465 self.line_split = re.compile(r'^([\s*,;/])'
466 r'([\?\w\.]+\w*\s*)'
466 r'([\?\w\.]+\w*\s*)'
467 r'(\(?.*$)')
467 r'(\(?.*$)')
468
468
469 # Original re, keep around for a while in case changes break something
469 # Original re, keep around for a while in case changes break something
470 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
470 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
471 # r'(\s*[\?\w\.]+\w*\s*)'
471 # r'(\s*[\?\w\.]+\w*\s*)'
472 # r'(\(?.*$)')
472 # r'(\(?.*$)')
473
473
474 # RegExp to identify potential function names
474 # RegExp to identify potential function names
475 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
475 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
476 # RegExp to exclude strings with this start from autocalling
476 # RegExp to exclude strings with this start from autocalling
477 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
477 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
478
478
479 # try to catch also methods for stuff in lists/tuples/dicts: off
479 # try to catch also methods for stuff in lists/tuples/dicts: off
480 # (experimental). For this to work, the line_split regexp would need
480 # (experimental). For this to work, the line_split regexp would need
481 # to be modified so it wouldn't break things at '['. That line is
481 # to be modified so it wouldn't break things at '['. That line is
482 # nasty enough that I shouldn't change it until I can test it _well_.
482 # nasty enough that I shouldn't change it until I can test it _well_.
483 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
483 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
484
484
485 # keep track of where we started running (mainly for crash post-mortem)
485 # keep track of where we started running (mainly for crash post-mortem)
486 self.starting_dir = os.getcwd()
486 self.starting_dir = os.getcwd()
487
487
488 # Various switches which can be set
488 # Various switches which can be set
489 self.CACHELENGTH = 5000 # this is cheap, it's just text
489 self.CACHELENGTH = 5000 # this is cheap, it's just text
490 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
490 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
491 self.banner2 = banner2
491 self.banner2 = banner2
492
492
493 # TraceBack handlers:
493 # TraceBack handlers:
494
494
495 # Syntax error handler.
495 # Syntax error handler.
496 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
496 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
497
497
498 # The interactive one is initialized with an offset, meaning we always
498 # The interactive one is initialized with an offset, meaning we always
499 # want to remove the topmost item in the traceback, which is our own
499 # want to remove the topmost item in the traceback, which is our own
500 # internal code. Valid modes: ['Plain','Context','Verbose']
500 # internal code. Valid modes: ['Plain','Context','Verbose']
501 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
501 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
502 color_scheme='NoColor',
502 color_scheme='NoColor',
503 tb_offset = 1)
503 tb_offset = 1)
504
504
505 # IPython itself shouldn't crash. This will produce a detailed
505 # IPython itself shouldn't crash. This will produce a detailed
506 # post-mortem if it does. But we only install the crash handler for
506 # post-mortem if it does. But we only install the crash handler for
507 # non-threaded shells, the threaded ones use a normal verbose reporter
507 # non-threaded shells, the threaded ones use a normal verbose reporter
508 # and lose the crash handler. This is because exceptions in the main
508 # and lose the crash handler. This is because exceptions in the main
509 # thread (such as in GUI code) propagate directly to sys.excepthook,
509 # thread (such as in GUI code) propagate directly to sys.excepthook,
510 # and there's no point in printing crash dumps for every user exception.
510 # and there's no point in printing crash dumps for every user exception.
511 if self.isthreaded:
511 if self.isthreaded:
512 sys.excepthook = ultraTB.FormattedTB()
512 sys.excepthook = ultraTB.FormattedTB()
513 else:
513 else:
514 from IPython import CrashHandler
514 from IPython import CrashHandler
515 sys.excepthook = CrashHandler.CrashHandler(self)
515 sys.excepthook = CrashHandler.CrashHandler(self)
516
516
517 # The instance will store a pointer to this, so that runtime code
517 # The instance will store a pointer to this, so that runtime code
518 # (such as magics) can access it. This is because during the
518 # (such as magics) can access it. This is because during the
519 # read-eval loop, it gets temporarily overwritten (to deal with GUI
519 # read-eval loop, it gets temporarily overwritten (to deal with GUI
520 # frameworks).
520 # frameworks).
521 self.sys_excepthook = sys.excepthook
521 self.sys_excepthook = sys.excepthook
522
522
523 # and add any custom exception handlers the user may have specified
523 # and add any custom exception handlers the user may have specified
524 self.set_custom_exc(*custom_exceptions)
524 self.set_custom_exc(*custom_exceptions)
525
525
526 # Object inspector
526 # Object inspector
527 self.inspector = OInspect.Inspector(OInspect.InspectColors,
527 self.inspector = OInspect.Inspector(OInspect.InspectColors,
528 PyColorize.ANSICodeColors,
528 PyColorize.ANSICodeColors,
529 'NoColor')
529 'NoColor')
530 # indentation management
530 # indentation management
531 self.autoindent = False
531 self.autoindent = False
532 self.indent_current_nsp = 0
532 self.indent_current_nsp = 0
533 self.indent_current = '' # actual indent string
533 self.indent_current = '' # actual indent string
534
534
535 # Make some aliases automatically
535 # Make some aliases automatically
536 # Prepare list of shell aliases to auto-define
536 # Prepare list of shell aliases to auto-define
537 if os.name == 'posix':
537 if os.name == 'posix':
538 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
538 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
539 'mv mv -i','rm rm -i','cp cp -i',
539 'mv mv -i','rm rm -i','cp cp -i',
540 'cat cat','less less','clear clear',
540 'cat cat','less less','clear clear',
541 # a better ls
541 # a better ls
542 'ls ls -F',
542 'ls ls -F',
543 # long ls
543 # long ls
544 'll ls -lF',
544 'll ls -lF',
545 # color ls
545 # color ls
546 'lc ls -F -o --color',
546 'lc ls -F -o --color',
547 # ls normal files only
547 # ls normal files only
548 'lf ls -F -o --color %l | grep ^-',
548 'lf ls -F -o --color %l | grep ^-',
549 # ls symbolic links
549 # ls symbolic links
550 'lk ls -F -o --color %l | grep ^l',
550 'lk ls -F -o --color %l | grep ^l',
551 # directories or links to directories,
551 # directories or links to directories,
552 'ldir ls -F -o --color %l | grep /$',
552 'ldir ls -F -o --color %l | grep /$',
553 # things which are executable
553 # things which are executable
554 'lx ls -F -o --color %l | grep ^-..x',
554 'lx ls -F -o --color %l | grep ^-..x',
555 )
555 )
556 elif os.name in ['nt','dos']:
556 elif os.name in ['nt','dos']:
557 auto_alias = ('dir dir /on', 'ls dir /on',
557 auto_alias = ('dir dir /on', 'ls dir /on',
558 'ddir dir /ad /on', 'ldir dir /ad /on',
558 'ddir dir /ad /on', 'ldir dir /ad /on',
559 'mkdir mkdir','rmdir rmdir','echo echo',
559 'mkdir mkdir','rmdir rmdir','echo echo',
560 'ren ren','cls cls','copy copy')
560 'ren ren','cls cls','copy copy')
561 else:
561 else:
562 auto_alias = ()
562 auto_alias = ()
563 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
563 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
564 # Call the actual (public) initializer
564 # Call the actual (public) initializer
565 self.init_auto_alias()
565 self.init_auto_alias()
566 # end __init__
566 # end __init__
567
567
568 def post_config_initialization(self):
568 def post_config_initialization(self):
569 """Post configuration init method
569 """Post configuration init method
570
570
571 This is called after the configuration files have been processed to
571 This is called after the configuration files have been processed to
572 'finalize' the initialization."""
572 'finalize' the initialization."""
573
573
574 rc = self.rc
574 rc = self.rc
575
575
576 # Load readline proper
576 # Load readline proper
577 if rc.readline:
577 if rc.readline:
578 self.init_readline()
578 self.init_readline()
579
579
580 # log system
580 # log system
581 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
581 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
582 # local shortcut, this is used a LOT
582 # local shortcut, this is used a LOT
583 self.log = self.logger.log
583 self.log = self.logger.log
584
584
585 # Initialize cache, set in/out prompts and printing system
585 # Initialize cache, set in/out prompts and printing system
586 self.outputcache = CachedOutput(self,
586 self.outputcache = CachedOutput(self,
587 rc.cache_size,
587 rc.cache_size,
588 rc.pprint,
588 rc.pprint,
589 input_sep = rc.separate_in,
589 input_sep = rc.separate_in,
590 output_sep = rc.separate_out,
590 output_sep = rc.separate_out,
591 output_sep2 = rc.separate_out2,
591 output_sep2 = rc.separate_out2,
592 ps1 = rc.prompt_in1,
592 ps1 = rc.prompt_in1,
593 ps2 = rc.prompt_in2,
593 ps2 = rc.prompt_in2,
594 ps_out = rc.prompt_out,
594 ps_out = rc.prompt_out,
595 pad_left = rc.prompts_pad_left)
595 pad_left = rc.prompts_pad_left)
596
596
597 # user may have over-ridden the default print hook:
597 # user may have over-ridden the default print hook:
598 try:
598 try:
599 self.outputcache.__class__.display = self.hooks.display
599 self.outputcache.__class__.display = self.hooks.display
600 except AttributeError:
600 except AttributeError:
601 pass
601 pass
602
602
603 # I don't like assigning globally to sys, because it means when embedding
603 # I don't like assigning globally to sys, because it means when embedding
604 # instances, each embedded instance overrides the previous choice. But
604 # instances, each embedded instance overrides the previous choice. But
605 # sys.displayhook seems to be called internally by exec, so I don't see a
605 # sys.displayhook seems to be called internally by exec, so I don't see a
606 # way around it.
606 # way around it.
607 sys.displayhook = self.outputcache
607 sys.displayhook = self.outputcache
608
608
609 # Set user colors (don't do it in the constructor above so that it
609 # Set user colors (don't do it in the constructor above so that it
610 # doesn't crash if colors option is invalid)
610 # doesn't crash if colors option is invalid)
611 self.magic_colors(rc.colors)
611 self.magic_colors(rc.colors)
612
612
613 # Set calling of pdb on exceptions
613 # Set calling of pdb on exceptions
614 self.call_pdb = rc.pdb
614 self.call_pdb = rc.pdb
615
615
616 # Load user aliases
616 # Load user aliases
617 for alias in rc.alias:
617 for alias in rc.alias:
618 self.magic_alias(alias)
618 self.magic_alias(alias)
619
619
620 # dynamic data that survives through sessions
620 # dynamic data that survives through sessions
621 # XXX make the filename a config option?
621 # XXX make the filename a config option?
622 persist_base = 'persist'
622 persist_base = 'persist'
623 if rc.profile:
623 if rc.profile:
624 persist_base += '_%s' % rc.profile
624 persist_base += '_%s' % rc.profile
625 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
625 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
626
626
627 try:
627 try:
628 self.persist = pickle.load(file(self.persist_fname))
628 self.persist = pickle.load(file(self.persist_fname))
629 except:
629 except:
630 self.persist = {}
630 self.persist = {}
631
631
632
632
633 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
633 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
634 try:
634 try:
635 obj = pickle.loads(value)
635 obj = pickle.loads(value)
636 except:
636 except:
637
637
638 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
638 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
639 print "The error was:",sys.exc_info()[0]
639 print "The error was:",sys.exc_info()[0]
640 continue
640 continue
641
641
642
642
643 self.user_ns[key] = obj
643 self.user_ns[key] = obj
644
644
645 def add_builtins(self):
645 def add_builtins(self):
646 """Store ipython references into the builtin namespace.
646 """Store ipython references into the builtin namespace.
647
647
648 Some parts of ipython operate via builtins injected here, which hold a
648 Some parts of ipython operate via builtins injected here, which hold a
649 reference to IPython itself."""
649 reference to IPython itself."""
650
650
651 builtins_new = dict(__IPYTHON__ = self,
651 builtins_new = dict(__IPYTHON__ = self,
652 ip_set_hook = self.set_hook,
652 ip_set_hook = self.set_hook,
653 jobs = self.jobs,
653 jobs = self.jobs,
654 ipmagic = self.ipmagic,
654 ipmagic = self.ipmagic,
655 ipalias = self.ipalias,
655 ipalias = self.ipalias,
656 ipsystem = self.ipsystem,
656 ipsystem = self.ipsystem,
657 )
657 )
658 for biname,bival in builtins_new.items():
658 for biname,bival in builtins_new.items():
659 try:
659 try:
660 # store the orignal value so we can restore it
660 # store the orignal value so we can restore it
661 self.builtins_added[biname] = __builtin__.__dict__[biname]
661 self.builtins_added[biname] = __builtin__.__dict__[biname]
662 except KeyError:
662 except KeyError:
663 # or mark that it wasn't defined, and we'll just delete it at
663 # or mark that it wasn't defined, and we'll just delete it at
664 # cleanup
664 # cleanup
665 self.builtins_added[biname] = Undefined
665 self.builtins_added[biname] = Undefined
666 __builtin__.__dict__[biname] = bival
666 __builtin__.__dict__[biname] = bival
667
667
668 # Keep in the builtins a flag for when IPython is active. We set it
668 # Keep in the builtins a flag for when IPython is active. We set it
669 # with setdefault so that multiple nested IPythons don't clobber one
669 # with setdefault so that multiple nested IPythons don't clobber one
670 # another. Each will increase its value by one upon being activated,
670 # another. Each will increase its value by one upon being activated,
671 # which also gives us a way to determine the nesting level.
671 # which also gives us a way to determine the nesting level.
672 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
672 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
673
673
674 def clean_builtins(self):
674 def clean_builtins(self):
675 """Remove any builtins which might have been added by add_builtins, or
675 """Remove any builtins which might have been added by add_builtins, or
676 restore overwritten ones to their previous values."""
676 restore overwritten ones to their previous values."""
677 for biname,bival in self.builtins_added.items():
677 for biname,bival in self.builtins_added.items():
678 if bival is Undefined:
678 if bival is Undefined:
679 del __builtin__.__dict__[biname]
679 del __builtin__.__dict__[biname]
680 else:
680 else:
681 __builtin__.__dict__[biname] = bival
681 __builtin__.__dict__[biname] = bival
682 self.builtins_added.clear()
682 self.builtins_added.clear()
683
683
684 def set_hook(self,name,hook):
684 def set_hook(self,name,hook):
685 """set_hook(name,hook) -> sets an internal IPython hook.
685 """set_hook(name,hook) -> sets an internal IPython hook.
686
686
687 IPython exposes some of its internal API as user-modifiable hooks. By
687 IPython exposes some of its internal API as user-modifiable hooks. By
688 resetting one of these hooks, you can modify IPython's behavior to
688 resetting one of these hooks, you can modify IPython's behavior to
689 call at runtime your own routines."""
689 call at runtime your own routines."""
690
690
691 # At some point in the future, this should validate the hook before it
691 # At some point in the future, this should validate the hook before it
692 # accepts it. Probably at least check that the hook takes the number
692 # accepts it. Probably at least check that the hook takes the number
693 # of args it's supposed to.
693 # of args it's supposed to.
694 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
694 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
695
695
696 def set_custom_exc(self,exc_tuple,handler):
696 def set_custom_exc(self,exc_tuple,handler):
697 """set_custom_exc(exc_tuple,handler)
697 """set_custom_exc(exc_tuple,handler)
698
698
699 Set a custom exception handler, which will be called if any of the
699 Set a custom exception handler, which will be called if any of the
700 exceptions in exc_tuple occur in the mainloop (specifically, in the
700 exceptions in exc_tuple occur in the mainloop (specifically, in the
701 runcode() method.
701 runcode() method.
702
702
703 Inputs:
703 Inputs:
704
704
705 - exc_tuple: a *tuple* of valid exceptions to call the defined
705 - exc_tuple: a *tuple* of valid exceptions to call the defined
706 handler for. It is very important that you use a tuple, and NOT A
706 handler for. It is very important that you use a tuple, and NOT A
707 LIST here, because of the way Python's except statement works. If
707 LIST here, because of the way Python's except statement works. If
708 you only want to trap a single exception, use a singleton tuple:
708 you only want to trap a single exception, use a singleton tuple:
709
709
710 exc_tuple == (MyCustomException,)
710 exc_tuple == (MyCustomException,)
711
711
712 - handler: this must be defined as a function with the following
712 - handler: this must be defined as a function with the following
713 basic interface: def my_handler(self,etype,value,tb).
713 basic interface: def my_handler(self,etype,value,tb).
714
714
715 This will be made into an instance method (via new.instancemethod)
715 This will be made into an instance method (via new.instancemethod)
716 of IPython itself, and it will be called if any of the exceptions
716 of IPython itself, and it will be called if any of the exceptions
717 listed in the exc_tuple are caught. If the handler is None, an
717 listed in the exc_tuple are caught. If the handler is None, an
718 internal basic one is used, which just prints basic info.
718 internal basic one is used, which just prints basic info.
719
719
720 WARNING: by putting in your own exception handler into IPython's main
720 WARNING: by putting in your own exception handler into IPython's main
721 execution loop, you run a very good chance of nasty crashes. This
721 execution loop, you run a very good chance of nasty crashes. This
722 facility should only be used if you really know what you are doing."""
722 facility should only be used if you really know what you are doing."""
723
723
724 assert type(exc_tuple)==type(()) , \
724 assert type(exc_tuple)==type(()) , \
725 "The custom exceptions must be given AS A TUPLE."
725 "The custom exceptions must be given AS A TUPLE."
726
726
727 def dummy_handler(self,etype,value,tb):
727 def dummy_handler(self,etype,value,tb):
728 print '*** Simple custom exception handler ***'
728 print '*** Simple custom exception handler ***'
729 print 'Exception type :',etype
729 print 'Exception type :',etype
730 print 'Exception value:',value
730 print 'Exception value:',value
731 print 'Traceback :',tb
731 print 'Traceback :',tb
732 print 'Source code :','\n'.join(self.buffer)
732 print 'Source code :','\n'.join(self.buffer)
733
733
734 if handler is None: handler = dummy_handler
734 if handler is None: handler = dummy_handler
735
735
736 self.CustomTB = new.instancemethod(handler,self,self.__class__)
736 self.CustomTB = new.instancemethod(handler,self,self.__class__)
737 self.custom_exceptions = exc_tuple
737 self.custom_exceptions = exc_tuple
738
738
739 def set_custom_completer(self,completer,pos=0):
739 def set_custom_completer(self,completer,pos=0):
740 """set_custom_completer(completer,pos=0)
740 """set_custom_completer(completer,pos=0)
741
741
742 Adds a new custom completer function.
742 Adds a new custom completer function.
743
743
744 The position argument (defaults to 0) is the index in the completers
744 The position argument (defaults to 0) is the index in the completers
745 list where you want the completer to be inserted."""
745 list where you want the completer to be inserted."""
746
746
747 newcomp = new.instancemethod(completer,self.Completer,
747 newcomp = new.instancemethod(completer,self.Completer,
748 self.Completer.__class__)
748 self.Completer.__class__)
749 self.Completer.matchers.insert(pos,newcomp)
749 self.Completer.matchers.insert(pos,newcomp)
750
750
751 def _get_call_pdb(self):
751 def _get_call_pdb(self):
752 return self._call_pdb
752 return self._call_pdb
753
753
754 def _set_call_pdb(self,val):
754 def _set_call_pdb(self,val):
755
755
756 if val not in (0,1,False,True):
756 if val not in (0,1,False,True):
757 raise ValueError,'new call_pdb value must be boolean'
757 raise ValueError,'new call_pdb value must be boolean'
758
758
759 # store value in instance
759 # store value in instance
760 self._call_pdb = val
760 self._call_pdb = val
761
761
762 # notify the actual exception handlers
762 # notify the actual exception handlers
763 self.InteractiveTB.call_pdb = val
763 self.InteractiveTB.call_pdb = val
764 if self.isthreaded:
764 if self.isthreaded:
765 try:
765 try:
766 self.sys_excepthook.call_pdb = val
766 self.sys_excepthook.call_pdb = val
767 except:
767 except:
768 warn('Failed to activate pdb for threaded exception handler')
768 warn('Failed to activate pdb for threaded exception handler')
769
769
770 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
770 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
771 'Control auto-activation of pdb at exceptions')
771 'Control auto-activation of pdb at exceptions')
772
772
773
773
774 # These special functions get installed in the builtin namespace, to
774 # These special functions get installed in the builtin namespace, to
775 # provide programmatic (pure python) access to magics, aliases and system
775 # provide programmatic (pure python) access to magics, aliases and system
776 # calls. This is important for logging, user scripting, and more.
776 # calls. This is important for logging, user scripting, and more.
777
777
778 # We are basically exposing, via normal python functions, the three
778 # We are basically exposing, via normal python functions, the three
779 # mechanisms in which ipython offers special call modes (magics for
779 # mechanisms in which ipython offers special call modes (magics for
780 # internal control, aliases for direct system access via pre-selected
780 # internal control, aliases for direct system access via pre-selected
781 # names, and !cmd for calling arbitrary system commands).
781 # names, and !cmd for calling arbitrary system commands).
782
782
783 def ipmagic(self,arg_s):
783 def ipmagic(self,arg_s):
784 """Call a magic function by name.
784 """Call a magic function by name.
785
785
786 Input: a string containing the name of the magic function to call and any
786 Input: a string containing the name of the magic function to call and any
787 additional arguments to be passed to the magic.
787 additional arguments to be passed to the magic.
788
788
789 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
789 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
790 prompt:
790 prompt:
791
791
792 In[1]: %name -opt foo bar
792 In[1]: %name -opt foo bar
793
793
794 To call a magic without arguments, simply use ipmagic('name').
794 To call a magic without arguments, simply use ipmagic('name').
795
795
796 This provides a proper Python function to call IPython's magics in any
796 This provides a proper Python function to call IPython's magics in any
797 valid Python code you can type at the interpreter, including loops and
797 valid Python code you can type at the interpreter, including loops and
798 compound statements. It is added by IPython to the Python builtin
798 compound statements. It is added by IPython to the Python builtin
799 namespace upon initialization."""
799 namespace upon initialization."""
800
800
801 args = arg_s.split(' ',1)
801 args = arg_s.split(' ',1)
802 magic_name = args[0]
802 magic_name = args[0]
803 if magic_name.startswith(self.ESC_MAGIC):
803 if magic_name.startswith(self.ESC_MAGIC):
804 magic_name = magic_name[1:]
804 magic_name = magic_name[1:]
805 try:
805 try:
806 magic_args = args[1]
806 magic_args = args[1]
807 except IndexError:
807 except IndexError:
808 magic_args = ''
808 magic_args = ''
809 fn = getattr(self,'magic_'+magic_name,None)
809 fn = getattr(self,'magic_'+magic_name,None)
810 if fn is None:
810 if fn is None:
811 error("Magic function `%s` not found." % magic_name)
811 error("Magic function `%s` not found." % magic_name)
812 else:
812 else:
813 magic_args = self.var_expand(magic_args)
813 magic_args = self.var_expand(magic_args)
814 return fn(magic_args)
814 return fn(magic_args)
815
815
816 def ipalias(self,arg_s):
816 def ipalias(self,arg_s):
817 """Call an alias by name.
817 """Call an alias by name.
818
818
819 Input: a string containing the name of the alias to call and any
819 Input: a string containing the name of the alias to call and any
820 additional arguments to be passed to the magic.
820 additional arguments to be passed to the magic.
821
821
822 ipalias('name -opt foo bar') is equivalent to typing at the ipython
822 ipalias('name -opt foo bar') is equivalent to typing at the ipython
823 prompt:
823 prompt:
824
824
825 In[1]: name -opt foo bar
825 In[1]: name -opt foo bar
826
826
827 To call an alias without arguments, simply use ipalias('name').
827 To call an alias without arguments, simply use ipalias('name').
828
828
829 This provides a proper Python function to call IPython's aliases in any
829 This provides a proper Python function to call IPython's aliases in any
830 valid Python code you can type at the interpreter, including loops and
830 valid Python code you can type at the interpreter, including loops and
831 compound statements. It is added by IPython to the Python builtin
831 compound statements. It is added by IPython to the Python builtin
832 namespace upon initialization."""
832 namespace upon initialization."""
833
833
834 args = arg_s.split(' ',1)
834 args = arg_s.split(' ',1)
835 alias_name = args[0]
835 alias_name = args[0]
836 try:
836 try:
837 alias_args = args[1]
837 alias_args = args[1]
838 except IndexError:
838 except IndexError:
839 alias_args = ''
839 alias_args = ''
840 if alias_name in self.alias_table:
840 if alias_name in self.alias_table:
841 self.call_alias(alias_name,alias_args)
841 self.call_alias(alias_name,alias_args)
842 else:
842 else:
843 error("Alias `%s` not found." % alias_name)
843 error("Alias `%s` not found." % alias_name)
844
844
845 def ipsystem(self,arg_s):
845 def ipsystem(self,arg_s):
846 """Make a system call, using IPython."""
846 """Make a system call, using IPython."""
847
847
848 self.system(arg_s)
848 self.system(arg_s)
849
849
850 def complete(self,text):
850 def complete(self,text):
851 """Return a sorted list of all possible completions on text.
851 """Return a sorted list of all possible completions on text.
852
852
853 Inputs:
853 Inputs:
854
854
855 - text: a string of text to be completed on.
855 - text: a string of text to be completed on.
856
856
857 This is a wrapper around the completion mechanism, similar to what
857 This is a wrapper around the completion mechanism, similar to what
858 readline does at the command line when the TAB key is hit. By
858 readline does at the command line when the TAB key is hit. By
859 exposing it as a method, it can be used by other non-readline
859 exposing it as a method, it can be used by other non-readline
860 environments (such as GUIs) for text completion.
860 environments (such as GUIs) for text completion.
861
861
862 Simple usage example:
862 Simple usage example:
863
863
864 In [1]: x = 'hello'
864 In [1]: x = 'hello'
865
865
866 In [2]: __IP.complete('x.l')
866 In [2]: __IP.complete('x.l')
867 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
867 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
868
868
869 complete = self.Completer.complete
869 complete = self.Completer.complete
870 state = 0
870 state = 0
871 # use a dict so we get unique keys, since ipyhton's multiple
871 # use a dict so we get unique keys, since ipyhton's multiple
872 # completers can return duplicates.
872 # completers can return duplicates.
873 comps = {}
873 comps = {}
874 while True:
874 while True:
875 newcomp = complete(text,state)
875 newcomp = complete(text,state)
876 if newcomp is None:
876 if newcomp is None:
877 break
877 break
878 comps[newcomp] = 1
878 comps[newcomp] = 1
879 state += 1
879 state += 1
880 outcomps = comps.keys()
880 outcomps = comps.keys()
881 outcomps.sort()
881 outcomps.sort()
882 return outcomps
882 return outcomps
883
883
884 def set_completer_frame(self, frame=None):
884 def set_completer_frame(self, frame=None):
885 if frame:
885 if frame:
886 self.Completer.namespace = frame.f_locals
886 self.Completer.namespace = frame.f_locals
887 self.Completer.global_namespace = frame.f_globals
887 self.Completer.global_namespace = frame.f_globals
888 else:
888 else:
889 self.Completer.namespace = self.user_ns
889 self.Completer.namespace = self.user_ns
890 self.Completer.global_namespace = self.user_global_ns
890 self.Completer.global_namespace = self.user_global_ns
891
891
892 def init_auto_alias(self):
892 def init_auto_alias(self):
893 """Define some aliases automatically.
893 """Define some aliases automatically.
894
894
895 These are ALL parameter-less aliases"""
895 These are ALL parameter-less aliases"""
896
896
897 for alias,cmd in self.auto_alias:
897 for alias,cmd in self.auto_alias:
898 self.alias_table[alias] = (0,cmd)
898 self.alias_table[alias] = (0,cmd)
899
899
900 def alias_table_validate(self,verbose=0):
900 def alias_table_validate(self,verbose=0):
901 """Update information about the alias table.
901 """Update information about the alias table.
902
902
903 In particular, make sure no Python keywords/builtins are in it."""
903 In particular, make sure no Python keywords/builtins are in it."""
904
904
905 no_alias = self.no_alias
905 no_alias = self.no_alias
906 for k in self.alias_table.keys():
906 for k in self.alias_table.keys():
907 if k in no_alias:
907 if k in no_alias:
908 del self.alias_table[k]
908 del self.alias_table[k]
909 if verbose:
909 if verbose:
910 print ("Deleting alias <%s>, it's a Python "
910 print ("Deleting alias <%s>, it's a Python "
911 "keyword or builtin." % k)
911 "keyword or builtin." % k)
912
912
913 def set_autoindent(self,value=None):
913 def set_autoindent(self,value=None):
914 """Set the autoindent flag, checking for readline support.
914 """Set the autoindent flag, checking for readline support.
915
915
916 If called with no arguments, it acts as a toggle."""
916 If called with no arguments, it acts as a toggle."""
917
917
918 if not self.has_readline:
918 if not self.has_readline:
919 if os.name == 'posix':
919 if os.name == 'posix':
920 warn("The auto-indent feature requires the readline library")
920 warn("The auto-indent feature requires the readline library")
921 self.autoindent = 0
921 self.autoindent = 0
922 return
922 return
923 if value is None:
923 if value is None:
924 self.autoindent = not self.autoindent
924 self.autoindent = not self.autoindent
925 else:
925 else:
926 self.autoindent = value
926 self.autoindent = value
927
927
928 def rc_set_toggle(self,rc_field,value=None):
928 def rc_set_toggle(self,rc_field,value=None):
929 """Set or toggle a field in IPython's rc config. structure.
929 """Set or toggle a field in IPython's rc config. structure.
930
930
931 If called with no arguments, it acts as a toggle.
931 If called with no arguments, it acts as a toggle.
932
932
933 If called with a non-existent field, the resulting AttributeError
933 If called with a non-existent field, the resulting AttributeError
934 exception will propagate out."""
934 exception will propagate out."""
935
935
936 rc_val = getattr(self.rc,rc_field)
936 rc_val = getattr(self.rc,rc_field)
937 if value is None:
937 if value is None:
938 value = not rc_val
938 value = not rc_val
939 setattr(self.rc,rc_field,value)
939 setattr(self.rc,rc_field,value)
940
940
941 def user_setup(self,ipythondir,rc_suffix,mode='install'):
941 def user_setup(self,ipythondir,rc_suffix,mode='install'):
942 """Install the user configuration directory.
942 """Install the user configuration directory.
943
943
944 Can be called when running for the first time or to upgrade the user's
944 Can be called when running for the first time or to upgrade the user's
945 .ipython/ directory with the mode parameter. Valid modes are 'install'
945 .ipython/ directory with the mode parameter. Valid modes are 'install'
946 and 'upgrade'."""
946 and 'upgrade'."""
947
947
948 def wait():
948 def wait():
949 try:
949 try:
950 raw_input("Please press <RETURN> to start IPython.")
950 raw_input("Please press <RETURN> to start IPython.")
951 except EOFError:
951 except EOFError:
952 print >> Term.cout
952 print >> Term.cout
953 print '*'*70
953 print '*'*70
954
954
955 cwd = os.getcwd() # remember where we started
955 cwd = os.getcwd() # remember where we started
956 glb = glob.glob
956 glb = glob.glob
957 print '*'*70
957 print '*'*70
958 if mode == 'install':
958 if mode == 'install':
959 print \
959 print \
960 """Welcome to IPython. I will try to create a personal configuration directory
960 """Welcome to IPython. I will try to create a personal configuration directory
961 where you can customize many aspects of IPython's functionality in:\n"""
961 where you can customize many aspects of IPython's functionality in:\n"""
962 else:
962 else:
963 print 'I am going to upgrade your configuration in:'
963 print 'I am going to upgrade your configuration in:'
964
964
965 print ipythondir
965 print ipythondir
966
966
967 rcdirend = os.path.join('IPython','UserConfig')
967 rcdirend = os.path.join('IPython','UserConfig')
968 cfg = lambda d: os.path.join(d,rcdirend)
968 cfg = lambda d: os.path.join(d,rcdirend)
969 try:
969 try:
970 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
970 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
971 except IOError:
971 except IOError:
972 warning = """
972 warning = """
973 Installation error. IPython's directory was not found.
973 Installation error. IPython's directory was not found.
974
974
975 Check the following:
975 Check the following:
976
976
977 The ipython/IPython directory should be in a directory belonging to your
977 The ipython/IPython directory should be in a directory belonging to your
978 PYTHONPATH environment variable (that is, it should be in a directory
978 PYTHONPATH environment variable (that is, it should be in a directory
979 belonging to sys.path). You can copy it explicitly there or just link to it.
979 belonging to sys.path). You can copy it explicitly there or just link to it.
980
980
981 IPython will proceed with builtin defaults.
981 IPython will proceed with builtin defaults.
982 """
982 """
983 warn(warning)
983 warn(warning)
984 wait()
984 wait()
985 return
985 return
986
986
987 if mode == 'install':
987 if mode == 'install':
988 try:
988 try:
989 shutil.copytree(rcdir,ipythondir)
989 shutil.copytree(rcdir,ipythondir)
990 os.chdir(ipythondir)
990 os.chdir(ipythondir)
991 rc_files = glb("ipythonrc*")
991 rc_files = glb("ipythonrc*")
992 for rc_file in rc_files:
992 for rc_file in rc_files:
993 os.rename(rc_file,rc_file+rc_suffix)
993 os.rename(rc_file,rc_file+rc_suffix)
994 except:
994 except:
995 warning = """
995 warning = """
996
996
997 There was a problem with the installation:
997 There was a problem with the installation:
998 %s
998 %s
999 Try to correct it or contact the developers if you think it's a bug.
999 Try to correct it or contact the developers if you think it's a bug.
1000 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1000 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1001 warn(warning)
1001 warn(warning)
1002 wait()
1002 wait()
1003 return
1003 return
1004
1004
1005 elif mode == 'upgrade':
1005 elif mode == 'upgrade':
1006 try:
1006 try:
1007 os.chdir(ipythondir)
1007 os.chdir(ipythondir)
1008 except:
1008 except:
1009 print """
1009 print """
1010 Can not upgrade: changing to directory %s failed. Details:
1010 Can not upgrade: changing to directory %s failed. Details:
1011 %s
1011 %s
1012 """ % (ipythondir,sys.exc_info()[1])
1012 """ % (ipythondir,sys.exc_info()[1])
1013 wait()
1013 wait()
1014 return
1014 return
1015 else:
1015 else:
1016 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1016 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1017 for new_full_path in sources:
1017 for new_full_path in sources:
1018 new_filename = os.path.basename(new_full_path)
1018 new_filename = os.path.basename(new_full_path)
1019 if new_filename.startswith('ipythonrc'):
1019 if new_filename.startswith('ipythonrc'):
1020 new_filename = new_filename + rc_suffix
1020 new_filename = new_filename + rc_suffix
1021 # The config directory should only contain files, skip any
1021 # The config directory should only contain files, skip any
1022 # directories which may be there (like CVS)
1022 # directories which may be there (like CVS)
1023 if os.path.isdir(new_full_path):
1023 if os.path.isdir(new_full_path):
1024 continue
1024 continue
1025 if os.path.exists(new_filename):
1025 if os.path.exists(new_filename):
1026 old_file = new_filename+'.old'
1026 old_file = new_filename+'.old'
1027 if os.path.exists(old_file):
1027 if os.path.exists(old_file):
1028 os.remove(old_file)
1028 os.remove(old_file)
1029 os.rename(new_filename,old_file)
1029 os.rename(new_filename,old_file)
1030 shutil.copy(new_full_path,new_filename)
1030 shutil.copy(new_full_path,new_filename)
1031 else:
1031 else:
1032 raise ValueError,'unrecognized mode for install:',`mode`
1032 raise ValueError,'unrecognized mode for install:',`mode`
1033
1033
1034 # Fix line-endings to those native to each platform in the config
1034 # Fix line-endings to those native to each platform in the config
1035 # directory.
1035 # directory.
1036 try:
1036 try:
1037 os.chdir(ipythondir)
1037 os.chdir(ipythondir)
1038 except:
1038 except:
1039 print """
1039 print """
1040 Problem: changing to directory %s failed.
1040 Problem: changing to directory %s failed.
1041 Details:
1041 Details:
1042 %s
1042 %s
1043
1043
1044 Some configuration files may have incorrect line endings. This should not
1044 Some configuration files may have incorrect line endings. This should not
1045 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1045 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1046 wait()
1046 wait()
1047 else:
1047 else:
1048 for fname in glb('ipythonrc*'):
1048 for fname in glb('ipythonrc*'):
1049 try:
1049 try:
1050 native_line_ends(fname,backup=0)
1050 native_line_ends(fname,backup=0)
1051 except IOError:
1051 except IOError:
1052 pass
1052 pass
1053
1053
1054 if mode == 'install':
1054 if mode == 'install':
1055 print """
1055 print """
1056 Successful installation!
1056 Successful installation!
1057
1057
1058 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1058 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1059 IPython manual (there are both HTML and PDF versions supplied with the
1059 IPython manual (there are both HTML and PDF versions supplied with the
1060 distribution) to make sure that your system environment is properly configured
1060 distribution) to make sure that your system environment is properly configured
1061 to take advantage of IPython's features."""
1061 to take advantage of IPython's features."""
1062 else:
1062 else:
1063 print """
1063 print """
1064 Successful upgrade!
1064 Successful upgrade!
1065
1065
1066 All files in your directory:
1066 All files in your directory:
1067 %(ipythondir)s
1067 %(ipythondir)s
1068 which would have been overwritten by the upgrade were backed up with a .old
1068 which would have been overwritten by the upgrade were backed up with a .old
1069 extension. If you had made particular customizations in those files you may
1069 extension. If you had made particular customizations in those files you may
1070 want to merge them back into the new files.""" % locals()
1070 want to merge them back into the new files.""" % locals()
1071 wait()
1071 wait()
1072 os.chdir(cwd)
1072 os.chdir(cwd)
1073 # end user_setup()
1073 # end user_setup()
1074
1074
1075 def atexit_operations(self):
1075 def atexit_operations(self):
1076 """This will be executed at the time of exit.
1076 """This will be executed at the time of exit.
1077
1077
1078 Saving of persistent data should be performed here. """
1078 Saving of persistent data should be performed here. """
1079
1079
1080 # input history
1080 # input history
1081 self.savehist()
1081 self.savehist()
1082
1082
1083 # Cleanup all tempfiles left around
1083 # Cleanup all tempfiles left around
1084 for tfile in self.tempfiles:
1084 for tfile in self.tempfiles:
1085 try:
1085 try:
1086 os.unlink(tfile)
1086 os.unlink(tfile)
1087 except OSError:
1087 except OSError:
1088 pass
1088 pass
1089
1089
1090 # save the "persistent data" catch-all dictionary
1090 # save the "persistent data" catch-all dictionary
1091 try:
1091 try:
1092 pickle.dump(self.persist, open(self.persist_fname,"w"))
1092 pickle.dump(self.persist, open(self.persist_fname,"w"))
1093 except:
1093 except:
1094 print "*** ERROR *** persistent data saving failed."
1094 print "*** ERROR *** persistent data saving failed."
1095
1095
1096 def savehist(self):
1096 def savehist(self):
1097 """Save input history to a file (via readline library)."""
1097 """Save input history to a file (via readline library)."""
1098 try:
1098 try:
1099 self.readline.write_history_file(self.histfile)
1099 self.readline.write_history_file(self.histfile)
1100 except:
1100 except:
1101 print 'Unable to save IPython command history to file: ' + \
1101 print 'Unable to save IPython command history to file: ' + \
1102 `self.histfile`
1102 `self.histfile`
1103
1103
1104 def pre_readline(self):
1104 def pre_readline(self):
1105 """readline hook to be used at the start of each line.
1105 """readline hook to be used at the start of each line.
1106
1106
1107 Currently it handles auto-indent only."""
1107 Currently it handles auto-indent only."""
1108
1108
1109 self.readline.insert_text(self.indent_current)
1109 self.readline.insert_text(self.indent_current)
1110
1110
1111 def init_readline(self):
1111 def init_readline(self):
1112 """Command history completion/saving/reloading."""
1112 """Command history completion/saving/reloading."""
1113 try:
1113 try:
1114 import readline
1114 import readline
1115 except ImportError:
1115 except ImportError:
1116 self.has_readline = 0
1116 self.has_readline = 0
1117 self.readline = None
1117 self.readline = None
1118 # no point in bugging windows users with this every time:
1118 # no point in bugging windows users with this every time:
1119 if os.name == 'posix':
1119 if os.name == 'posix':
1120 warn('Readline services not available on this platform.')
1120 warn('Readline services not available on this platform.')
1121 else:
1121 else:
1122 import atexit
1122 import atexit
1123 from IPython.completer import IPCompleter
1123 from IPython.completer import IPCompleter
1124 self.Completer = IPCompleter(self,
1124 self.Completer = IPCompleter(self,
1125 self.user_ns,
1125 self.user_ns,
1126 self.user_global_ns,
1126 self.user_global_ns,
1127 self.rc.readline_omit__names,
1127 self.rc.readline_omit__names,
1128 self.alias_table)
1128 self.alias_table)
1129
1129
1130 # Platform-specific configuration
1130 # Platform-specific configuration
1131 if os.name == 'nt':
1131 if os.name == 'nt':
1132 self.readline_startup_hook = readline.set_pre_input_hook
1132 self.readline_startup_hook = readline.set_pre_input_hook
1133 else:
1133 else:
1134 self.readline_startup_hook = readline.set_startup_hook
1134 self.readline_startup_hook = readline.set_startup_hook
1135
1135
1136 # Load user's initrc file (readline config)
1136 # Load user's initrc file (readline config)
1137 inputrc_name = os.environ.get('INPUTRC')
1137 inputrc_name = os.environ.get('INPUTRC')
1138 if inputrc_name is None:
1138 if inputrc_name is None:
1139 home_dir = get_home_dir()
1139 home_dir = get_home_dir()
1140 if home_dir is not None:
1140 if home_dir is not None:
1141 inputrc_name = os.path.join(home_dir,'.inputrc')
1141 inputrc_name = os.path.join(home_dir,'.inputrc')
1142 if os.path.isfile(inputrc_name):
1142 if os.path.isfile(inputrc_name):
1143 try:
1143 try:
1144 readline.read_init_file(inputrc_name)
1144 readline.read_init_file(inputrc_name)
1145 except:
1145 except:
1146 warn('Problems reading readline initialization file <%s>'
1146 warn('Problems reading readline initialization file <%s>'
1147 % inputrc_name)
1147 % inputrc_name)
1148
1148
1149 self.has_readline = 1
1149 self.has_readline = 1
1150 self.readline = readline
1150 self.readline = readline
1151 # save this in sys so embedded copies can restore it properly
1151 # save this in sys so embedded copies can restore it properly
1152 sys.ipcompleter = self.Completer.complete
1152 sys.ipcompleter = self.Completer.complete
1153 readline.set_completer(self.Completer.complete)
1153 readline.set_completer(self.Completer.complete)
1154
1154
1155 # Configure readline according to user's prefs
1155 # Configure readline according to user's prefs
1156 for rlcommand in self.rc.readline_parse_and_bind:
1156 for rlcommand in self.rc.readline_parse_and_bind:
1157 readline.parse_and_bind(rlcommand)
1157 readline.parse_and_bind(rlcommand)
1158
1158
1159 # remove some chars from the delimiters list
1159 # remove some chars from the delimiters list
1160 delims = readline.get_completer_delims()
1160 delims = readline.get_completer_delims()
1161 delims = delims.translate(string._idmap,
1161 delims = delims.translate(string._idmap,
1162 self.rc.readline_remove_delims)
1162 self.rc.readline_remove_delims)
1163 readline.set_completer_delims(delims)
1163 readline.set_completer_delims(delims)
1164 # otherwise we end up with a monster history after a while:
1164 # otherwise we end up with a monster history after a while:
1165 readline.set_history_length(1000)
1165 readline.set_history_length(1000)
1166 try:
1166 try:
1167 #print '*** Reading readline history' # dbg
1167 #print '*** Reading readline history' # dbg
1168 readline.read_history_file(self.histfile)
1168 readline.read_history_file(self.histfile)
1169 except IOError:
1169 except IOError:
1170 pass # It doesn't exist yet.
1170 pass # It doesn't exist yet.
1171
1171
1172 atexit.register(self.atexit_operations)
1172 atexit.register(self.atexit_operations)
1173 del atexit
1173 del atexit
1174
1174
1175 # Configure auto-indent for all platforms
1175 # Configure auto-indent for all platforms
1176 self.set_autoindent(self.rc.autoindent)
1176 self.set_autoindent(self.rc.autoindent)
1177
1177
1178 def _should_recompile(self,e):
1178 def _should_recompile(self,e):
1179 """Utility routine for edit_syntax_error"""
1179 """Utility routine for edit_syntax_error"""
1180
1180
1181 if e.filename in ('<ipython console>','<input>','<string>',
1181 if e.filename in ('<ipython console>','<input>','<string>',
1182 '<console>',None):
1182 '<console>',None):
1183 return False
1183 return False
1184 try:
1184 try:
1185 if not ask_yes_no('Return to editor to correct syntax error? '
1185 if not ask_yes_no('Return to editor to correct syntax error? '
1186 '[Y/n] ','y'):
1186 '[Y/n] ','y'):
1187 return False
1187 return False
1188 except EOFError:
1188 except EOFError:
1189 return False
1189 return False
1190
1190
1191 def int0(x):
1191 def int0(x):
1192 try:
1192 try:
1193 return int(x)
1193 return int(x)
1194 except TypeError:
1194 except TypeError:
1195 return 0
1195 return 0
1196 # always pass integer line and offset values to editor hook
1196 # always pass integer line and offset values to editor hook
1197 self.hooks.fix_error_editor(e.filename,
1197 self.hooks.fix_error_editor(e.filename,
1198 int0(e.lineno),int0(e.offset),e.msg)
1198 int0(e.lineno),int0(e.offset),e.msg)
1199 return True
1199 return True
1200
1200
1201 def edit_syntax_error(self):
1201 def edit_syntax_error(self):
1202 """The bottom half of the syntax error handler called in the main loop.
1202 """The bottom half of the syntax error handler called in the main loop.
1203
1203
1204 Loop until syntax error is fixed or user cancels.
1204 Loop until syntax error is fixed or user cancels.
1205 """
1205 """
1206
1206
1207 while self.SyntaxTB.last_syntax_error:
1207 while self.SyntaxTB.last_syntax_error:
1208 # copy and clear last_syntax_error
1208 # copy and clear last_syntax_error
1209 err = self.SyntaxTB.clear_err_state()
1209 err = self.SyntaxTB.clear_err_state()
1210 if not self._should_recompile(err):
1210 if not self._should_recompile(err):
1211 return
1211 return
1212 try:
1212 try:
1213 # may set last_syntax_error again if a SyntaxError is raised
1213 # may set last_syntax_error again if a SyntaxError is raised
1214 self.safe_execfile(err.filename,self.shell.user_ns)
1214 self.safe_execfile(err.filename,self.shell.user_ns)
1215 except:
1215 except:
1216 self.showtraceback()
1216 self.showtraceback()
1217 else:
1217 else:
1218 f = file(err.filename)
1218 f = file(err.filename)
1219 try:
1219 try:
1220 sys.displayhook(f.read())
1220 sys.displayhook(f.read())
1221 finally:
1221 finally:
1222 f.close()
1222 f.close()
1223
1223
1224 def showsyntaxerror(self, filename=None):
1224 def showsyntaxerror(self, filename=None):
1225 """Display the syntax error that just occurred.
1225 """Display the syntax error that just occurred.
1226
1226
1227 This doesn't display a stack trace because there isn't one.
1227 This doesn't display a stack trace because there isn't one.
1228
1228
1229 If a filename is given, it is stuffed in the exception instead
1229 If a filename is given, it is stuffed in the exception instead
1230 of what was there before (because Python's parser always uses
1230 of what was there before (because Python's parser always uses
1231 "<string>" when reading from a string).
1231 "<string>" when reading from a string).
1232 """
1232 """
1233 etype, value, last_traceback = sys.exc_info()
1233 etype, value, last_traceback = sys.exc_info()
1234 if filename and etype is SyntaxError:
1234 if filename and etype is SyntaxError:
1235 # Work hard to stuff the correct filename in the exception
1235 # Work hard to stuff the correct filename in the exception
1236 try:
1236 try:
1237 msg, (dummy_filename, lineno, offset, line) = value
1237 msg, (dummy_filename, lineno, offset, line) = value
1238 except:
1238 except:
1239 # Not the format we expect; leave it alone
1239 # Not the format we expect; leave it alone
1240 pass
1240 pass
1241 else:
1241 else:
1242 # Stuff in the right filename
1242 # Stuff in the right filename
1243 try:
1243 try:
1244 # Assume SyntaxError is a class exception
1244 # Assume SyntaxError is a class exception
1245 value = SyntaxError(msg, (filename, lineno, offset, line))
1245 value = SyntaxError(msg, (filename, lineno, offset, line))
1246 except:
1246 except:
1247 # If that failed, assume SyntaxError is a string
1247 # If that failed, assume SyntaxError is a string
1248 value = msg, (filename, lineno, offset, line)
1248 value = msg, (filename, lineno, offset, line)
1249 self.SyntaxTB(etype,value,[])
1249 self.SyntaxTB(etype,value,[])
1250
1250
1251 def debugger(self):
1251 def debugger(self):
1252 """Call the pdb debugger."""
1252 """Call the pdb debugger."""
1253
1253
1254 if not self.rc.pdb:
1254 if not self.rc.pdb:
1255 return
1255 return
1256 pdb.pm()
1256 pdb.pm()
1257
1257
1258 def showtraceback(self,exc_tuple = None,filename=None):
1258 def showtraceback(self,exc_tuple = None,filename=None):
1259 """Display the exception that just occurred."""
1259 """Display the exception that just occurred."""
1260
1260
1261 # Though this won't be called by syntax errors in the input line,
1261 # Though this won't be called by syntax errors in the input line,
1262 # there may be SyntaxError cases whith imported code.
1262 # there may be SyntaxError cases whith imported code.
1263 if exc_tuple is None:
1263 if exc_tuple is None:
1264 type, value, tb = sys.exc_info()
1264 type, value, tb = sys.exc_info()
1265 else:
1265 else:
1266 type, value, tb = exc_tuple
1266 type, value, tb = exc_tuple
1267 if type is SyntaxError:
1267 if type is SyntaxError:
1268 self.showsyntaxerror(filename)
1268 self.showsyntaxerror(filename)
1269 else:
1269 else:
1270 self.InteractiveTB()
1270 self.InteractiveTB()
1271 if self.InteractiveTB.call_pdb and self.has_readline:
1271 if self.InteractiveTB.call_pdb and self.has_readline:
1272 # pdb mucks up readline, fix it back
1272 # pdb mucks up readline, fix it back
1273 self.readline.set_completer(self.Completer.complete)
1273 self.readline.set_completer(self.Completer.complete)
1274
1274
1275 def mainloop(self,banner=None):
1275 def mainloop(self,banner=None):
1276 """Creates the local namespace and starts the mainloop.
1276 """Creates the local namespace and starts the mainloop.
1277
1277
1278 If an optional banner argument is given, it will override the
1278 If an optional banner argument is given, it will override the
1279 internally created default banner."""
1279 internally created default banner."""
1280
1280
1281 if self.rc.c: # Emulate Python's -c option
1281 if self.rc.c: # Emulate Python's -c option
1282 self.exec_init_cmd()
1282 self.exec_init_cmd()
1283 if banner is None:
1283 if banner is None:
1284 if self.rc.banner:
1284 if self.rc.banner:
1285 banner = self.BANNER+self.banner2
1285 banner = self.BANNER+self.banner2
1286 else:
1286 else:
1287 banner = ''
1287 banner = ''
1288 self.interact(banner)
1288 self.interact(banner)
1289
1289
1290 def exec_init_cmd(self):
1290 def exec_init_cmd(self):
1291 """Execute a command given at the command line.
1291 """Execute a command given at the command line.
1292
1292
1293 This emulates Python's -c option."""
1293 This emulates Python's -c option."""
1294
1294
1295 sys.argv = ['-c']
1295 sys.argv = ['-c']
1296 self.push(self.rc.c)
1296 self.push(self.rc.c)
1297
1297
1298 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1298 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1299 """Embeds IPython into a running python program.
1299 """Embeds IPython into a running python program.
1300
1300
1301 Input:
1301 Input:
1302
1302
1303 - header: An optional header message can be specified.
1303 - header: An optional header message can be specified.
1304
1304
1305 - local_ns, global_ns: working namespaces. If given as None, the
1305 - local_ns, global_ns: working namespaces. If given as None, the
1306 IPython-initialized one is updated with __main__.__dict__, so that
1306 IPython-initialized one is updated with __main__.__dict__, so that
1307 program variables become visible but user-specific configuration
1307 program variables become visible but user-specific configuration
1308 remains possible.
1308 remains possible.
1309
1309
1310 - stack_depth: specifies how many levels in the stack to go to
1310 - stack_depth: specifies how many levels in the stack to go to
1311 looking for namespaces (when local_ns and global_ns are None). This
1311 looking for namespaces (when local_ns and global_ns are None). This
1312 allows an intermediate caller to make sure that this function gets
1312 allows an intermediate caller to make sure that this function gets
1313 the namespace from the intended level in the stack. By default (0)
1313 the namespace from the intended level in the stack. By default (0)
1314 it will get its locals and globals from the immediate caller.
1314 it will get its locals and globals from the immediate caller.
1315
1315
1316 Warning: it's possible to use this in a program which is being run by
1316 Warning: it's possible to use this in a program which is being run by
1317 IPython itself (via %run), but some funny things will happen (a few
1317 IPython itself (via %run), but some funny things will happen (a few
1318 globals get overwritten). In the future this will be cleaned up, as
1318 globals get overwritten). In the future this will be cleaned up, as
1319 there is no fundamental reason why it can't work perfectly."""
1319 there is no fundamental reason why it can't work perfectly."""
1320
1320
1321 # Get locals and globals from caller
1321 # Get locals and globals from caller
1322 if local_ns is None or global_ns is None:
1322 if local_ns is None or global_ns is None:
1323 call_frame = sys._getframe(stack_depth).f_back
1323 call_frame = sys._getframe(stack_depth).f_back
1324
1324
1325 if local_ns is None:
1325 if local_ns is None:
1326 local_ns = call_frame.f_locals
1326 local_ns = call_frame.f_locals
1327 if global_ns is None:
1327 if global_ns is None:
1328 global_ns = call_frame.f_globals
1328 global_ns = call_frame.f_globals
1329
1329
1330 # Update namespaces and fire up interpreter
1330 # Update namespaces and fire up interpreter
1331
1331
1332 # The global one is easy, we can just throw it in
1332 # The global one is easy, we can just throw it in
1333 self.user_global_ns = global_ns
1333 self.user_global_ns = global_ns
1334
1334
1335 # but the user/local one is tricky: ipython needs it to store internal
1335 # but the user/local one is tricky: ipython needs it to store internal
1336 # data, but we also need the locals. We'll copy locals in the user
1336 # data, but we also need the locals. We'll copy locals in the user
1337 # one, but will track what got copied so we can delete them at exit.
1337 # one, but will track what got copied so we can delete them at exit.
1338 # This is so that a later embedded call doesn't see locals from a
1338 # This is so that a later embedded call doesn't see locals from a
1339 # previous call (which most likely existed in a separate scope).
1339 # previous call (which most likely existed in a separate scope).
1340 local_varnames = local_ns.keys()
1340 local_varnames = local_ns.keys()
1341 self.user_ns.update(local_ns)
1341 self.user_ns.update(local_ns)
1342
1342
1343 # Patch for global embedding to make sure that things don't overwrite
1343 # Patch for global embedding to make sure that things don't overwrite
1344 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1344 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1345 # FIXME. Test this a bit more carefully (the if.. is new)
1345 # FIXME. Test this a bit more carefully (the if.. is new)
1346 if local_ns is None and global_ns is None:
1346 if local_ns is None and global_ns is None:
1347 self.user_global_ns.update(__main__.__dict__)
1347 self.user_global_ns.update(__main__.__dict__)
1348
1348
1349 # make sure the tab-completer has the correct frame information, so it
1349 # make sure the tab-completer has the correct frame information, so it
1350 # actually completes using the frame's locals/globals
1350 # actually completes using the frame's locals/globals
1351 self.set_completer_frame()
1351 self.set_completer_frame()
1352
1352
1353 # before activating the interactive mode, we need to make sure that
1353 # before activating the interactive mode, we need to make sure that
1354 # all names in the builtin namespace needed by ipython point to
1354 # all names in the builtin namespace needed by ipython point to
1355 # ourselves, and not to other instances.
1355 # ourselves, and not to other instances.
1356 self.add_builtins()
1356 self.add_builtins()
1357
1357
1358 self.interact(header)
1358 self.interact(header)
1359
1359
1360 # now, purge out the user namespace from anything we might have added
1360 # now, purge out the user namespace from anything we might have added
1361 # from the caller's local namespace
1361 # from the caller's local namespace
1362 delvar = self.user_ns.pop
1362 delvar = self.user_ns.pop
1363 for var in local_varnames:
1363 for var in local_varnames:
1364 delvar(var,None)
1364 delvar(var,None)
1365 # and clean builtins we may have overridden
1365 # and clean builtins we may have overridden
1366 self.clean_builtins()
1366 self.clean_builtins()
1367
1367
1368 def interact(self, banner=None):
1368 def interact(self, banner=None):
1369 """Closely emulate the interactive Python console.
1369 """Closely emulate the interactive Python console.
1370
1370
1371 The optional banner argument specify the banner to print
1371 The optional banner argument specify the banner to print
1372 before the first interaction; by default it prints a banner
1372 before the first interaction; by default it prints a banner
1373 similar to the one printed by the real Python interpreter,
1373 similar to the one printed by the real Python interpreter,
1374 followed by the current class name in parentheses (so as not
1374 followed by the current class name in parentheses (so as not
1375 to confuse this with the real interpreter -- since it's so
1375 to confuse this with the real interpreter -- since it's so
1376 close!).
1376 close!).
1377
1377
1378 """
1378 """
1379 cprt = 'Type "copyright", "credits" or "license" for more information.'
1379 cprt = 'Type "copyright", "credits" or "license" for more information.'
1380 if banner is None:
1380 if banner is None:
1381 self.write("Python %s on %s\n%s\n(%s)\n" %
1381 self.write("Python %s on %s\n%s\n(%s)\n" %
1382 (sys.version, sys.platform, cprt,
1382 (sys.version, sys.platform, cprt,
1383 self.__class__.__name__))
1383 self.__class__.__name__))
1384 else:
1384 else:
1385 self.write(banner)
1385 self.write(banner)
1386
1386
1387 more = 0
1387 more = 0
1388
1388
1389 # Mark activity in the builtins
1389 # Mark activity in the builtins
1390 __builtin__.__dict__['__IPYTHON__active'] += 1
1390 __builtin__.__dict__['__IPYTHON__active'] += 1
1391
1391
1392 # exit_now is set by a call to %Exit or %Quit
1392 # exit_now is set by a call to %Exit or %Quit
1393 self.exit_now = False
1393 self.exit_now = False
1394 while not self.exit_now:
1394 while not self.exit_now:
1395
1395
1396 try:
1396 try:
1397 if more:
1397 if more:
1398 prompt = self.outputcache.prompt2
1398 prompt = self.outputcache.prompt2
1399 if self.autoindent:
1399 if self.autoindent:
1400 self.readline_startup_hook(self.pre_readline)
1400 self.readline_startup_hook(self.pre_readline)
1401 else:
1401 else:
1402 prompt = self.outputcache.prompt1
1402 prompt = self.outputcache.prompt1
1403 try:
1403 try:
1404 line = self.raw_input(prompt,more)
1404 line = self.raw_input(prompt,more)
1405 if self.autoindent:
1405 if self.autoindent:
1406 self.readline_startup_hook(None)
1406 self.readline_startup_hook(None)
1407 except EOFError:
1407 except EOFError:
1408 if self.autoindent:
1408 if self.autoindent:
1409 self.readline_startup_hook(None)
1409 self.readline_startup_hook(None)
1410 self.write("\n")
1410 self.write("\n")
1411 self.exit()
1411 self.exit()
1412 else:
1412 else:
1413 more = self.push(line)
1413 more = self.push(line)
1414
1414
1415 if (self.SyntaxTB.last_syntax_error and
1415 if (self.SyntaxTB.last_syntax_error and
1416 self.rc.autoedit_syntax):
1416 self.rc.autoedit_syntax):
1417 self.edit_syntax_error()
1417 self.edit_syntax_error()
1418
1418
1419 except KeyboardInterrupt:
1419 except KeyboardInterrupt:
1420 self.write("\nKeyboardInterrupt\n")
1420 self.write("\nKeyboardInterrupt\n")
1421 self.resetbuffer()
1421 self.resetbuffer()
1422 more = 0
1422 more = 0
1423 # keep cache in sync with the prompt counter:
1423 # keep cache in sync with the prompt counter:
1424 self.outputcache.prompt_count -= 1
1424 self.outputcache.prompt_count -= 1
1425
1425
1426 if self.autoindent:
1426 if self.autoindent:
1427 self.indent_current_nsp = 0
1427 self.indent_current_nsp = 0
1428 self.indent_current = ' '* self.indent_current_nsp
1428 self.indent_current = ' '* self.indent_current_nsp
1429
1429
1430 except bdb.BdbQuit:
1430 except bdb.BdbQuit:
1431 warn("The Python debugger has exited with a BdbQuit exception.\n"
1431 warn("The Python debugger has exited with a BdbQuit exception.\n"
1432 "Because of how pdb handles the stack, it is impossible\n"
1432 "Because of how pdb handles the stack, it is impossible\n"
1433 "for IPython to properly format this particular exception.\n"
1433 "for IPython to properly format this particular exception.\n"
1434 "IPython will resume normal operation.")
1434 "IPython will resume normal operation.")
1435
1435
1436 # We are off again...
1436 # We are off again...
1437 __builtin__.__dict__['__IPYTHON__active'] -= 1
1437 __builtin__.__dict__['__IPYTHON__active'] -= 1
1438
1438
1439 def excepthook(self, type, value, tb):
1439 def excepthook(self, type, value, tb):
1440 """One more defense for GUI apps that call sys.excepthook.
1440 """One more defense for GUI apps that call sys.excepthook.
1441
1441
1442 GUI frameworks like wxPython trap exceptions and call
1442 GUI frameworks like wxPython trap exceptions and call
1443 sys.excepthook themselves. I guess this is a feature that
1443 sys.excepthook themselves. I guess this is a feature that
1444 enables them to keep running after exceptions that would
1444 enables them to keep running after exceptions that would
1445 otherwise kill their mainloop. This is a bother for IPython
1445 otherwise kill their mainloop. This is a bother for IPython
1446 which excepts to catch all of the program exceptions with a try:
1446 which excepts to catch all of the program exceptions with a try:
1447 except: statement.
1447 except: statement.
1448
1448
1449 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1449 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1450 any app directly invokes sys.excepthook, it will look to the user like
1450 any app directly invokes sys.excepthook, it will look to the user like
1451 IPython crashed. In order to work around this, we can disable the
1451 IPython crashed. In order to work around this, we can disable the
1452 CrashHandler and replace it with this excepthook instead, which prints a
1452 CrashHandler and replace it with this excepthook instead, which prints a
1453 regular traceback using our InteractiveTB. In this fashion, apps which
1453 regular traceback using our InteractiveTB. In this fashion, apps which
1454 call sys.excepthook will generate a regular-looking exception from
1454 call sys.excepthook will generate a regular-looking exception from
1455 IPython, and the CrashHandler will only be triggered by real IPython
1455 IPython, and the CrashHandler will only be triggered by real IPython
1456 crashes.
1456 crashes.
1457
1457
1458 This hook should be used sparingly, only in places which are not likely
1458 This hook should be used sparingly, only in places which are not likely
1459 to be true IPython errors.
1459 to be true IPython errors.
1460 """
1460 """
1461
1461
1462 self.InteractiveTB(type, value, tb, tb_offset=0)
1462 self.InteractiveTB(type, value, tb, tb_offset=0)
1463 if self.InteractiveTB.call_pdb and self.has_readline:
1463 if self.InteractiveTB.call_pdb and self.has_readline:
1464 self.readline.set_completer(self.Completer.complete)
1464 self.readline.set_completer(self.Completer.complete)
1465
1465
1466 def call_alias(self,alias,rest=''):
1466 def call_alias(self,alias,rest=''):
1467 """Call an alias given its name and the rest of the line.
1467 """Call an alias given its name and the rest of the line.
1468
1468
1469 This function MUST be given a proper alias, because it doesn't make
1469 This function MUST be given a proper alias, because it doesn't make
1470 any checks when looking up into the alias table. The caller is
1470 any checks when looking up into the alias table. The caller is
1471 responsible for invoking it only with a valid alias."""
1471 responsible for invoking it only with a valid alias."""
1472
1472
1473 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1473 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1474 nargs,cmd = self.alias_table[alias]
1474 nargs,cmd = self.alias_table[alias]
1475 # Expand the %l special to be the user's input line
1475 # Expand the %l special to be the user's input line
1476 if cmd.find('%l') >= 0:
1476 if cmd.find('%l') >= 0:
1477 cmd = cmd.replace('%l',rest)
1477 cmd = cmd.replace('%l',rest)
1478 rest = ''
1478 rest = ''
1479 if nargs==0:
1479 if nargs==0:
1480 # Simple, argument-less aliases
1480 # Simple, argument-less aliases
1481 cmd = '%s %s' % (cmd,rest)
1481 cmd = '%s %s' % (cmd,rest)
1482 else:
1482 else:
1483 # Handle aliases with positional arguments
1483 # Handle aliases with positional arguments
1484 args = rest.split(None,nargs)
1484 args = rest.split(None,nargs)
1485 if len(args)< nargs:
1485 if len(args)< nargs:
1486 error('Alias <%s> requires %s arguments, %s given.' %
1486 error('Alias <%s> requires %s arguments, %s given.' %
1487 (alias,nargs,len(args)))
1487 (alias,nargs,len(args)))
1488 return
1488 return
1489 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1489 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1490 # Now call the macro, evaluating in the user's namespace
1490 # Now call the macro, evaluating in the user's namespace
1491 try:
1491 try:
1492 self.system(cmd)
1492 self.system(cmd)
1493 except:
1493 except:
1494 self.showtraceback()
1494 self.showtraceback()
1495
1495
1496 def autoindent_update(self,line):
1496 def autoindent_update(self,line):
1497 """Keep track of the indent level."""
1497 """Keep track of the indent level."""
1498 if self.autoindent:
1498 if self.autoindent:
1499 if line:
1499 if line:
1500 ini_spaces = ini_spaces_re.match(line)
1500 ini_spaces = ini_spaces_re.match(line)
1501 if ini_spaces:
1501 if ini_spaces:
1502 nspaces = ini_spaces.end()
1502 nspaces = ini_spaces.end()
1503 else:
1503 else:
1504 nspaces = 0
1504 nspaces = 0
1505 self.indent_current_nsp = nspaces
1505 self.indent_current_nsp = nspaces
1506
1506
1507 if line[-1] == ':':
1507 if line[-1] == ':':
1508 self.indent_current_nsp += 4
1508 self.indent_current_nsp += 4
1509 elif dedent_re.match(line):
1509 elif dedent_re.match(line):
1510 self.indent_current_nsp -= 4
1510 self.indent_current_nsp -= 4
1511 else:
1511 else:
1512 self.indent_current_nsp = 0
1512 self.indent_current_nsp = 0
1513
1513
1514 # indent_current is the actual string to be inserted
1514 # indent_current is the actual string to be inserted
1515 # by the readline hooks for indentation
1515 # by the readline hooks for indentation
1516 self.indent_current = ' '* self.indent_current_nsp
1516 self.indent_current = ' '* self.indent_current_nsp
1517
1517
1518 def runlines(self,lines):
1518 def runlines(self,lines):
1519 """Run a string of one or more lines of source.
1519 """Run a string of one or more lines of source.
1520
1520
1521 This method is capable of running a string containing multiple source
1521 This method is capable of running a string containing multiple source
1522 lines, as if they had been entered at the IPython prompt. Since it
1522 lines, as if they had been entered at the IPython prompt. Since it
1523 exposes IPython's processing machinery, the given strings can contain
1523 exposes IPython's processing machinery, the given strings can contain
1524 magic calls (%magic), special shell access (!cmd), etc."""
1524 magic calls (%magic), special shell access (!cmd), etc."""
1525
1525
1526 # We must start with a clean buffer, in case this is run from an
1526 # We must start with a clean buffer, in case this is run from an
1527 # interactive IPython session (via a magic, for example).
1527 # interactive IPython session (via a magic, for example).
1528 self.resetbuffer()
1528 self.resetbuffer()
1529 lines = lines.split('\n')
1529 lines = lines.split('\n')
1530 more = 0
1530 more = 0
1531 for line in lines:
1531 for line in lines:
1532 # skip blank lines so we don't mess up the prompt counter, but do
1532 # skip blank lines so we don't mess up the prompt counter, but do
1533 # NOT skip even a blank line if we are in a code block (more is
1533 # NOT skip even a blank line if we are in a code block (more is
1534 # true)
1534 # true)
1535 if line or more:
1535 if line or more:
1536 more = self.push(self.prefilter(line,more))
1536 more = self.push(self.prefilter(line,more))
1537 # IPython's runsource returns None if there was an error
1537 # IPython's runsource returns None if there was an error
1538 # compiling the code. This allows us to stop processing right
1538 # compiling the code. This allows us to stop processing right
1539 # away, so the user gets the error message at the right place.
1539 # away, so the user gets the error message at the right place.
1540 if more is None:
1540 if more is None:
1541 break
1541 break
1542 # final newline in case the input didn't have it, so that the code
1542 # final newline in case the input didn't have it, so that the code
1543 # actually does get executed
1543 # actually does get executed
1544 if more:
1544 if more:
1545 self.push('\n')
1545 self.push('\n')
1546
1546
1547 def runsource(self, source, filename='<input>', symbol='single'):
1547 def runsource(self, source, filename='<input>', symbol='single'):
1548 """Compile and run some source in the interpreter.
1548 """Compile and run some source in the interpreter.
1549
1549
1550 Arguments are as for compile_command().
1550 Arguments are as for compile_command().
1551
1551
1552 One several things can happen:
1552 One several things can happen:
1553
1553
1554 1) The input is incorrect; compile_command() raised an
1554 1) The input is incorrect; compile_command() raised an
1555 exception (SyntaxError or OverflowError). A syntax traceback
1555 exception (SyntaxError or OverflowError). A syntax traceback
1556 will be printed by calling the showsyntaxerror() method.
1556 will be printed by calling the showsyntaxerror() method.
1557
1557
1558 2) The input is incomplete, and more input is required;
1558 2) The input is incomplete, and more input is required;
1559 compile_command() returned None. Nothing happens.
1559 compile_command() returned None. Nothing happens.
1560
1560
1561 3) The input is complete; compile_command() returned a code
1561 3) The input is complete; compile_command() returned a code
1562 object. The code is executed by calling self.runcode() (which
1562 object. The code is executed by calling self.runcode() (which
1563 also handles run-time exceptions, except for SystemExit).
1563 also handles run-time exceptions, except for SystemExit).
1564
1564
1565 The return value is:
1565 The return value is:
1566
1566
1567 - True in case 2
1567 - True in case 2
1568
1568
1569 - False in the other cases, unless an exception is raised, where
1569 - False in the other cases, unless an exception is raised, where
1570 None is returned instead. This can be used by external callers to
1570 None is returned instead. This can be used by external callers to
1571 know whether to continue feeding input or not.
1571 know whether to continue feeding input or not.
1572
1572
1573 The return value can be used to decide whether to use sys.ps1 or
1573 The return value can be used to decide whether to use sys.ps1 or
1574 sys.ps2 to prompt the next line."""
1574 sys.ps2 to prompt the next line."""
1575
1575
1576 try:
1576 try:
1577 code = self.compile(source,filename,symbol)
1577 code = self.compile(source,filename,symbol)
1578 except (OverflowError, SyntaxError, ValueError):
1578 except (OverflowError, SyntaxError, ValueError):
1579 # Case 1
1579 # Case 1
1580 self.showsyntaxerror(filename)
1580 self.showsyntaxerror(filename)
1581 return None
1581 return None
1582
1582
1583 if code is None:
1583 if code is None:
1584 # Case 2
1584 # Case 2
1585 return True
1585 return True
1586
1586
1587 # Case 3
1587 # Case 3
1588 # We store the code object so that threaded shells and
1588 # We store the code object so that threaded shells and
1589 # custom exception handlers can access all this info if needed.
1589 # custom exception handlers can access all this info if needed.
1590 # The source corresponding to this can be obtained from the
1590 # The source corresponding to this can be obtained from the
1591 # buffer attribute as '\n'.join(self.buffer).
1591 # buffer attribute as '\n'.join(self.buffer).
1592 self.code_to_run = code
1592 self.code_to_run = code
1593 # now actually execute the code object
1593 # now actually execute the code object
1594 if self.runcode(code) == 0:
1594 if self.runcode(code) == 0:
1595 return False
1595 return False
1596 else:
1596 else:
1597 return None
1597 return None
1598
1598
1599 def runcode(self,code_obj):
1599 def runcode(self,code_obj):
1600 """Execute a code object.
1600 """Execute a code object.
1601
1601
1602 When an exception occurs, self.showtraceback() is called to display a
1602 When an exception occurs, self.showtraceback() is called to display a
1603 traceback.
1603 traceback.
1604
1604
1605 Return value: a flag indicating whether the code to be run completed
1605 Return value: a flag indicating whether the code to be run completed
1606 successfully:
1606 successfully:
1607
1607
1608 - 0: successful execution.
1608 - 0: successful execution.
1609 - 1: an error occurred.
1609 - 1: an error occurred.
1610 """
1610 """
1611
1611
1612 # Set our own excepthook in case the user code tries to call it
1612 # Set our own excepthook in case the user code tries to call it
1613 # directly, so that the IPython crash handler doesn't get triggered
1613 # directly, so that the IPython crash handler doesn't get triggered
1614 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1614 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1615
1615
1616 # we save the original sys.excepthook in the instance, in case config
1616 # we save the original sys.excepthook in the instance, in case config
1617 # code (such as magics) needs access to it.
1617 # code (such as magics) needs access to it.
1618 self.sys_excepthook = old_excepthook
1618 self.sys_excepthook = old_excepthook
1619 outflag = 1 # happens in more places, so it's easier as default
1619 outflag = 1 # happens in more places, so it's easier as default
1620 try:
1620 try:
1621 try:
1621 try:
1622 # Embedded instances require separate global/local namespaces
1622 # Embedded instances require separate global/local namespaces
1623 # so they can see both the surrounding (local) namespace and
1623 # so they can see both the surrounding (local) namespace and
1624 # the module-level globals when called inside another function.
1624 # the module-level globals when called inside another function.
1625 if self.embedded:
1625 if self.embedded:
1626 exec code_obj in self.user_global_ns, self.user_ns
1626 exec code_obj in self.user_global_ns, self.user_ns
1627 # Normal (non-embedded) instances should only have a single
1627 # Normal (non-embedded) instances should only have a single
1628 # namespace for user code execution, otherwise functions won't
1628 # namespace for user code execution, otherwise functions won't
1629 # see interactive top-level globals.
1629 # see interactive top-level globals.
1630 else:
1630 else:
1631 exec code_obj in self.user_ns
1631 exec code_obj in self.user_ns
1632 finally:
1632 finally:
1633 # Reset our crash handler in place
1633 # Reset our crash handler in place
1634 sys.excepthook = old_excepthook
1634 sys.excepthook = old_excepthook
1635 except SystemExit:
1635 except SystemExit:
1636 self.resetbuffer()
1636 self.resetbuffer()
1637 self.showtraceback()
1637 self.showtraceback()
1638 warn("Type exit or quit to exit IPython "
1638 warn("Type exit or quit to exit IPython "
1639 "(%Exit or %Quit do so unconditionally).",level=1)
1639 "(%Exit or %Quit do so unconditionally).",level=1)
1640 except self.custom_exceptions:
1640 except self.custom_exceptions:
1641 etype,value,tb = sys.exc_info()
1641 etype,value,tb = sys.exc_info()
1642 self.CustomTB(etype,value,tb)
1642 self.CustomTB(etype,value,tb)
1643 except:
1643 except:
1644 self.showtraceback()
1644 self.showtraceback()
1645 else:
1645 else:
1646 outflag = 0
1646 outflag = 0
1647 if softspace(sys.stdout, 0):
1647 if softspace(sys.stdout, 0):
1648 print
1648 print
1649 # Flush out code object which has been run (and source)
1649 # Flush out code object which has been run (and source)
1650 self.code_to_run = None
1650 self.code_to_run = None
1651 return outflag
1651 return outflag
1652
1652
1653 def push(self, line):
1653 def push(self, line):
1654 """Push a line to the interpreter.
1654 """Push a line to the interpreter.
1655
1655
1656 The line should not have a trailing newline; it may have
1656 The line should not have a trailing newline; it may have
1657 internal newlines. The line is appended to a buffer and the
1657 internal newlines. The line is appended to a buffer and the
1658 interpreter's runsource() method is called with the
1658 interpreter's runsource() method is called with the
1659 concatenated contents of the buffer as source. If this
1659 concatenated contents of the buffer as source. If this
1660 indicates that the command was executed or invalid, the buffer
1660 indicates that the command was executed or invalid, the buffer
1661 is reset; otherwise, the command is incomplete, and the buffer
1661 is reset; otherwise, the command is incomplete, and the buffer
1662 is left as it was after the line was appended. The return
1662 is left as it was after the line was appended. The return
1663 value is 1 if more input is required, 0 if the line was dealt
1663 value is 1 if more input is required, 0 if the line was dealt
1664 with in some way (this is the same as runsource()).
1664 with in some way (this is the same as runsource()).
1665 """
1665 """
1666
1666
1667 # autoindent management should be done here, and not in the
1667 # autoindent management should be done here, and not in the
1668 # interactive loop, since that one is only seen by keyboard input. We
1668 # interactive loop, since that one is only seen by keyboard input. We
1669 # need this done correctly even for code run via runlines (which uses
1669 # need this done correctly even for code run via runlines (which uses
1670 # push).
1670 # push).
1671
1671
1672 #print 'push line: <%s>' % line # dbg
1672 #print 'push line: <%s>' % line # dbg
1673 self.autoindent_update(line)
1673 self.autoindent_update(line)
1674
1674
1675 self.buffer.append(line)
1675 self.buffer.append(line)
1676 more = self.runsource('\n'.join(self.buffer), self.filename)
1676 more = self.runsource('\n'.join(self.buffer), self.filename)
1677 if not more:
1677 if not more:
1678 self.resetbuffer()
1678 self.resetbuffer()
1679 return more
1679 return more
1680
1680
1681 def resetbuffer(self):
1681 def resetbuffer(self):
1682 """Reset the input buffer."""
1682 """Reset the input buffer."""
1683 self.buffer[:] = []
1683 self.buffer[:] = []
1684
1684
1685 def raw_input(self,prompt='',continue_prompt=False):
1685 def raw_input(self,prompt='',continue_prompt=False):
1686 """Write a prompt and read a line.
1686 """Write a prompt and read a line.
1687
1687
1688 The returned line does not include the trailing newline.
1688 The returned line does not include the trailing newline.
1689 When the user enters the EOF key sequence, EOFError is raised.
1689 When the user enters the EOF key sequence, EOFError is raised.
1690
1690
1691 Optional inputs:
1691 Optional inputs:
1692
1692
1693 - prompt(''): a string to be printed to prompt the user.
1693 - prompt(''): a string to be printed to prompt the user.
1694
1694
1695 - continue_prompt(False): whether this line is the first one or a
1695 - continue_prompt(False): whether this line is the first one or a
1696 continuation in a sequence of inputs.
1696 continuation in a sequence of inputs.
1697 """
1697 """
1698
1698
1699 line = raw_input_original(prompt)
1699 line = raw_input_original(prompt)
1700 # Try to be reasonably smart about not re-indenting pasted input more
1700 # Try to be reasonably smart about not re-indenting pasted input more
1701 # than necessary. We do this by trimming out the auto-indent initial
1701 # than necessary. We do this by trimming out the auto-indent initial
1702 # spaces, if the user's actual input started itself with whitespace.
1702 # spaces, if the user's actual input started itself with whitespace.
1703 if self.autoindent:
1703 if self.autoindent:
1704 line2 = line[self.indent_current_nsp:]
1704 line2 = line[self.indent_current_nsp:]
1705 if line2[0:1] in (' ','\t'):
1705 if line2[0:1] in (' ','\t'):
1706 line = line2
1706 line = line2
1707 return self.prefilter(line,continue_prompt)
1707 return self.prefilter(line,continue_prompt)
1708
1708
1709 def split_user_input(self,line):
1709 def split_user_input(self,line):
1710 """Split user input into pre-char, function part and rest."""
1710 """Split user input into pre-char, function part and rest."""
1711
1711
1712 lsplit = self.line_split.match(line)
1712 lsplit = self.line_split.match(line)
1713 if lsplit is None: # no regexp match returns None
1713 if lsplit is None: # no regexp match returns None
1714 try:
1714 try:
1715 iFun,theRest = line.split(None,1)
1715 iFun,theRest = line.split(None,1)
1716 except ValueError:
1716 except ValueError:
1717 iFun,theRest = line,''
1717 iFun,theRest = line,''
1718 pre = re.match('^(\s*)(.*)',line).groups()[0]
1718 pre = re.match('^(\s*)(.*)',line).groups()[0]
1719 else:
1719 else:
1720 pre,iFun,theRest = lsplit.groups()
1720 pre,iFun,theRest = lsplit.groups()
1721
1721
1722 #print 'line:<%s>' % line # dbg
1722 #print 'line:<%s>' % line # dbg
1723 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1723 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1724 return pre,iFun.strip(),theRest
1724 return pre,iFun.strip(),theRest
1725
1725
1726 def _prefilter(self, line, continue_prompt):
1726 def _prefilter(self, line, continue_prompt):
1727 """Calls different preprocessors, depending on the form of line."""
1727 """Calls different preprocessors, depending on the form of line."""
1728
1728
1729 # All handlers *must* return a value, even if it's blank ('').
1729 # All handlers *must* return a value, even if it's blank ('').
1730
1730
1731 # Lines are NOT logged here. Handlers should process the line as
1731 # Lines are NOT logged here. Handlers should process the line as
1732 # needed, update the cache AND log it (so that the input cache array
1732 # needed, update the cache AND log it (so that the input cache array
1733 # stays synced).
1733 # stays synced).
1734
1734
1735 # This function is _very_ delicate, and since it's also the one which
1735 # This function is _very_ delicate, and since it's also the one which
1736 # determines IPython's response to user input, it must be as efficient
1736 # determines IPython's response to user input, it must be as efficient
1737 # as possible. For this reason it has _many_ returns in it, trying
1737 # as possible. For this reason it has _many_ returns in it, trying
1738 # always to exit as quickly as it can figure out what it needs to do.
1738 # always to exit as quickly as it can figure out what it needs to do.
1739
1739
1740 # This function is the main responsible for maintaining IPython's
1740 # This function is the main responsible for maintaining IPython's
1741 # behavior respectful of Python's semantics. So be _very_ careful if
1741 # behavior respectful of Python's semantics. So be _very_ careful if
1742 # making changes to anything here.
1742 # making changes to anything here.
1743
1743
1744 #.....................................................................
1744 #.....................................................................
1745 # Code begins
1745 # Code begins
1746
1746
1747 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1747 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1748
1748
1749 # save the line away in case we crash, so the post-mortem handler can
1749 # save the line away in case we crash, so the post-mortem handler can
1750 # record it
1750 # record it
1751 self._last_input_line = line
1751 self._last_input_line = line
1752
1752
1753 #print '***line: <%s>' % line # dbg
1753 #print '***line: <%s>' % line # dbg
1754
1754
1755 # the input history needs to track even empty lines
1755 # the input history needs to track even empty lines
1756 if not line.strip():
1756 if not line.strip():
1757 if not continue_prompt:
1757 if not continue_prompt:
1758 self.outputcache.prompt_count -= 1
1758 self.outputcache.prompt_count -= 1
1759 return self.handle_normal(line,continue_prompt)
1759 return self.handle_normal(line,continue_prompt)
1760 #return self.handle_normal('',continue_prompt)
1760 #return self.handle_normal('',continue_prompt)
1761
1761
1762 # print '***cont',continue_prompt # dbg
1762 # print '***cont',continue_prompt # dbg
1763 # special handlers are only allowed for single line statements
1763 # special handlers are only allowed for single line statements
1764 if continue_prompt and not self.rc.multi_line_specials:
1764 if continue_prompt and not self.rc.multi_line_specials:
1765 return self.handle_normal(line,continue_prompt)
1765 return self.handle_normal(line,continue_prompt)
1766
1766
1767 # For the rest, we need the structure of the input
1767 # For the rest, we need the structure of the input
1768 pre,iFun,theRest = self.split_user_input(line)
1768 pre,iFun,theRest = self.split_user_input(line)
1769 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1769 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1770
1770
1771 # First check for explicit escapes in the last/first character
1771 # First check for explicit escapes in the last/first character
1772 handler = None
1772 handler = None
1773 if line[-1] == self.ESC_HELP:
1773 if line[-1] == self.ESC_HELP:
1774 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1774 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1775 if handler is None:
1775 if handler is None:
1776 # look at the first character of iFun, NOT of line, so we skip
1776 # look at the first character of iFun, NOT of line, so we skip
1777 # leading whitespace in multiline input
1777 # leading whitespace in multiline input
1778 handler = self.esc_handlers.get(iFun[0:1])
1778 handler = self.esc_handlers.get(iFun[0:1])
1779 if handler is not None:
1779 if handler is not None:
1780 return handler(line,continue_prompt,pre,iFun,theRest)
1780 return handler(line,continue_prompt,pre,iFun,theRest)
1781 # Emacs ipython-mode tags certain input lines
1781 # Emacs ipython-mode tags certain input lines
1782 if line.endswith('# PYTHON-MODE'):
1782 if line.endswith('# PYTHON-MODE'):
1783 return self.handle_emacs(line,continue_prompt)
1783 return self.handle_emacs(line,continue_prompt)
1784
1784
1785 # Next, check if we can automatically execute this thing
1785 # Next, check if we can automatically execute this thing
1786
1786
1787 # Allow ! in multi-line statements if multi_line_specials is on:
1787 # Allow ! in multi-line statements if multi_line_specials is on:
1788 if continue_prompt and self.rc.multi_line_specials and \
1788 if continue_prompt and self.rc.multi_line_specials and \
1789 iFun.startswith(self.ESC_SHELL):
1789 iFun.startswith(self.ESC_SHELL):
1790 return self.handle_shell_escape(line,continue_prompt,
1790 return self.handle_shell_escape(line,continue_prompt,
1791 pre=pre,iFun=iFun,
1791 pre=pre,iFun=iFun,
1792 theRest=theRest)
1792 theRest=theRest)
1793
1793
1794 # Let's try to find if the input line is a magic fn
1794 # Let's try to find if the input line is a magic fn
1795 oinfo = None
1795 oinfo = None
1796 if hasattr(self,'magic_'+iFun):
1796 if hasattr(self,'magic_'+iFun):
1797 # WARNING: _ofind uses getattr(), so it can consume generators and
1797 # WARNING: _ofind uses getattr(), so it can consume generators and
1798 # cause other side effects.
1798 # cause other side effects.
1799 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1799 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1800 if oinfo['ismagic']:
1800 if oinfo['ismagic']:
1801 # Be careful not to call magics when a variable assignment is
1801 # Be careful not to call magics when a variable assignment is
1802 # being made (ls='hi', for example)
1802 # being made (ls='hi', for example)
1803 if self.rc.automagic and \
1803 if self.rc.automagic and \
1804 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1804 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1805 (self.rc.multi_line_specials or not continue_prompt):
1805 (self.rc.multi_line_specials or not continue_prompt):
1806 return self.handle_magic(line,continue_prompt,
1806 return self.handle_magic(line,continue_prompt,
1807 pre,iFun,theRest)
1807 pre,iFun,theRest)
1808 else:
1808 else:
1809 return self.handle_normal(line,continue_prompt)
1809 return self.handle_normal(line,continue_prompt)
1810
1810
1811 # If the rest of the line begins with an (in)equality, assginment or
1811 # If the rest of the line begins with an (in)equality, assginment or
1812 # function call, we should not call _ofind but simply execute it.
1812 # function call, we should not call _ofind but simply execute it.
1813 # This avoids spurious geattr() accesses on objects upon assignment.
1813 # This avoids spurious geattr() accesses on objects upon assignment.
1814 #
1814 #
1815 # It also allows users to assign to either alias or magic names true
1815 # It also allows users to assign to either alias or magic names true
1816 # python variables (the magic/alias systems always take second seat to
1816 # python variables (the magic/alias systems always take second seat to
1817 # true python code).
1817 # true python code).
1818 if theRest and theRest[0] in '!=()':
1818 if theRest and theRest[0] in '!=()':
1819 return self.handle_normal(line,continue_prompt)
1819 return self.handle_normal(line,continue_prompt)
1820
1820
1821 if oinfo is None:
1821 if oinfo is None:
1822 # let's try to ensure that _oinfo is ONLY called when autocall is
1822 # let's try to ensure that _oinfo is ONLY called when autocall is
1823 # on. Since it has inevitable potential side effects, at least
1823 # on. Since it has inevitable potential side effects, at least
1824 # having autocall off should be a guarantee to the user that no
1824 # having autocall off should be a guarantee to the user that no
1825 # weird things will happen.
1825 # weird things will happen.
1826
1826
1827 if self.rc.autocall:
1827 if self.rc.autocall:
1828 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1828 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1829 else:
1829 else:
1830 # in this case, all that's left is either an alias or
1830 # in this case, all that's left is either an alias or
1831 # processing the line normally.
1831 # processing the line normally.
1832 if iFun in self.alias_table:
1832 if iFun in self.alias_table:
1833 return self.handle_alias(line,continue_prompt,
1833 return self.handle_alias(line,continue_prompt,
1834 pre,iFun,theRest)
1834 pre,iFun,theRest)
1835 else:
1835 else:
1836 return self.handle_normal(line,continue_prompt)
1836 return self.handle_normal(line,continue_prompt)
1837
1837
1838 if not oinfo['found']:
1838 if not oinfo['found']:
1839 return self.handle_normal(line,continue_prompt)
1839 return self.handle_normal(line,continue_prompt)
1840 else:
1840 else:
1841 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1841 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1842 if oinfo['isalias']:
1842 if oinfo['isalias']:
1843 return self.handle_alias(line,continue_prompt,
1843 return self.handle_alias(line,continue_prompt,
1844 pre,iFun,theRest)
1844 pre,iFun,theRest)
1845
1845
1846 if self.rc.autocall and \
1846 if self.rc.autocall and \
1847 not self.re_exclude_auto.match(theRest) and \
1847 not self.re_exclude_auto.match(theRest) and \
1848 self.re_fun_name.match(iFun) and \
1848 self.re_fun_name.match(iFun) and \
1849 callable(oinfo['obj']) :
1849 callable(oinfo['obj']) :
1850 #print 'going auto' # dbg
1850 #print 'going auto' # dbg
1851 return self.handle_auto(line,continue_prompt,
1851 return self.handle_auto(line,continue_prompt,
1852 pre,iFun,theRest,oinfo['obj'])
1852 pre,iFun,theRest,oinfo['obj'])
1853 else:
1853 else:
1854 #print 'was callable?', callable(oinfo['obj']) # dbg
1854 #print 'was callable?', callable(oinfo['obj']) # dbg
1855 return self.handle_normal(line,continue_prompt)
1855 return self.handle_normal(line,continue_prompt)
1856
1856
1857 # If we get here, we have a normal Python line. Log and return.
1857 # If we get here, we have a normal Python line. Log and return.
1858 return self.handle_normal(line,continue_prompt)
1858 return self.handle_normal(line,continue_prompt)
1859
1859
1860 def _prefilter_dumb(self, line, continue_prompt):
1860 def _prefilter_dumb(self, line, continue_prompt):
1861 """simple prefilter function, for debugging"""
1861 """simple prefilter function, for debugging"""
1862 return self.handle_normal(line,continue_prompt)
1862 return self.handle_normal(line,continue_prompt)
1863
1863
1864 # Set the default prefilter() function (this can be user-overridden)
1864 # Set the default prefilter() function (this can be user-overridden)
1865 prefilter = _prefilter
1865 prefilter = _prefilter
1866
1866
1867 def handle_normal(self,line,continue_prompt=None,
1867 def handle_normal(self,line,continue_prompt=None,
1868 pre=None,iFun=None,theRest=None):
1868 pre=None,iFun=None,theRest=None):
1869 """Handle normal input lines. Use as a template for handlers."""
1869 """Handle normal input lines. Use as a template for handlers."""
1870
1870
1871 # With autoindent on, we need some way to exit the input loop, and I
1871 # With autoindent on, we need some way to exit the input loop, and I
1872 # don't want to force the user to have to backspace all the way to
1872 # don't want to force the user to have to backspace all the way to
1873 # clear the line. The rule will be in this case, that either two
1873 # clear the line. The rule will be in this case, that either two
1874 # lines of pure whitespace in a row, or a line of pure whitespace but
1874 # lines of pure whitespace in a row, or a line of pure whitespace but
1875 # of a size different to the indent level, will exit the input loop.
1875 # of a size different to the indent level, will exit the input loop.
1876
1876
1877 if (continue_prompt and self.autoindent and isspace(line) and
1877 if (continue_prompt and self.autoindent and isspace(line) and
1878 (line != self.indent_current or isspace(self.buffer[-1]))):
1878 (line != self.indent_current or isspace(self.buffer[-1]))):
1879 line = ''
1879 line = ''
1880
1880
1881 self.log(line,continue_prompt)
1881 self.log(line,continue_prompt)
1882 return line
1882 return line
1883
1883
1884 def handle_alias(self,line,continue_prompt=None,
1884 def handle_alias(self,line,continue_prompt=None,
1885 pre=None,iFun=None,theRest=None):
1885 pre=None,iFun=None,theRest=None):
1886 """Handle alias input lines. """
1886 """Handle alias input lines. """
1887
1887
1888 # pre is needed, because it carries the leading whitespace. Otherwise
1888 # pre is needed, because it carries the leading whitespace. Otherwise
1889 # aliases won't work in indented sections.
1889 # aliases won't work in indented sections.
1890 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1890 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1891 self.log(line_out,continue_prompt)
1891 self.log(line_out,continue_prompt)
1892 return line_out
1892 return line_out
1893
1893
1894 def handle_shell_escape(self, line, continue_prompt=None,
1894 def handle_shell_escape(self, line, continue_prompt=None,
1895 pre=None,iFun=None,theRest=None):
1895 pre=None,iFun=None,theRest=None):
1896 """Execute the line in a shell, empty return value"""
1896 """Execute the line in a shell, empty return value"""
1897
1897
1898 #print 'line in :', `line` # dbg
1898 #print 'line in :', `line` # dbg
1899 # Example of a special handler. Others follow a similar pattern.
1899 # Example of a special handler. Others follow a similar pattern.
1900 if continue_prompt: # multi-line statements
1900 if continue_prompt: # multi-line statements
1901 if iFun.startswith('!!'):
1901 if iFun.startswith('!!'):
1902 print 'SyntaxError: !! is not allowed in multiline statements'
1902 print 'SyntaxError: !! is not allowed in multiline statements'
1903 return pre
1903 return pre
1904 else:
1904 else:
1905 cmd = ("%s %s" % (iFun[1:],theRest))
1905 cmd = ("%s %s" % (iFun[1:],theRest))
1906 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1906 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1907 else: # single-line input
1907 else: # single-line input
1908 if line.startswith('!!'):
1908 if line.startswith('!!'):
1909 # rewrite iFun/theRest to properly hold the call to %sx and
1909 # rewrite iFun/theRest to properly hold the call to %sx and
1910 # the actual command to be executed, so handle_magic can work
1910 # the actual command to be executed, so handle_magic can work
1911 # correctly
1911 # correctly
1912 theRest = '%s %s' % (iFun[2:],theRest)
1912 theRest = '%s %s' % (iFun[2:],theRest)
1913 iFun = 'sx'
1913 iFun = 'sx'
1914 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1914 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1915 continue_prompt,pre,iFun,theRest)
1915 continue_prompt,pre,iFun,theRest)
1916 else:
1916 else:
1917 cmd=line[1:]
1917 cmd=line[1:]
1918 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1918 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1919 # update cache/log and return
1919 # update cache/log and return
1920 self.log(line_out,continue_prompt)
1920 self.log(line_out,continue_prompt)
1921 return line_out
1921 return line_out
1922
1922
1923 def handle_magic(self, line, continue_prompt=None,
1923 def handle_magic(self, line, continue_prompt=None,
1924 pre=None,iFun=None,theRest=None):
1924 pre=None,iFun=None,theRest=None):
1925 """Execute magic functions.
1925 """Execute magic functions.
1926
1926
1927 Also log them with a prepended # so the log is clean Python."""
1927 Also log them with a prepended # so the log is clean Python."""
1928
1928
1929 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1929 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1930 self.log(cmd,continue_prompt)
1930 self.log(cmd,continue_prompt)
1931 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1931 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1932 return cmd
1932 return cmd
1933
1933
1934 def handle_auto(self, line, continue_prompt=None,
1934 def handle_auto(self, line, continue_prompt=None,
1935 pre=None,iFun=None,theRest=None,obj=None):
1935 pre=None,iFun=None,theRest=None,obj=None):
1936 """Hande lines which can be auto-executed, quoting if requested."""
1936 """Hande lines which can be auto-executed, quoting if requested."""
1937
1937
1938 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1938 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1939
1939
1940 # This should only be active for single-line input!
1940 # This should only be active for single-line input!
1941 if continue_prompt:
1941 if continue_prompt:
1942 self.log(line,continue_prompt)
1942 self.log(line,continue_prompt)
1943 return line
1943 return line
1944
1944
1945 auto_rewrite = True
1945 auto_rewrite = True
1946 if pre == self.ESC_QUOTE:
1946 if pre == self.ESC_QUOTE:
1947 # Auto-quote splitting on whitespace
1947 # Auto-quote splitting on whitespace
1948 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1948 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1949 elif pre == self.ESC_QUOTE2:
1949 elif pre == self.ESC_QUOTE2:
1950 # Auto-quote whole string
1950 # Auto-quote whole string
1951 newcmd = '%s("%s")' % (iFun,theRest)
1951 newcmd = '%s("%s")' % (iFun,theRest)
1952 else:
1952 else:
1953 # Auto-paren.
1953 # Auto-paren.
1954 # We only apply it to argument-less calls if the autocall
1954 # We only apply it to argument-less calls if the autocall
1955 # parameter is set to 2. We only need to check that autocall is <
1955 # parameter is set to 2. We only need to check that autocall is <
1956 # 2, since this function isn't called unless it's at least 1.
1956 # 2, since this function isn't called unless it's at least 1.
1957 if not theRest and (self.rc.autocall < 2):
1957 if not theRest and (self.rc.autocall < 2):
1958 newcmd = '%s %s' % (iFun,theRest)
1958 newcmd = '%s %s' % (iFun,theRest)
1959 auto_rewrite = False
1959 auto_rewrite = False
1960 else:
1960 else:
1961 if theRest.startswith('['):
1961 if theRest.startswith('['):
1962 if hasattr(obj,'__getitem__'):
1962 if hasattr(obj,'__getitem__'):
1963 # Don't autocall in this case: item access for an object
1963 # Don't autocall in this case: item access for an object
1964 # which is BOTH callable and implements __getitem__.
1964 # which is BOTH callable and implements __getitem__.
1965 newcmd = '%s %s' % (iFun,theRest)
1965 newcmd = '%s %s' % (iFun,theRest)
1966 auto_rewrite = False
1966 auto_rewrite = False
1967 else:
1967 else:
1968 # if the object doesn't support [] access, go ahead and
1968 # if the object doesn't support [] access, go ahead and
1969 # autocall
1969 # autocall
1970 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1970 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1971 elif theRest.endswith(';'):
1971 elif theRest.endswith(';'):
1972 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1972 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1973 else:
1973 else:
1974 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1974 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1975
1975
1976 if auto_rewrite:
1976 if auto_rewrite:
1977 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1977 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1978 # log what is now valid Python, not the actual user input (without the
1978 # log what is now valid Python, not the actual user input (without the
1979 # final newline)
1979 # final newline)
1980 self.log(newcmd,continue_prompt)
1980 self.log(newcmd,continue_prompt)
1981 return newcmd
1981 return newcmd
1982
1982
1983 def handle_help(self, line, continue_prompt=None,
1983 def handle_help(self, line, continue_prompt=None,
1984 pre=None,iFun=None,theRest=None):
1984 pre=None,iFun=None,theRest=None):
1985 """Try to get some help for the object.
1985 """Try to get some help for the object.
1986
1986
1987 obj? or ?obj -> basic information.
1987 obj? or ?obj -> basic information.
1988 obj?? or ??obj -> more details.
1988 obj?? or ??obj -> more details.
1989 """
1989 """
1990
1990
1991 # We need to make sure that we don't process lines which would be
1991 # We need to make sure that we don't process lines which would be
1992 # otherwise valid python, such as "x=1 # what?"
1992 # otherwise valid python, such as "x=1 # what?"
1993 try:
1993 try:
1994 codeop.compile_command(line)
1994 codeop.compile_command(line)
1995 except SyntaxError:
1995 except SyntaxError:
1996 # We should only handle as help stuff which is NOT valid syntax
1996 # We should only handle as help stuff which is NOT valid syntax
1997 if line[0]==self.ESC_HELP:
1997 if line[0]==self.ESC_HELP:
1998 line = line[1:]
1998 line = line[1:]
1999 elif line[-1]==self.ESC_HELP:
1999 elif line[-1]==self.ESC_HELP:
2000 line = line[:-1]
2000 line = line[:-1]
2001 self.log('#?'+line)
2001 self.log('#?'+line)
2002 if line:
2002 if line:
2003 self.magic_pinfo(line)
2003 self.magic_pinfo(line)
2004 else:
2004 else:
2005 page(self.usage,screen_lines=self.rc.screen_length)
2005 page(self.usage,screen_lines=self.rc.screen_length)
2006 return '' # Empty string is needed here!
2006 return '' # Empty string is needed here!
2007 except:
2007 except:
2008 # Pass any other exceptions through to the normal handler
2008 # Pass any other exceptions through to the normal handler
2009 return self.handle_normal(line,continue_prompt)
2009 return self.handle_normal(line,continue_prompt)
2010 else:
2010 else:
2011 # If the code compiles ok, we should handle it normally
2011 # If the code compiles ok, we should handle it normally
2012 return self.handle_normal(line,continue_prompt)
2012 return self.handle_normal(line,continue_prompt)
2013
2013
2014 def handle_emacs(self,line,continue_prompt=None,
2014 def handle_emacs(self,line,continue_prompt=None,
2015 pre=None,iFun=None,theRest=None):
2015 pre=None,iFun=None,theRest=None):
2016 """Handle input lines marked by python-mode."""
2016 """Handle input lines marked by python-mode."""
2017
2017
2018 # Currently, nothing is done. Later more functionality can be added
2018 # Currently, nothing is done. Later more functionality can be added
2019 # here if needed.
2019 # here if needed.
2020
2020
2021 # The input cache shouldn't be updated
2021 # The input cache shouldn't be updated
2022
2022
2023 return line
2023 return line
2024
2024
2025 def mktempfile(self,data=None):
2025 def mktempfile(self,data=None):
2026 """Make a new tempfile and return its filename.
2026 """Make a new tempfile and return its filename.
2027
2027
2028 This makes a call to tempfile.mktemp, but it registers the created
2028 This makes a call to tempfile.mktemp, but it registers the created
2029 filename internally so ipython cleans it up at exit time.
2029 filename internally so ipython cleans it up at exit time.
2030
2030
2031 Optional inputs:
2031 Optional inputs:
2032
2032
2033 - data(None): if data is given, it gets written out to the temp file
2033 - data(None): if data is given, it gets written out to the temp file
2034 immediately, and the file is closed again."""
2034 immediately, and the file is closed again."""
2035
2035
2036 filename = tempfile.mktemp('.py','ipython_edit_')
2036 filename = tempfile.mktemp('.py','ipython_edit_')
2037 self.tempfiles.append(filename)
2037 self.tempfiles.append(filename)
2038
2038
2039 if data:
2039 if data:
2040 tmp_file = open(filename,'w')
2040 tmp_file = open(filename,'w')
2041 tmp_file.write(data)
2041 tmp_file.write(data)
2042 tmp_file.close()
2042 tmp_file.close()
2043 return filename
2043 return filename
2044
2044
2045 def write(self,data):
2045 def write(self,data):
2046 """Write a string to the default output"""
2046 """Write a string to the default output"""
2047 Term.cout.write(data)
2047 Term.cout.write(data)
2048
2048
2049 def write_err(self,data):
2049 def write_err(self,data):
2050 """Write a string to the default error output"""
2050 """Write a string to the default error output"""
2051 Term.cerr.write(data)
2051 Term.cerr.write(data)
2052
2052
2053 def exit(self):
2053 def exit(self):
2054 """Handle interactive exit.
2054 """Handle interactive exit.
2055
2055
2056 This method sets the exit_now attribute."""
2056 This method sets the exit_now attribute."""
2057
2057
2058 if self.rc.confirm_exit:
2058 if self.rc.confirm_exit:
2059 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2059 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2060 self.exit_now = True
2060 self.exit_now = True
2061 else:
2061 else:
2062 self.exit_now = True
2062 self.exit_now = True
2063 return self.exit_now
2063 return self.exit_now
2064
2064
2065 def safe_execfile(self,fname,*where,**kw):
2065 def safe_execfile(self,fname,*where,**kw):
2066 fname = os.path.expanduser(fname)
2066 fname = os.path.expanduser(fname)
2067
2067
2068 # find things also in current directory
2068 # find things also in current directory
2069 dname = os.path.dirname(fname)
2069 dname = os.path.dirname(fname)
2070 if not sys.path.count(dname):
2070 if not sys.path.count(dname):
2071 sys.path.append(dname)
2071 sys.path.append(dname)
2072
2072
2073 try:
2073 try:
2074 xfile = open(fname)
2074 xfile = open(fname)
2075 except:
2075 except:
2076 print >> Term.cerr, \
2076 print >> Term.cerr, \
2077 'Could not open file <%s> for safe execution.' % fname
2077 'Could not open file <%s> for safe execution.' % fname
2078 return None
2078 return None
2079
2079
2080 kw.setdefault('islog',0)
2080 kw.setdefault('islog',0)
2081 kw.setdefault('quiet',1)
2081 kw.setdefault('quiet',1)
2082 kw.setdefault('exit_ignore',0)
2082 kw.setdefault('exit_ignore',0)
2083 first = xfile.readline()
2083 first = xfile.readline()
2084 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2084 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2085 xfile.close()
2085 xfile.close()
2086 # line by line execution
2086 # line by line execution
2087 if first.startswith(loghead) or kw['islog']:
2087 if first.startswith(loghead) or kw['islog']:
2088 print 'Loading log file <%s> one line at a time...' % fname
2088 print 'Loading log file <%s> one line at a time...' % fname
2089 if kw['quiet']:
2089 if kw['quiet']:
2090 stdout_save = sys.stdout
2090 stdout_save = sys.stdout
2091 sys.stdout = StringIO.StringIO()
2091 sys.stdout = StringIO.StringIO()
2092 try:
2092 try:
2093 globs,locs = where[0:2]
2093 globs,locs = where[0:2]
2094 except:
2094 except:
2095 try:
2095 try:
2096 globs = locs = where[0]
2096 globs = locs = where[0]
2097 except:
2097 except:
2098 globs = locs = globals()
2098 globs = locs = globals()
2099 badblocks = []
2099 badblocks = []
2100
2100
2101 # we also need to identify indented blocks of code when replaying
2101 # we also need to identify indented blocks of code when replaying
2102 # logs and put them together before passing them to an exec
2102 # logs and put them together before passing them to an exec
2103 # statement. This takes a bit of regexp and look-ahead work in the
2103 # statement. This takes a bit of regexp and look-ahead work in the
2104 # file. It's easiest if we swallow the whole thing in memory
2104 # file. It's easiest if we swallow the whole thing in memory
2105 # first, and manually walk through the lines list moving the
2105 # first, and manually walk through the lines list moving the
2106 # counter ourselves.
2106 # counter ourselves.
2107 indent_re = re.compile('\s+\S')
2107 indent_re = re.compile('\s+\S')
2108 xfile = open(fname)
2108 xfile = open(fname)
2109 filelines = xfile.readlines()
2109 filelines = xfile.readlines()
2110 xfile.close()
2110 xfile.close()
2111 nlines = len(filelines)
2111 nlines = len(filelines)
2112 lnum = 0
2112 lnum = 0
2113 while lnum < nlines:
2113 while lnum < nlines:
2114 line = filelines[lnum]
2114 line = filelines[lnum]
2115 lnum += 1
2115 lnum += 1
2116 # don't re-insert logger status info into cache
2116 # don't re-insert logger status info into cache
2117 if line.startswith('#log#'):
2117 if line.startswith('#log#'):
2118 continue
2118 continue
2119 else:
2119 else:
2120 # build a block of code (maybe a single line) for execution
2120 # build a block of code (maybe a single line) for execution
2121 block = line
2121 block = line
2122 try:
2122 try:
2123 next = filelines[lnum] # lnum has already incremented
2123 next = filelines[lnum] # lnum has already incremented
2124 except:
2124 except:
2125 next = None
2125 next = None
2126 while next and indent_re.match(next):
2126 while next and indent_re.match(next):
2127 block += next
2127 block += next
2128 lnum += 1
2128 lnum += 1
2129 try:
2129 try:
2130 next = filelines[lnum]
2130 next = filelines[lnum]
2131 except:
2131 except:
2132 next = None
2132 next = None
2133 # now execute the block of one or more lines
2133 # now execute the block of one or more lines
2134 try:
2134 try:
2135 exec block in globs,locs
2135 exec block in globs,locs
2136 except SystemExit:
2136 except SystemExit:
2137 pass
2137 pass
2138 except:
2138 except:
2139 badblocks.append(block.rstrip())
2139 badblocks.append(block.rstrip())
2140 if kw['quiet']: # restore stdout
2140 if kw['quiet']: # restore stdout
2141 sys.stdout.close()
2141 sys.stdout.close()
2142 sys.stdout = stdout_save
2142 sys.stdout = stdout_save
2143 print 'Finished replaying log file <%s>' % fname
2143 print 'Finished replaying log file <%s>' % fname
2144 if badblocks:
2144 if badblocks:
2145 print >> sys.stderr, ('\nThe following lines/blocks in file '
2145 print >> sys.stderr, ('\nThe following lines/blocks in file '
2146 '<%s> reported errors:' % fname)
2146 '<%s> reported errors:' % fname)
2147
2147
2148 for badline in badblocks:
2148 for badline in badblocks:
2149 print >> sys.stderr, badline
2149 print >> sys.stderr, badline
2150 else: # regular file execution
2150 else: # regular file execution
2151 try:
2151 try:
2152 execfile(fname,*where)
2152 execfile(fname,*where)
2153 except SyntaxError:
2153 except SyntaxError:
2154 etype,evalue = sys.exc_info()[:2]
2154 etype,evalue = sys.exc_info()[:2]
2155 self.SyntaxTB(etype,evalue,[])
2155 self.SyntaxTB(etype,evalue,[])
2156 warn('Failure executing file: <%s>' % fname)
2156 warn('Failure executing file: <%s>' % fname)
2157 except SystemExit,status:
2157 except SystemExit,status:
2158 if not kw['exit_ignore']:
2158 if not kw['exit_ignore']:
2159 self.InteractiveTB()
2159 self.InteractiveTB()
2160 warn('Failure executing file: <%s>' % fname)
2160 warn('Failure executing file: <%s>' % fname)
2161 except:
2161 except:
2162 self.InteractiveTB()
2162 self.InteractiveTB()
2163 warn('Failure executing file: <%s>' % fname)
2163 warn('Failure executing file: <%s>' % fname)
2164
2164
2165 #************************* end of file <iplib.py> *****************************
2165 #************************* end of file <iplib.py> *****************************
@@ -1,703 +1,703 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or better.
5 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8
8
9 $Id: ipmaker.py 998 2006-01-09 06:57:40Z fperez $"""
9 $Id: ipmaker.py 1005 2006-01-12 08:39:26Z fperez $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 from IPython import Release
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
20 __license__ = Release.license
21 __version__ = Release.version
21 __version__ = Release.version
22
22
23 credits._Printer__data = """
23 credits._Printer__data = """
24 Python: %s
24 Python: %s
25
25
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 See http://ipython.scipy.org for more information.""" \
27 See http://ipython.scipy.org for more information.""" \
28 % credits._Printer__data
28 % credits._Printer__data
29
29
30 copyright._Printer__data += """
30 copyright._Printer__data += """
31
31
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 All Rights Reserved."""
33 All Rights Reserved."""
34
34
35 #****************************************************************************
35 #****************************************************************************
36 # Required modules
36 # Required modules
37
37
38 # From the standard library
38 # From the standard library
39 import __main__
39 import __main__
40 import __builtin__
40 import __builtin__
41 import os
41 import os
42 import re
42 import re
43 import sys
43 import sys
44 import types
44 import types
45 from pprint import pprint,pformat
45 from pprint import pprint,pformat
46
46
47 # Our own
47 # Our own
48 from IPython import DPyGetOpt
48 from IPython import DPyGetOpt
49 from IPython.Struct import Struct
49 from IPython.ipstruct import Struct
50 from IPython.OutputTrap import OutputTrap
50 from IPython.OutputTrap import OutputTrap
51 from IPython.ConfigLoader import ConfigLoader
51 from IPython.ConfigLoader import ConfigLoader
52 from IPython.iplib import InteractiveShell
52 from IPython.iplib import InteractiveShell
53 from IPython.usage import cmd_line_usage,interactive_usage
53 from IPython.usage import cmd_line_usage,interactive_usage
54 from IPython.genutils import *
54 from IPython.genutils import *
55
55
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 rc_override=None,shell_class=InteractiveShell,
58 rc_override=None,shell_class=InteractiveShell,
59 embedded=False,**kw):
59 embedded=False,**kw):
60 """This is a dump of IPython into a single function.
60 """This is a dump of IPython into a single function.
61
61
62 Later it will have to be broken up in a sensible manner.
62 Later it will have to be broken up in a sensible manner.
63
63
64 Arguments:
64 Arguments:
65
65
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 script name, b/c DPyGetOpt strips the first argument only for the real
67 script name, b/c DPyGetOpt strips the first argument only for the real
68 sys.argv.
68 sys.argv.
69
69
70 - user_ns: a dict to be used as the user's namespace."""
70 - user_ns: a dict to be used as the user's namespace."""
71
71
72 #----------------------------------------------------------------------
72 #----------------------------------------------------------------------
73 # Defaults and initialization
73 # Defaults and initialization
74
74
75 # For developer debugging, deactivates crash handler and uses pdb.
75 # For developer debugging, deactivates crash handler and uses pdb.
76 DEVDEBUG = False
76 DEVDEBUG = False
77
77
78 if argv is None:
78 if argv is None:
79 argv = sys.argv
79 argv = sys.argv
80
80
81 # __IP is the main global that lives throughout and represents the whole
81 # __IP is the main global that lives throughout and represents the whole
82 # application. If the user redefines it, all bets are off as to what
82 # application. If the user redefines it, all bets are off as to what
83 # happens.
83 # happens.
84
84
85 # __IP is the name of he global which the caller will have accessible as
85 # __IP is the name of he global which the caller will have accessible as
86 # __IP.name. We set its name via the first parameter passed to
86 # __IP.name. We set its name via the first parameter passed to
87 # InteractiveShell:
87 # InteractiveShell:
88
88
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 embedded=embedded,**kw)
90 embedded=embedded,**kw)
91
91
92 # Put 'help' in the user namespace
92 # Put 'help' in the user namespace
93 from site import _Helper
93 from site import _Helper
94 IP.user_ns['help'] = _Helper()
94 IP.user_ns['help'] = _Helper()
95
95
96
96
97 if DEVDEBUG:
97 if DEVDEBUG:
98 # For developer debugging only (global flag)
98 # For developer debugging only (global flag)
99 from IPython import ultraTB
99 from IPython import ultraTB
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101
101
102 IP.BANNER_PARTS = ['Python %s\n'
102 IP.BANNER_PARTS = ['Python %s\n'
103 'Type "copyright", "credits" or "license" '
103 'Type "copyright", "credits" or "license" '
104 'for more information.\n'
104 'for more information.\n'
105 % (sys.version.split('\n')[0],),
105 % (sys.version.split('\n')[0],),
106 "IPython %s -- An enhanced Interactive Python."
106 "IPython %s -- An enhanced Interactive Python."
107 % (__version__,),
107 % (__version__,),
108 """? -> Introduction to IPython's features.
108 """? -> Introduction to IPython's features.
109 %magic -> Information about IPython's 'magic' % functions.
109 %magic -> Information about IPython's 'magic' % functions.
110 help -> Python's own help system.
110 help -> Python's own help system.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 """ ]
112 """ ]
113
113
114 IP.usage = interactive_usage
114 IP.usage = interactive_usage
115
115
116 # Platform-dependent suffix and directory names. We use _ipython instead
116 # Platform-dependent suffix and directory names. We use _ipython instead
117 # of .ipython under win32 b/c there's software that breaks with .named
117 # of .ipython under win32 b/c there's software that breaks with .named
118 # directories on that platform.
118 # directories on that platform.
119 if os.name == 'posix':
119 if os.name == 'posix':
120 rc_suffix = ''
120 rc_suffix = ''
121 ipdir_def = '.ipython'
121 ipdir_def = '.ipython'
122 else:
122 else:
123 rc_suffix = '.ini'
123 rc_suffix = '.ini'
124 ipdir_def = '_ipython'
124 ipdir_def = '_ipython'
125
125
126 # default directory for configuration
126 # default directory for configuration
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
128 os.path.join(IP.home_dir,ipdir_def)))
128 os.path.join(IP.home_dir,ipdir_def)))
129
129
130 # we need the directory where IPython itself is installed
130 # we need the directory where IPython itself is installed
131 import IPython
131 import IPython
132 IPython_dir = os.path.dirname(IPython.__file__)
132 IPython_dir = os.path.dirname(IPython.__file__)
133 del IPython
133 del IPython
134
134
135 #-------------------------------------------------------------------------
135 #-------------------------------------------------------------------------
136 # Command line handling
136 # Command line handling
137
137
138 # Valid command line options (uses DPyGetOpt syntax, like Perl's
138 # Valid command line options (uses DPyGetOpt syntax, like Perl's
139 # GetOpt::Long)
139 # GetOpt::Long)
140
140
141 # Any key not listed here gets deleted even if in the file (like session
141 # Any key not listed here gets deleted even if in the file (like session
142 # or profile). That's deliberate, to maintain the rc namespace clean.
142 # or profile). That's deliberate, to maintain the rc namespace clean.
143
143
144 # Each set of options appears twice: under _conv only the names are
144 # Each set of options appears twice: under _conv only the names are
145 # listed, indicating which type they must be converted to when reading the
145 # listed, indicating which type they must be converted to when reading the
146 # ipythonrc file. And under DPyGetOpt they are listed with the regular
146 # ipythonrc file. And under DPyGetOpt they are listed with the regular
147 # DPyGetOpt syntax (=s,=i,:f,etc).
147 # DPyGetOpt syntax (=s,=i,:f,etc).
148
148
149 # Make sure there's a space before each end of line (they get auto-joined!)
149 # Make sure there's a space before each end of line (they get auto-joined!)
150 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
150 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
151 'c=s classic|cl color_info! colors=s confirm_exit! '
151 'c=s classic|cl color_info! colors=s confirm_exit! '
152 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
152 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
153 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
153 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
154 'quick screen_length|sl=i prompts_pad_left=i '
154 'quick screen_length|sl=i prompts_pad_left=i '
155 'logfile|lf=s logplay|lp=s profile|p=s '
155 'logfile|lf=s logplay|lp=s profile|p=s '
156 'readline! readline_merge_completions! '
156 'readline! readline_merge_completions! '
157 'readline_omit__names! '
157 'readline_omit__names! '
158 'rcfile=s separate_in|si=s separate_out|so=s '
158 'rcfile=s separate_in|si=s separate_out|so=s '
159 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
159 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
160 'magic_docstrings system_verbose! '
160 'magic_docstrings system_verbose! '
161 'multi_line_specials! '
161 'multi_line_specials! '
162 'wxversion=s '
162 'wxversion=s '
163 'autoedit_syntax!')
163 'autoedit_syntax!')
164
164
165 # Options that can *only* appear at the cmd line (not in rcfiles).
165 # Options that can *only* appear at the cmd line (not in rcfiles).
166
166
167 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
167 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
168 # the 'C-c !' command in emacs automatically appends a -i option at the end.
168 # the 'C-c !' command in emacs automatically appends a -i option at the end.
169 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
169 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
170 'gthread! qthread! wthread! pylab! tk!')
170 'gthread! qthread! wthread! pylab! tk!')
171
171
172 # Build the actual name list to be used by DPyGetOpt
172 # Build the actual name list to be used by DPyGetOpt
173 opts_names = qw(cmdline_opts) + qw(cmdline_only)
173 opts_names = qw(cmdline_opts) + qw(cmdline_only)
174
174
175 # Set sensible command line defaults.
175 # Set sensible command line defaults.
176 # This should have everything from cmdline_opts and cmdline_only
176 # This should have everything from cmdline_opts and cmdline_only
177 opts_def = Struct(autocall = 1,
177 opts_def = Struct(autocall = 1,
178 autoedit_syntax = 1,
178 autoedit_syntax = 1,
179 autoindent=0,
179 autoindent=0,
180 automagic = 1,
180 automagic = 1,
181 banner = 1,
181 banner = 1,
182 cache_size = 1000,
182 cache_size = 1000,
183 c = '',
183 c = '',
184 classic = 0,
184 classic = 0,
185 colors = 'NoColor',
185 colors = 'NoColor',
186 color_info = 0,
186 color_info = 0,
187 confirm_exit = 1,
187 confirm_exit = 1,
188 debug = 0,
188 debug = 0,
189 deep_reload = 0,
189 deep_reload = 0,
190 editor = '0',
190 editor = '0',
191 help = 0,
191 help = 0,
192 ignore = 0,
192 ignore = 0,
193 ipythondir = ipythondir,
193 ipythondir = ipythondir,
194 log = 0,
194 log = 0,
195 logfile = '',
195 logfile = '',
196 logplay = '',
196 logplay = '',
197 multi_line_specials = 1,
197 multi_line_specials = 1,
198 messages = 1,
198 messages = 1,
199 nosep = 0,
199 nosep = 0,
200 pdb = 0,
200 pdb = 0,
201 pprint = 0,
201 pprint = 0,
202 profile = '',
202 profile = '',
203 prompt_in1 = 'In [\\#]: ',
203 prompt_in1 = 'In [\\#]: ',
204 prompt_in2 = ' .\\D.: ',
204 prompt_in2 = ' .\\D.: ',
205 prompt_out = 'Out[\\#]: ',
205 prompt_out = 'Out[\\#]: ',
206 prompts_pad_left = 1,
206 prompts_pad_left = 1,
207 quick = 0,
207 quick = 0,
208 readline = 1,
208 readline = 1,
209 readline_merge_completions = 1,
209 readline_merge_completions = 1,
210 readline_omit__names = 0,
210 readline_omit__names = 0,
211 rcfile = 'ipythonrc' + rc_suffix,
211 rcfile = 'ipythonrc' + rc_suffix,
212 screen_length = 0,
212 screen_length = 0,
213 separate_in = '\n',
213 separate_in = '\n',
214 separate_out = '\n',
214 separate_out = '\n',
215 separate_out2 = '',
215 separate_out2 = '',
216 system_verbose = 0,
216 system_verbose = 0,
217 gthread = 0,
217 gthread = 0,
218 qthread = 0,
218 qthread = 0,
219 wthread = 0,
219 wthread = 0,
220 pylab = 0,
220 pylab = 0,
221 tk = 0,
221 tk = 0,
222 upgrade = 0,
222 upgrade = 0,
223 Version = 0,
223 Version = 0,
224 xmode = 'Verbose',
224 xmode = 'Verbose',
225 wildcards_case_sensitive = 1,
225 wildcards_case_sensitive = 1,
226 wxversion = '0',
226 wxversion = '0',
227 magic_docstrings = 0, # undocumented, for doc generation
227 magic_docstrings = 0, # undocumented, for doc generation
228 )
228 )
229
229
230 # Things that will *only* appear in rcfiles (not at the command line).
230 # Things that will *only* appear in rcfiles (not at the command line).
231 # Make sure there's a space before each end of line (they get auto-joined!)
231 # Make sure there's a space before each end of line (they get auto-joined!)
232 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
232 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
233 qw_lol: 'import_some ',
233 qw_lol: 'import_some ',
234 # for things with embedded whitespace:
234 # for things with embedded whitespace:
235 list_strings:'execute alias readline_parse_and_bind ',
235 list_strings:'execute alias readline_parse_and_bind ',
236 # Regular strings need no conversion:
236 # Regular strings need no conversion:
237 None:'readline_remove_delims ',
237 None:'readline_remove_delims ',
238 }
238 }
239 # Default values for these
239 # Default values for these
240 rc_def = Struct(include = [],
240 rc_def = Struct(include = [],
241 import_mod = [],
241 import_mod = [],
242 import_all = [],
242 import_all = [],
243 import_some = [[]],
243 import_some = [[]],
244 execute = [],
244 execute = [],
245 execfile = [],
245 execfile = [],
246 alias = [],
246 alias = [],
247 readline_parse_and_bind = [],
247 readline_parse_and_bind = [],
248 readline_remove_delims = '',
248 readline_remove_delims = '',
249 )
249 )
250
250
251 # Build the type conversion dictionary from the above tables:
251 # Build the type conversion dictionary from the above tables:
252 typeconv = rcfile_opts.copy()
252 typeconv = rcfile_opts.copy()
253 typeconv.update(optstr2types(cmdline_opts))
253 typeconv.update(optstr2types(cmdline_opts))
254
254
255 # FIXME: the None key appears in both, put that back together by hand. Ugly!
255 # FIXME: the None key appears in both, put that back together by hand. Ugly!
256 typeconv[None] += ' ' + rcfile_opts[None]
256 typeconv[None] += ' ' + rcfile_opts[None]
257
257
258 # Remove quotes at ends of all strings (used to protect spaces)
258 # Remove quotes at ends of all strings (used to protect spaces)
259 typeconv[unquote_ends] = typeconv[None]
259 typeconv[unquote_ends] = typeconv[None]
260 del typeconv[None]
260 del typeconv[None]
261
261
262 # Build the list we'll use to make all config decisions with defaults:
262 # Build the list we'll use to make all config decisions with defaults:
263 opts_all = opts_def.copy()
263 opts_all = opts_def.copy()
264 opts_all.update(rc_def)
264 opts_all.update(rc_def)
265
265
266 # Build conflict resolver for recursive loading of config files:
266 # Build conflict resolver for recursive loading of config files:
267 # - preserve means the outermost file maintains the value, it is not
267 # - preserve means the outermost file maintains the value, it is not
268 # overwritten if an included file has the same key.
268 # overwritten if an included file has the same key.
269 # - add_flip applies + to the two values, so it better make sense to add
269 # - add_flip applies + to the two values, so it better make sense to add
270 # those types of keys. But it flips them first so that things loaded
270 # those types of keys. But it flips them first so that things loaded
271 # deeper in the inclusion chain have lower precedence.
271 # deeper in the inclusion chain have lower precedence.
272 conflict = {'preserve': ' '.join([ typeconv[int],
272 conflict = {'preserve': ' '.join([ typeconv[int],
273 typeconv[unquote_ends] ]),
273 typeconv[unquote_ends] ]),
274 'add_flip': ' '.join([ typeconv[qwflat],
274 'add_flip': ' '.join([ typeconv[qwflat],
275 typeconv[qw_lol],
275 typeconv[qw_lol],
276 typeconv[list_strings] ])
276 typeconv[list_strings] ])
277 }
277 }
278
278
279 # Now actually process the command line
279 # Now actually process the command line
280 getopt = DPyGetOpt.DPyGetOpt()
280 getopt = DPyGetOpt.DPyGetOpt()
281 getopt.setIgnoreCase(0)
281 getopt.setIgnoreCase(0)
282
282
283 getopt.parseConfiguration(opts_names)
283 getopt.parseConfiguration(opts_names)
284
284
285 try:
285 try:
286 getopt.processArguments(argv)
286 getopt.processArguments(argv)
287 except:
287 except:
288 print cmd_line_usage
288 print cmd_line_usage
289 warn('\nError in Arguments: ' + `sys.exc_value`)
289 warn('\nError in Arguments: ' + `sys.exc_value`)
290 sys.exit(1)
290 sys.exit(1)
291
291
292 # convert the options dict to a struct for much lighter syntax later
292 # convert the options dict to a struct for much lighter syntax later
293 opts = Struct(getopt.optionValues)
293 opts = Struct(getopt.optionValues)
294 args = getopt.freeValues
294 args = getopt.freeValues
295
295
296 # this is the struct (which has default values at this point) with which
296 # this is the struct (which has default values at this point) with which
297 # we make all decisions:
297 # we make all decisions:
298 opts_all.update(opts)
298 opts_all.update(opts)
299
299
300 # Options that force an immediate exit
300 # Options that force an immediate exit
301 if opts_all.help:
301 if opts_all.help:
302 page(cmd_line_usage)
302 page(cmd_line_usage)
303 sys.exit()
303 sys.exit()
304
304
305 if opts_all.Version:
305 if opts_all.Version:
306 print __version__
306 print __version__
307 sys.exit()
307 sys.exit()
308
308
309 if opts_all.magic_docstrings:
309 if opts_all.magic_docstrings:
310 IP.magic_magic('-latex')
310 IP.magic_magic('-latex')
311 sys.exit()
311 sys.exit()
312
312
313 # Create user config directory if it doesn't exist. This must be done
313 # Create user config directory if it doesn't exist. This must be done
314 # *after* getting the cmd line options.
314 # *after* getting the cmd line options.
315 if not os.path.isdir(opts_all.ipythondir):
315 if not os.path.isdir(opts_all.ipythondir):
316 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
316 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
317
317
318 # upgrade user config files while preserving a copy of the originals
318 # upgrade user config files while preserving a copy of the originals
319 if opts_all.upgrade:
319 if opts_all.upgrade:
320 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
320 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
321
321
322 # check mutually exclusive options in the *original* command line
322 # check mutually exclusive options in the *original* command line
323 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
323 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
324 qw('classic profile'),qw('classic rcfile')])
324 qw('classic profile'),qw('classic rcfile')])
325
325
326 #---------------------------------------------------------------------------
326 #---------------------------------------------------------------------------
327 # Log replay
327 # Log replay
328
328
329 # if -logplay, we need to 'become' the other session. That basically means
329 # if -logplay, we need to 'become' the other session. That basically means
330 # replacing the current command line environment with that of the old
330 # replacing the current command line environment with that of the old
331 # session and moving on.
331 # session and moving on.
332
332
333 # this is needed so that later we know we're in session reload mode, as
333 # this is needed so that later we know we're in session reload mode, as
334 # opts_all will get overwritten:
334 # opts_all will get overwritten:
335 load_logplay = 0
335 load_logplay = 0
336
336
337 if opts_all.logplay:
337 if opts_all.logplay:
338 load_logplay = opts_all.logplay
338 load_logplay = opts_all.logplay
339 opts_debug_save = opts_all.debug
339 opts_debug_save = opts_all.debug
340 try:
340 try:
341 logplay = open(opts_all.logplay)
341 logplay = open(opts_all.logplay)
342 except IOError:
342 except IOError:
343 if opts_all.debug: IP.InteractiveTB()
343 if opts_all.debug: IP.InteractiveTB()
344 warn('Could not open logplay file '+`opts_all.logplay`)
344 warn('Could not open logplay file '+`opts_all.logplay`)
345 # restore state as if nothing had happened and move on, but make
345 # restore state as if nothing had happened and move on, but make
346 # sure that later we don't try to actually load the session file
346 # sure that later we don't try to actually load the session file
347 logplay = None
347 logplay = None
348 load_logplay = 0
348 load_logplay = 0
349 del opts_all.logplay
349 del opts_all.logplay
350 else:
350 else:
351 try:
351 try:
352 logplay.readline()
352 logplay.readline()
353 logplay.readline();
353 logplay.readline();
354 # this reloads that session's command line
354 # this reloads that session's command line
355 cmd = logplay.readline()[6:]
355 cmd = logplay.readline()[6:]
356 exec cmd
356 exec cmd
357 # restore the true debug flag given so that the process of
357 # restore the true debug flag given so that the process of
358 # session loading itself can be monitored.
358 # session loading itself can be monitored.
359 opts.debug = opts_debug_save
359 opts.debug = opts_debug_save
360 # save the logplay flag so later we don't overwrite the log
360 # save the logplay flag so later we don't overwrite the log
361 opts.logplay = load_logplay
361 opts.logplay = load_logplay
362 # now we must update our own structure with defaults
362 # now we must update our own structure with defaults
363 opts_all.update(opts)
363 opts_all.update(opts)
364 # now load args
364 # now load args
365 cmd = logplay.readline()[6:]
365 cmd = logplay.readline()[6:]
366 exec cmd
366 exec cmd
367 logplay.close()
367 logplay.close()
368 except:
368 except:
369 logplay.close()
369 logplay.close()
370 if opts_all.debug: IP.InteractiveTB()
370 if opts_all.debug: IP.InteractiveTB()
371 warn("Logplay file lacking full configuration information.\n"
371 warn("Logplay file lacking full configuration information.\n"
372 "I'll try to read it, but some things may not work.")
372 "I'll try to read it, but some things may not work.")
373
373
374 #-------------------------------------------------------------------------
374 #-------------------------------------------------------------------------
375 # set up output traps: catch all output from files, being run, modules
375 # set up output traps: catch all output from files, being run, modules
376 # loaded, etc. Then give it to the user in a clean form at the end.
376 # loaded, etc. Then give it to the user in a clean form at the end.
377
377
378 msg_out = 'Output messages. '
378 msg_out = 'Output messages. '
379 msg_err = 'Error messages. '
379 msg_err = 'Error messages. '
380 msg_sep = '\n'
380 msg_sep = '\n'
381 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
381 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
382 msg_err,msg_sep,debug,
382 msg_err,msg_sep,debug,
383 quiet_out=1),
383 quiet_out=1),
384 user_exec = OutputTrap('User File Execution',msg_out,
384 user_exec = OutputTrap('User File Execution',msg_out,
385 msg_err,msg_sep,debug),
385 msg_err,msg_sep,debug),
386 logplay = OutputTrap('Log Loader',msg_out,
386 logplay = OutputTrap('Log Loader',msg_out,
387 msg_err,msg_sep,debug),
387 msg_err,msg_sep,debug),
388 summary = ''
388 summary = ''
389 )
389 )
390
390
391 #-------------------------------------------------------------------------
391 #-------------------------------------------------------------------------
392 # Process user ipythonrc-type configuration files
392 # Process user ipythonrc-type configuration files
393
393
394 # turn on output trapping and log to msg.config
394 # turn on output trapping and log to msg.config
395 # remember that with debug on, trapping is actually disabled
395 # remember that with debug on, trapping is actually disabled
396 msg.config.trap_all()
396 msg.config.trap_all()
397
397
398 # look for rcfile in current or default directory
398 # look for rcfile in current or default directory
399 try:
399 try:
400 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
400 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
401 except IOError:
401 except IOError:
402 if opts_all.debug: IP.InteractiveTB()
402 if opts_all.debug: IP.InteractiveTB()
403 warn('Configuration file %s not found. Ignoring request.'
403 warn('Configuration file %s not found. Ignoring request.'
404 % (opts_all.rcfile) )
404 % (opts_all.rcfile) )
405
405
406 # 'profiles' are a shorthand notation for config filenames
406 # 'profiles' are a shorthand notation for config filenames
407 if opts_all.profile:
407 if opts_all.profile:
408 try:
408 try:
409 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
409 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
410 + rc_suffix,
410 + rc_suffix,
411 opts_all.ipythondir)
411 opts_all.ipythondir)
412 except IOError:
412 except IOError:
413 if opts_all.debug: IP.InteractiveTB()
413 if opts_all.debug: IP.InteractiveTB()
414 opts.profile = '' # remove profile from options if invalid
414 opts.profile = '' # remove profile from options if invalid
415 warn('Profile configuration file %s not found. Ignoring request.'
415 warn('Profile configuration file %s not found. Ignoring request.'
416 % (opts_all.profile) )
416 % (opts_all.profile) )
417
417
418 # load the config file
418 # load the config file
419 rcfiledata = None
419 rcfiledata = None
420 if opts_all.quick:
420 if opts_all.quick:
421 print 'Launching IPython in quick mode. No config file read.'
421 print 'Launching IPython in quick mode. No config file read.'
422 elif opts_all.classic:
422 elif opts_all.classic:
423 print 'Launching IPython in classic mode. No config file read.'
423 print 'Launching IPython in classic mode. No config file read.'
424 elif opts_all.rcfile:
424 elif opts_all.rcfile:
425 try:
425 try:
426 cfg_loader = ConfigLoader(conflict)
426 cfg_loader = ConfigLoader(conflict)
427 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
427 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
428 'include',opts_all.ipythondir,
428 'include',opts_all.ipythondir,
429 purge = 1,
429 purge = 1,
430 unique = conflict['preserve'])
430 unique = conflict['preserve'])
431 except:
431 except:
432 IP.InteractiveTB()
432 IP.InteractiveTB()
433 warn('Problems loading configuration file '+
433 warn('Problems loading configuration file '+
434 `opts_all.rcfile`+
434 `opts_all.rcfile`+
435 '\nStarting with default -bare bones- configuration.')
435 '\nStarting with default -bare bones- configuration.')
436 else:
436 else:
437 warn('No valid configuration file found in either currrent directory\n'+
437 warn('No valid configuration file found in either currrent directory\n'+
438 'or in the IPython config. directory: '+`opts_all.ipythondir`+
438 'or in the IPython config. directory: '+`opts_all.ipythondir`+
439 '\nProceeding with internal defaults.')
439 '\nProceeding with internal defaults.')
440
440
441 #------------------------------------------------------------------------
441 #------------------------------------------------------------------------
442 # Set exception handlers in mode requested by user.
442 # Set exception handlers in mode requested by user.
443 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
443 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
444 IP.magic_xmode(opts_all.xmode)
444 IP.magic_xmode(opts_all.xmode)
445 otrap.release_out()
445 otrap.release_out()
446
446
447 #------------------------------------------------------------------------
447 #------------------------------------------------------------------------
448 # Execute user config
448 # Execute user config
449
449
450 # Create a valid config structure with the right precedence order:
450 # Create a valid config structure with the right precedence order:
451 # defaults < rcfile < command line. This needs to be in the instance, so
451 # defaults < rcfile < command line. This needs to be in the instance, so
452 # that method calls below that rely on it find it.
452 # that method calls below that rely on it find it.
453 IP.rc = rc_def.copy()
453 IP.rc = rc_def.copy()
454
454
455 # Work with a local alias inside this routine to avoid unnecessary
455 # Work with a local alias inside this routine to avoid unnecessary
456 # attribute lookups.
456 # attribute lookups.
457 IP_rc = IP.rc
457 IP_rc = IP.rc
458
458
459 IP_rc.update(opts_def)
459 IP_rc.update(opts_def)
460 if rcfiledata:
460 if rcfiledata:
461 # now we can update
461 # now we can update
462 IP_rc.update(rcfiledata)
462 IP_rc.update(rcfiledata)
463 IP_rc.update(opts)
463 IP_rc.update(opts)
464 IP_rc.update(rc_override)
464 IP_rc.update(rc_override)
465
465
466 # Store the original cmd line for reference:
466 # Store the original cmd line for reference:
467 IP_rc.opts = opts
467 IP_rc.opts = opts
468 IP_rc.args = args
468 IP_rc.args = args
469
469
470 # create a *runtime* Struct like rc for holding parameters which may be
470 # create a *runtime* Struct like rc for holding parameters which may be
471 # created and/or modified by runtime user extensions.
471 # created and/or modified by runtime user extensions.
472 IP.runtime_rc = Struct()
472 IP.runtime_rc = Struct()
473
473
474 # from this point on, all config should be handled through IP_rc,
474 # from this point on, all config should be handled through IP_rc,
475 # opts* shouldn't be used anymore.
475 # opts* shouldn't be used anymore.
476
476
477 # add personal .ipython dir to sys.path so that users can put things in
477 # add personal .ipython dir to sys.path so that users can put things in
478 # there for customization
478 # there for customization
479 sys.path.append(IP_rc.ipythondir)
479 sys.path.append(IP_rc.ipythondir)
480 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
480 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
481
481
482 # update IP_rc with some special things that need manual
482 # update IP_rc with some special things that need manual
483 # tweaks. Basically options which affect other options. I guess this
483 # tweaks. Basically options which affect other options. I guess this
484 # should just be written so that options are fully orthogonal and we
484 # should just be written so that options are fully orthogonal and we
485 # wouldn't worry about this stuff!
485 # wouldn't worry about this stuff!
486
486
487 if IP_rc.classic:
487 if IP_rc.classic:
488 IP_rc.quick = 1
488 IP_rc.quick = 1
489 IP_rc.cache_size = 0
489 IP_rc.cache_size = 0
490 IP_rc.pprint = 0
490 IP_rc.pprint = 0
491 IP_rc.prompt_in1 = '>>> '
491 IP_rc.prompt_in1 = '>>> '
492 IP_rc.prompt_in2 = '... '
492 IP_rc.prompt_in2 = '... '
493 IP_rc.prompt_out = ''
493 IP_rc.prompt_out = ''
494 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
494 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
495 IP_rc.colors = 'NoColor'
495 IP_rc.colors = 'NoColor'
496 IP_rc.xmode = 'Plain'
496 IP_rc.xmode = 'Plain'
497
497
498 # configure readline
498 # configure readline
499 # Define the history file for saving commands in between sessions
499 # Define the history file for saving commands in between sessions
500 if IP_rc.profile:
500 if IP_rc.profile:
501 histfname = 'history-%s' % IP_rc.profile
501 histfname = 'history-%s' % IP_rc.profile
502 else:
502 else:
503 histfname = 'history'
503 histfname = 'history'
504 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
504 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
505
505
506 # update exception handlers with rc file status
506 # update exception handlers with rc file status
507 otrap.trap_out() # I don't want these messages ever.
507 otrap.trap_out() # I don't want these messages ever.
508 IP.magic_xmode(IP_rc.xmode)
508 IP.magic_xmode(IP_rc.xmode)
509 otrap.release_out()
509 otrap.release_out()
510
510
511 # activate logging if requested and not reloading a log
511 # activate logging if requested and not reloading a log
512 if IP_rc.logplay:
512 if IP_rc.logplay:
513 IP.magic_logstart(IP_rc.logplay + ' append')
513 IP.magic_logstart(IP_rc.logplay + ' append')
514 elif IP_rc.logfile:
514 elif IP_rc.logfile:
515 IP.magic_logstart(IP_rc.logfile)
515 IP.magic_logstart(IP_rc.logfile)
516 elif IP_rc.log:
516 elif IP_rc.log:
517 IP.magic_logstart()
517 IP.magic_logstart()
518
518
519 # find user editor so that it we don't have to look it up constantly
519 # find user editor so that it we don't have to look it up constantly
520 if IP_rc.editor.strip()=='0':
520 if IP_rc.editor.strip()=='0':
521 try:
521 try:
522 ed = os.environ['EDITOR']
522 ed = os.environ['EDITOR']
523 except KeyError:
523 except KeyError:
524 if os.name == 'posix':
524 if os.name == 'posix':
525 ed = 'vi' # the only one guaranteed to be there!
525 ed = 'vi' # the only one guaranteed to be there!
526 else:
526 else:
527 ed = 'notepad' # same in Windows!
527 ed = 'notepad' # same in Windows!
528 IP_rc.editor = ed
528 IP_rc.editor = ed
529
529
530 # Keep track of whether this is an embedded instance or not (useful for
530 # Keep track of whether this is an embedded instance or not (useful for
531 # post-mortems).
531 # post-mortems).
532 IP_rc.embedded = IP.embedded
532 IP_rc.embedded = IP.embedded
533
533
534 # Recursive reload
534 # Recursive reload
535 try:
535 try:
536 from IPython import deep_reload
536 from IPython import deep_reload
537 if IP_rc.deep_reload:
537 if IP_rc.deep_reload:
538 __builtin__.reload = deep_reload.reload
538 __builtin__.reload = deep_reload.reload
539 else:
539 else:
540 __builtin__.dreload = deep_reload.reload
540 __builtin__.dreload = deep_reload.reload
541 del deep_reload
541 del deep_reload
542 except ImportError:
542 except ImportError:
543 pass
543 pass
544
544
545 # Save the current state of our namespace so that the interactive shell
545 # Save the current state of our namespace so that the interactive shell
546 # can later know which variables have been created by us from config files
546 # can later know which variables have been created by us from config files
547 # and loading. This way, loading a file (in any way) is treated just like
547 # and loading. This way, loading a file (in any way) is treated just like
548 # defining things on the command line, and %who works as expected.
548 # defining things on the command line, and %who works as expected.
549
549
550 # DON'T do anything that affects the namespace beyond this point!
550 # DON'T do anything that affects the namespace beyond this point!
551 IP.internal_ns.update(__main__.__dict__)
551 IP.internal_ns.update(__main__.__dict__)
552
552
553 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
553 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
554
554
555 # Now run through the different sections of the users's config
555 # Now run through the different sections of the users's config
556 if IP_rc.debug:
556 if IP_rc.debug:
557 print 'Trying to execute the following configuration structure:'
557 print 'Trying to execute the following configuration structure:'
558 print '(Things listed first are deeper in the inclusion tree and get'
558 print '(Things listed first are deeper in the inclusion tree and get'
559 print 'loaded first).\n'
559 print 'loaded first).\n'
560 pprint(IP_rc.__dict__)
560 pprint(IP_rc.__dict__)
561
561
562 for mod in IP_rc.import_mod:
562 for mod in IP_rc.import_mod:
563 try:
563 try:
564 exec 'import '+mod in IP.user_ns
564 exec 'import '+mod in IP.user_ns
565 except :
565 except :
566 IP.InteractiveTB()
566 IP.InteractiveTB()
567 import_fail_info(mod)
567 import_fail_info(mod)
568
568
569 for mod_fn in IP_rc.import_some:
569 for mod_fn in IP_rc.import_some:
570 if mod_fn == []: break
570 if mod_fn == []: break
571 mod,fn = mod_fn[0],','.join(mod_fn[1:])
571 mod,fn = mod_fn[0],','.join(mod_fn[1:])
572 try:
572 try:
573 exec 'from '+mod+' import '+fn in IP.user_ns
573 exec 'from '+mod+' import '+fn in IP.user_ns
574 except :
574 except :
575 IP.InteractiveTB()
575 IP.InteractiveTB()
576 import_fail_info(mod,fn)
576 import_fail_info(mod,fn)
577
577
578 for mod in IP_rc.import_all:
578 for mod in IP_rc.import_all:
579 try:
579 try:
580 exec 'from '+mod+' import *' in IP.user_ns
580 exec 'from '+mod+' import *' in IP.user_ns
581 except :
581 except :
582 IP.InteractiveTB()
582 IP.InteractiveTB()
583 import_fail_info(mod)
583 import_fail_info(mod)
584
584
585 for code in IP_rc.execute:
585 for code in IP_rc.execute:
586 try:
586 try:
587 exec code in IP.user_ns
587 exec code in IP.user_ns
588 except:
588 except:
589 IP.InteractiveTB()
589 IP.InteractiveTB()
590 warn('Failure executing code: ' + `code`)
590 warn('Failure executing code: ' + `code`)
591
591
592 # Execute the files the user wants in ipythonrc
592 # Execute the files the user wants in ipythonrc
593 for file in IP_rc.execfile:
593 for file in IP_rc.execfile:
594 try:
594 try:
595 file = filefind(file,sys.path+[IPython_dir])
595 file = filefind(file,sys.path+[IPython_dir])
596 except IOError:
596 except IOError:
597 warn(itpl('File $file not found. Skipping it.'))
597 warn(itpl('File $file not found. Skipping it.'))
598 else:
598 else:
599 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
599 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
600
600
601 # release stdout and stderr and save config log into a global summary
601 # release stdout and stderr and save config log into a global summary
602 msg.config.release_all()
602 msg.config.release_all()
603 if IP_rc.messages:
603 if IP_rc.messages:
604 msg.summary += msg.config.summary_all()
604 msg.summary += msg.config.summary_all()
605
605
606 #------------------------------------------------------------------------
606 #------------------------------------------------------------------------
607 # Setup interactive session
607 # Setup interactive session
608
608
609 # Now we should be fully configured. We can then execute files or load
609 # Now we should be fully configured. We can then execute files or load
610 # things only needed for interactive use. Then we'll open the shell.
610 # things only needed for interactive use. Then we'll open the shell.
611
611
612 # Take a snapshot of the user namespace before opening the shell. That way
612 # Take a snapshot of the user namespace before opening the shell. That way
613 # we'll be able to identify which things were interactively defined and
613 # we'll be able to identify which things were interactively defined and
614 # which were defined through config files.
614 # which were defined through config files.
615 IP.user_config_ns = IP.user_ns.copy()
615 IP.user_config_ns = IP.user_ns.copy()
616
616
617 # Force reading a file as if it were a session log. Slower but safer.
617 # Force reading a file as if it were a session log. Slower but safer.
618 if load_logplay:
618 if load_logplay:
619 print 'Replaying log...'
619 print 'Replaying log...'
620 try:
620 try:
621 if IP_rc.debug:
621 if IP_rc.debug:
622 logplay_quiet = 0
622 logplay_quiet = 0
623 else:
623 else:
624 logplay_quiet = 1
624 logplay_quiet = 1
625
625
626 msg.logplay.trap_all()
626 msg.logplay.trap_all()
627 IP.safe_execfile(load_logplay,IP.user_ns,
627 IP.safe_execfile(load_logplay,IP.user_ns,
628 islog = 1, quiet = logplay_quiet)
628 islog = 1, quiet = logplay_quiet)
629 msg.logplay.release_all()
629 msg.logplay.release_all()
630 if IP_rc.messages:
630 if IP_rc.messages:
631 msg.summary += msg.logplay.summary_all()
631 msg.summary += msg.logplay.summary_all()
632 except:
632 except:
633 warn('Problems replaying logfile %s.' % load_logplay)
633 warn('Problems replaying logfile %s.' % load_logplay)
634 IP.InteractiveTB()
634 IP.InteractiveTB()
635
635
636 # Load remaining files in command line
636 # Load remaining files in command line
637 msg.user_exec.trap_all()
637 msg.user_exec.trap_all()
638
638
639 # Do NOT execute files named in the command line as scripts to be loaded
639 # Do NOT execute files named in the command line as scripts to be loaded
640 # by embedded instances. Doing so has the potential for an infinite
640 # by embedded instances. Doing so has the potential for an infinite
641 # recursion if there are exceptions thrown in the process.
641 # recursion if there are exceptions thrown in the process.
642
642
643 # XXX FIXME: the execution of user files should be moved out to after
643 # XXX FIXME: the execution of user files should be moved out to after
644 # ipython is fully initialized, just as if they were run via %run at the
644 # ipython is fully initialized, just as if they were run via %run at the
645 # ipython prompt. This would also give them the benefit of ipython's
645 # ipython prompt. This would also give them the benefit of ipython's
646 # nice tracebacks.
646 # nice tracebacks.
647
647
648 if not embedded and IP_rc.args:
648 if not embedded and IP_rc.args:
649 name_save = IP.user_ns['__name__']
649 name_save = IP.user_ns['__name__']
650 IP.user_ns['__name__'] = '__main__'
650 IP.user_ns['__name__'] = '__main__'
651 try:
651 try:
652 # Set our own excepthook in case the user code tries to call it
652 # Set our own excepthook in case the user code tries to call it
653 # directly. This prevents triggering the IPython crash handler.
653 # directly. This prevents triggering the IPython crash handler.
654 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
654 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
655 for run in args:
655 for run in args:
656 IP.safe_execfile(run,IP.user_ns)
656 IP.safe_execfile(run,IP.user_ns)
657 finally:
657 finally:
658 # Reset our crash handler in place
658 # Reset our crash handler in place
659 sys.excepthook = old_excepthook
659 sys.excepthook = old_excepthook
660
660
661 IP.user_ns['__name__'] = name_save
661 IP.user_ns['__name__'] = name_save
662
662
663 msg.user_exec.release_all()
663 msg.user_exec.release_all()
664 if IP_rc.messages:
664 if IP_rc.messages:
665 msg.summary += msg.user_exec.summary_all()
665 msg.summary += msg.user_exec.summary_all()
666
666
667 # since we can't specify a null string on the cmd line, 0 is the equivalent:
667 # since we can't specify a null string on the cmd line, 0 is the equivalent:
668 if IP_rc.nosep:
668 if IP_rc.nosep:
669 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
669 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
670 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
670 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
671 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
671 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
672 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
672 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
673 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
673 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
674 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
674 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
675 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
675 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
676
676
677 # Determine how many lines at the bottom of the screen are needed for
677 # Determine how many lines at the bottom of the screen are needed for
678 # showing prompts, so we can know wheter long strings are to be printed or
678 # showing prompts, so we can know wheter long strings are to be printed or
679 # paged:
679 # paged:
680 num_lines_bot = IP_rc.separate_in.count('\n')+1
680 num_lines_bot = IP_rc.separate_in.count('\n')+1
681 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
681 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
682
682
683 # configure startup banner
683 # configure startup banner
684 if IP_rc.c: # regular python doesn't print the banner with -c
684 if IP_rc.c: # regular python doesn't print the banner with -c
685 IP_rc.banner = 0
685 IP_rc.banner = 0
686 if IP_rc.banner:
686 if IP_rc.banner:
687 BANN_P = IP.BANNER_PARTS
687 BANN_P = IP.BANNER_PARTS
688 else:
688 else:
689 BANN_P = []
689 BANN_P = []
690
690
691 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
691 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
692
692
693 # add message log (possibly empty)
693 # add message log (possibly empty)
694 if msg.summary: BANN_P.append(msg.summary)
694 if msg.summary: BANN_P.append(msg.summary)
695 # Final banner is a string
695 # Final banner is a string
696 IP.BANNER = '\n'.join(BANN_P)
696 IP.BANNER = '\n'.join(BANN_P)
697
697
698 # Finalize the IPython instance. This assumes the rc structure is fully
698 # Finalize the IPython instance. This assumes the rc structure is fully
699 # in place.
699 # in place.
700 IP.post_config_initialization()
700 IP.post_config_initialization()
701
701
702 return IP
702 return IP
703 #************************ end of file <ipmaker.py> **************************
703 #************************ end of file <ipmaker.py> **************************
@@ -1,376 +1,376 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Mimic C structs with lots of extra functionality.
2 """Mimic C structs with lots of extra functionality.
3
3
4 $Id: Struct.py 958 2005-12-27 23:17:51Z fperez $"""
4 $Id: ipstruct.py 1005 2006-01-12 08:39:26Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 from IPython import Release
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
15 __license__ = Release.license
16
16
17 __all__ = ['Struct']
17 __all__ = ['Struct']
18
18
19 import types
19 import types
20
20
21 from IPython.genutils import list2dict2
21 from IPython.genutils import list2dict2
22
22
23 class Struct:
23 class Struct:
24 """Class to mimic C structs but also provide convenient dictionary-like
24 """Class to mimic C structs but also provide convenient dictionary-like
25 functionality.
25 functionality.
26
26
27 Instances can be initialized with a dictionary, a list of key=value pairs
27 Instances can be initialized with a dictionary, a list of key=value pairs
28 or both. If both are present, the dictionary must come first.
28 or both. If both are present, the dictionary must come first.
29
29
30 Because Python classes provide direct assignment to their members, it's
30 Because Python classes provide direct assignment to their members, it's
31 easy to overwrite normal methods (S.copy = 1 would destroy access to
31 easy to overwrite normal methods (S.copy = 1 would destroy access to
32 S.copy()). For this reason, all builtin method names are protected and
32 S.copy()). For this reason, all builtin method names are protected and
33 can't be assigned to. An attempt to do s.copy=1 or s['copy']=1 will raise
33 can't be assigned to. An attempt to do s.copy=1 or s['copy']=1 will raise
34 a KeyError exception. If you really want to, you can bypass this
34 a KeyError exception. If you really want to, you can bypass this
35 protection by directly assigning to __dict__: s.__dict__['copy']=1 will
35 protection by directly assigning to __dict__: s.__dict__['copy']=1 will
36 still work. Doing this will break functionality, though. As in most of
36 still work. Doing this will break functionality, though. As in most of
37 Python, namespace protection is weakly enforced, so feel free to shoot
37 Python, namespace protection is weakly enforced, so feel free to shoot
38 yourself if you really want to.
38 yourself if you really want to.
39
39
40 Note that this class uses more memory and is *much* slower than a regular
40 Note that this class uses more memory and is *much* slower than a regular
41 dictionary, so be careful in situations where memory or performance are
41 dictionary, so be careful in situations where memory or performance are
42 critical. But for day to day use it should behave fine. It is particularly
42 critical. But for day to day use it should behave fine. It is particularly
43 convenient for storing configuration data in programs.
43 convenient for storing configuration data in programs.
44
44
45 +,+=,- and -= are implemented. +/+= do merges (non-destructive updates),
45 +,+=,- and -= are implemented. +/+= do merges (non-destructive updates),
46 -/-= remove keys from the original. See the method descripitions.
46 -/-= remove keys from the original. See the method descripitions.
47
47
48 This class allows a quick access syntax: both s.key and s['key'] are
48 This class allows a quick access syntax: both s.key and s['key'] are
49 valid. This syntax has a limitation: each 'key' has to be explicitly
49 valid. This syntax has a limitation: each 'key' has to be explicitly
50 accessed by its original name. The normal s.key syntax doesn't provide
50 accessed by its original name. The normal s.key syntax doesn't provide
51 access to the keys via variables whose values evaluate to the desired
51 access to the keys via variables whose values evaluate to the desired
52 keys. An example should clarify this:
52 keys. An example should clarify this:
53
53
54 Define a dictionary and initialize both with dict and k=v pairs:
54 Define a dictionary and initialize both with dict and k=v pairs:
55 >>> d={'a':1,'b':2}
55 >>> d={'a':1,'b':2}
56 >>> s=Struct(d,hi=10,ho=20)
56 >>> s=Struct(d,hi=10,ho=20)
57 The return of __repr__ can be used to create a new instance:
57 The return of __repr__ can be used to create a new instance:
58 >>> s
58 >>> s
59 Struct({'ho': 20, 'b': 2, 'hi': 10, 'a': 1})
59 Struct({'ho': 20, 'b': 2, 'hi': 10, 'a': 1})
60 __str__ (called by print) shows it's not quite a regular dictionary:
60 __str__ (called by print) shows it's not quite a regular dictionary:
61 >>> print s
61 >>> print s
62 Struct {a: 1, b: 2, hi: 10, ho: 20}
62 Struct {a: 1, b: 2, hi: 10, ho: 20}
63 Access by explicitly named key with dot notation:
63 Access by explicitly named key with dot notation:
64 >>> s.a
64 >>> s.a
65 1
65 1
66 Or like a dictionary:
66 Or like a dictionary:
67 >>> s['a']
67 >>> s['a']
68 1
68 1
69 If you want a variable to hold the key value, only dictionary access works:
69 If you want a variable to hold the key value, only dictionary access works:
70 >>> key='hi'
70 >>> key='hi'
71 >>> s.key
71 >>> s.key
72 Traceback (most recent call last):
72 Traceback (most recent call last):
73 File "<stdin>", line 1, in ?
73 File "<stdin>", line 1, in ?
74 AttributeError: Struct instance has no attribute 'key'
74 AttributeError: Struct instance has no attribute 'key'
75 >>> s[key]
75 >>> s[key]
76 10
76 10
77
77
78 Another limitation of the s.key syntax (and Struct(key=val)
78 Another limitation of the s.key syntax (and Struct(key=val)
79 initialization): keys can't be numbers. But numeric keys can be used and
79 initialization): keys can't be numbers. But numeric keys can be used and
80 accessed using the dictionary syntax. Again, an example:
80 accessed using the dictionary syntax. Again, an example:
81
81
82 This doesn't work:
82 This doesn't work:
83 >>> s=Struct(4='hi')
83 >>> s=Struct(4='hi')
84 SyntaxError: keyword can't be an expression
84 SyntaxError: keyword can't be an expression
85 But this does:
85 But this does:
86 >>> s=Struct()
86 >>> s=Struct()
87 >>> s[4]='hi'
87 >>> s[4]='hi'
88 >>> s
88 >>> s
89 Struct({4: 'hi'})
89 Struct({4: 'hi'})
90 >>> s[4]
90 >>> s[4]
91 'hi'
91 'hi'
92 """
92 """
93
93
94 # Attributes to which __setitem__ and __setattr__ will block access.
94 # Attributes to which __setitem__ and __setattr__ will block access.
95 # Note: much of this will be moot in Python 2.2 and will be done in a much
95 # Note: much of this will be moot in Python 2.2 and will be done in a much
96 # cleaner way.
96 # cleaner way.
97 __protected = ('copy dict dictcopy get has_attr has_key items keys '
97 __protected = ('copy dict dictcopy get has_attr has_key items keys '
98 'merge popitem setdefault update values '
98 'merge popitem setdefault update values '
99 '__make_dict __dict_invert ').split()
99 '__make_dict __dict_invert ').split()
100
100
101 def __init__(self,dict=None,**kw):
101 def __init__(self,dict=None,**kw):
102 """Initialize with a dictionary, another Struct, or by giving
102 """Initialize with a dictionary, another Struct, or by giving
103 explicitly the list of attributes.
103 explicitly the list of attributes.
104
104
105 Both can be used, but the dictionary must come first:
105 Both can be used, but the dictionary must come first:
106 Struct(dict), Struct(k1=v1,k2=v2) or Struct(dict,k1=v1,k2=v2).
106 Struct(dict), Struct(k1=v1,k2=v2) or Struct(dict,k1=v1,k2=v2).
107 """
107 """
108 if dict is None:
108 if dict is None:
109 dict = {}
109 dict = {}
110 if isinstance(dict,Struct):
110 if isinstance(dict,Struct):
111 dict = dict.dict()
111 dict = dict.dict()
112 elif dict and type(dict) is not types.DictType:
112 elif dict and type(dict) is not types.DictType:
113 raise TypeError,\
113 raise TypeError,\
114 'Initialize with a dictionary or key=val pairs.'
114 'Initialize with a dictionary or key=val pairs.'
115 dict.update(kw)
115 dict.update(kw)
116 # do the updating by hand to guarantee that we go through the
116 # do the updating by hand to guarantee that we go through the
117 # safety-checked __setitem__
117 # safety-checked __setitem__
118 for k,v in dict.items():
118 for k,v in dict.items():
119 self[k] = v
119 self[k] = v
120
120
121 def __setitem__(self,key,value):
121 def __setitem__(self,key,value):
122 """Used when struct[key] = val calls are made."""
122 """Used when struct[key] = val calls are made."""
123 if key in Struct.__protected:
123 if key in Struct.__protected:
124 raise KeyError,'Key '+`key`+' is a protected key of class Struct.'
124 raise KeyError,'Key '+`key`+' is a protected key of class Struct.'
125 self.__dict__[key] = value
125 self.__dict__[key] = value
126
126
127 def __setattr__(self, key, value):
127 def __setattr__(self, key, value):
128 """Used when struct.key = val calls are made."""
128 """Used when struct.key = val calls are made."""
129 self.__setitem__(key,value)
129 self.__setitem__(key,value)
130
130
131 def __str__(self):
131 def __str__(self):
132 """Gets called by print."""
132 """Gets called by print."""
133
133
134 return 'Struct('+str(self.__dict__)+')'
134 return 'Struct('+str(self.__dict__)+')'
135
135
136 def __repr__(self):
136 def __repr__(self):
137 """Gets called by repr.
137 """Gets called by repr.
138
138
139 A Struct can be recreated with S_new=eval(repr(S_old))."""
139 A Struct can be recreated with S_new=eval(repr(S_old))."""
140 return 'Struct('+str(self.__dict__)+')'
140 return 'Struct('+str(self.__dict__)+')'
141
141
142 def __getitem__(self,key):
142 def __getitem__(self,key):
143 """Allows struct[key] access."""
143 """Allows struct[key] access."""
144 return self.__dict__[key]
144 return self.__dict__[key]
145
145
146 def __contains__(self,key):
146 def __contains__(self,key):
147 """Allows use of the 'in' operator."""
147 """Allows use of the 'in' operator."""
148 return self.__dict__.has_key(key)
148 return self.__dict__.has_key(key)
149
149
150 def __iadd__(self,other):
150 def __iadd__(self,other):
151 """S += S2 is a shorthand for S.merge(S2)."""
151 """S += S2 is a shorthand for S.merge(S2)."""
152 self.merge(other)
152 self.merge(other)
153 return self
153 return self
154
154
155 def __add__(self,other):
155 def __add__(self,other):
156 """S + S2 -> New Struct made form S and S.merge(S2)"""
156 """S + S2 -> New Struct made form S and S.merge(S2)"""
157 Sout = self.copy()
157 Sout = self.copy()
158 Sout.merge(other)
158 Sout.merge(other)
159 return Sout
159 return Sout
160
160
161 def __sub__(self,other):
161 def __sub__(self,other):
162 """Return S1-S2, where all keys in S2 have been deleted (if present)
162 """Return S1-S2, where all keys in S2 have been deleted (if present)
163 from S1."""
163 from S1."""
164 Sout = self.copy()
164 Sout = self.copy()
165 Sout -= other
165 Sout -= other
166 return Sout
166 return Sout
167
167
168 def __isub__(self,other):
168 def __isub__(self,other):
169 """Do in place S = S - S2, meaning all keys in S2 have been deleted
169 """Do in place S = S - S2, meaning all keys in S2 have been deleted
170 (if present) from S1."""
170 (if present) from S1."""
171
171
172 for k in other.keys():
172 for k in other.keys():
173 if self.has_key(k):
173 if self.has_key(k):
174 del self.__dict__[k]
174 del self.__dict__[k]
175
175
176 def __make_dict(self,__loc_data__,**kw):
176 def __make_dict(self,__loc_data__,**kw):
177 "Helper function for update and merge. Return a dict from data."
177 "Helper function for update and merge. Return a dict from data."
178
178
179 if __loc_data__ == None:
179 if __loc_data__ == None:
180 dict = {}
180 dict = {}
181 elif type(__loc_data__) is types.DictType:
181 elif type(__loc_data__) is types.DictType:
182 dict = __loc_data__
182 dict = __loc_data__
183 elif isinstance(__loc_data__,Struct):
183 elif isinstance(__loc_data__,Struct):
184 dict = __loc_data__.__dict__
184 dict = __loc_data__.__dict__
185 else:
185 else:
186 raise TypeError, 'Update with a dict, a Struct or key=val pairs.'
186 raise TypeError, 'Update with a dict, a Struct or key=val pairs.'
187 if kw:
187 if kw:
188 dict.update(kw)
188 dict.update(kw)
189 return dict
189 return dict
190
190
191 def __dict_invert(self,dict):
191 def __dict_invert(self,dict):
192 """Helper function for merge. Takes a dictionary whose values are
192 """Helper function for merge. Takes a dictionary whose values are
193 lists and returns a dict. with the elements of each list as keys and
193 lists and returns a dict. with the elements of each list as keys and
194 the original keys as values."""
194 the original keys as values."""
195
195
196 outdict = {}
196 outdict = {}
197 for k,lst in dict.items():
197 for k,lst in dict.items():
198 if type(lst) is types.StringType:
198 if type(lst) is types.StringType:
199 lst = lst.split()
199 lst = lst.split()
200 for entry in lst:
200 for entry in lst:
201 outdict[entry] = k
201 outdict[entry] = k
202 return outdict
202 return outdict
203
203
204 def clear(self):
204 def clear(self):
205 """Clear all attributes."""
205 """Clear all attributes."""
206 self.__dict__.clear()
206 self.__dict__.clear()
207
207
208 def copy(self):
208 def copy(self):
209 """Return a (shallow) copy of a Struct."""
209 """Return a (shallow) copy of a Struct."""
210 return Struct(self.__dict__.copy())
210 return Struct(self.__dict__.copy())
211
211
212 def dict(self):
212 def dict(self):
213 """Return the Struct's dictionary."""
213 """Return the Struct's dictionary."""
214 return self.__dict__
214 return self.__dict__
215
215
216 def dictcopy(self):
216 def dictcopy(self):
217 """Return a (shallow) copy of the Struct's dictionary."""
217 """Return a (shallow) copy of the Struct's dictionary."""
218 return self.__dict__.copy()
218 return self.__dict__.copy()
219
219
220 def popitem(self):
220 def popitem(self):
221 """S.popitem() -> (k, v), remove and return some (key, value) pair as
221 """S.popitem() -> (k, v), remove and return some (key, value) pair as
222 a 2-tuple; but raise KeyError if S is empty."""
222 a 2-tuple; but raise KeyError if S is empty."""
223 return self.__dict__.popitem()
223 return self.__dict__.popitem()
224
224
225 def update(self,__loc_data__=None,**kw):
225 def update(self,__loc_data__=None,**kw):
226 """Update (merge) with data from another Struct or from a dictionary.
226 """Update (merge) with data from another Struct or from a dictionary.
227 Optionally, one or more key=value pairs can be given at the end for
227 Optionally, one or more key=value pairs can be given at the end for
228 direct update."""
228 direct update."""
229
229
230 # The funny name __loc_data__ is to prevent a common variable name which
230 # The funny name __loc_data__ is to prevent a common variable name which
231 # could be a fieled of a Struct to collide with this parameter. The problem
231 # could be a fieled of a Struct to collide with this parameter. The problem
232 # would arise if the function is called with a keyword with this same name
232 # would arise if the function is called with a keyword with this same name
233 # that a user means to add as a Struct field.
233 # that a user means to add as a Struct field.
234 newdict = Struct.__make_dict(self,__loc_data__,**kw)
234 newdict = Struct.__make_dict(self,__loc_data__,**kw)
235 for k,v in newdict.items():
235 for k,v in newdict.items():
236 self[k] = v
236 self[k] = v
237
237
238 def merge(self,__loc_data__=None,__conflict_solve=None,**kw):
238 def merge(self,__loc_data__=None,__conflict_solve=None,**kw):
239 """S.merge(data,conflict,k=v1,k=v2,...) -> merge data and k=v into S.
239 """S.merge(data,conflict,k=v1,k=v2,...) -> merge data and k=v into S.
240
240
241 This is similar to update(), but much more flexible. First, a dict is
241 This is similar to update(), but much more flexible. First, a dict is
242 made from data+key=value pairs. When merging this dict with the Struct
242 made from data+key=value pairs. When merging this dict with the Struct
243 S, the optional dictionary 'conflict' is used to decide what to do.
243 S, the optional dictionary 'conflict' is used to decide what to do.
244
244
245 If conflict is not given, the default behavior is to preserve any keys
245 If conflict is not given, the default behavior is to preserve any keys
246 with their current value (the opposite of the update method's
246 with their current value (the opposite of the update method's
247 behavior).
247 behavior).
248
248
249 conflict is a dictionary of binary functions which will be used to
249 conflict is a dictionary of binary functions which will be used to
250 solve key conflicts. It must have the following structure:
250 solve key conflicts. It must have the following structure:
251
251
252 conflict == { fn1 : [Skey1,Skey2,...], fn2 : [Skey3], etc }
252 conflict == { fn1 : [Skey1,Skey2,...], fn2 : [Skey3], etc }
253
253
254 Values must be lists or whitespace separated strings which are
254 Values must be lists or whitespace separated strings which are
255 automatically converted to lists of strings by calling string.split().
255 automatically converted to lists of strings by calling string.split().
256
256
257 Each key of conflict is a function which defines a policy for
257 Each key of conflict is a function which defines a policy for
258 resolving conflicts when merging with the input data. Each fn must be
258 resolving conflicts when merging with the input data. Each fn must be
259 a binary function which returns the desired outcome for a key
259 a binary function which returns the desired outcome for a key
260 conflict. These functions will be called as fn(old,new).
260 conflict. These functions will be called as fn(old,new).
261
261
262 An example is probably in order. Suppose you are merging the struct S
262 An example is probably in order. Suppose you are merging the struct S
263 with a dict D and the following conflict policy dict:
263 with a dict D and the following conflict policy dict:
264
264
265 S.merge(D,{fn1:['a','b',4], fn2:'key_c key_d'})
265 S.merge(D,{fn1:['a','b',4], fn2:'key_c key_d'})
266
266
267 If the key 'a' is found in both S and D, the merge method will call:
267 If the key 'a' is found in both S and D, the merge method will call:
268
268
269 S['a'] = fn1(S['a'],D['a'])
269 S['a'] = fn1(S['a'],D['a'])
270
270
271 As a convenience, merge() provides five (the most commonly needed)
271 As a convenience, merge() provides five (the most commonly needed)
272 pre-defined policies: preserve, update, add, add_flip and add_s. The
272 pre-defined policies: preserve, update, add, add_flip and add_s. The
273 easiest explanation is their implementation:
273 easiest explanation is their implementation:
274
274
275 preserve = lambda old,new: old
275 preserve = lambda old,new: old
276 update = lambda old,new: new
276 update = lambda old,new: new
277 add = lambda old,new: old + new
277 add = lambda old,new: old + new
278 add_flip = lambda old,new: new + old # note change of order!
278 add_flip = lambda old,new: new + old # note change of order!
279 add_s = lambda old,new: old + ' ' + new # only works for strings!
279 add_s = lambda old,new: old + ' ' + new # only works for strings!
280
280
281 You can use those four words (as strings) as keys in conflict instead
281 You can use those four words (as strings) as keys in conflict instead
282 of defining them as functions, and the merge method will substitute
282 of defining them as functions, and the merge method will substitute
283 the appropriate functions for you. That is, the call
283 the appropriate functions for you. That is, the call
284
284
285 S.merge(D,{'preserve':'a b c','add':[4,5,'d'],my_function:[6]})
285 S.merge(D,{'preserve':'a b c','add':[4,5,'d'],my_function:[6]})
286
286
287 will automatically substitute the functions preserve and add for the
287 will automatically substitute the functions preserve and add for the
288 names 'preserve' and 'add' before making any function calls.
288 names 'preserve' and 'add' before making any function calls.
289
289
290 For more complicated conflict resolution policies, you still need to
290 For more complicated conflict resolution policies, you still need to
291 construct your own functions. """
291 construct your own functions. """
292
292
293 data_dict = Struct.__make_dict(self,__loc_data__,**kw)
293 data_dict = Struct.__make_dict(self,__loc_data__,**kw)
294
294
295 # policies for conflict resolution: two argument functions which return
295 # policies for conflict resolution: two argument functions which return
296 # the value that will go in the new struct
296 # the value that will go in the new struct
297 preserve = lambda old,new: old
297 preserve = lambda old,new: old
298 update = lambda old,new: new
298 update = lambda old,new: new
299 add = lambda old,new: old + new
299 add = lambda old,new: old + new
300 add_flip = lambda old,new: new + old # note change of order!
300 add_flip = lambda old,new: new + old # note change of order!
301 add_s = lambda old,new: old + ' ' + new
301 add_s = lambda old,new: old + ' ' + new
302
302
303 # default policy is to keep current keys when there's a conflict
303 # default policy is to keep current keys when there's a conflict
304 conflict_solve = list2dict2(self.keys(),default = preserve)
304 conflict_solve = list2dict2(self.keys(),default = preserve)
305
305
306 # the conflict_solve dictionary is given by the user 'inverted': we
306 # the conflict_solve dictionary is given by the user 'inverted': we
307 # need a name-function mapping, it comes as a function -> names
307 # need a name-function mapping, it comes as a function -> names
308 # dict. Make a local copy (b/c we'll make changes), replace user
308 # dict. Make a local copy (b/c we'll make changes), replace user
309 # strings for the three builtin policies and invert it.
309 # strings for the three builtin policies and invert it.
310 if __conflict_solve:
310 if __conflict_solve:
311 inv_conflict_solve_user = __conflict_solve.copy()
311 inv_conflict_solve_user = __conflict_solve.copy()
312 for name, func in [('preserve',preserve), ('update',update),
312 for name, func in [('preserve',preserve), ('update',update),
313 ('add',add), ('add_flip',add_flip), ('add_s',add_s)]:
313 ('add',add), ('add_flip',add_flip), ('add_s',add_s)]:
314 if name in inv_conflict_solve_user.keys():
314 if name in inv_conflict_solve_user.keys():
315 inv_conflict_solve_user[func] = inv_conflict_solve_user[name]
315 inv_conflict_solve_user[func] = inv_conflict_solve_user[name]
316 del inv_conflict_solve_user[name]
316 del inv_conflict_solve_user[name]
317 conflict_solve.update(Struct.__dict_invert(self,inv_conflict_solve_user))
317 conflict_solve.update(Struct.__dict_invert(self,inv_conflict_solve_user))
318 #print 'merge. conflict_solve: '; pprint(conflict_solve) # dbg
318 #print 'merge. conflict_solve: '; pprint(conflict_solve) # dbg
319 #print '*'*50,'in merger. conflict_solver:'; pprint(conflict_solve)
319 #print '*'*50,'in merger. conflict_solver:'; pprint(conflict_solve)
320 for key in data_dict:
320 for key in data_dict:
321 if key not in self:
321 if key not in self:
322 self[key] = data_dict[key]
322 self[key] = data_dict[key]
323 else:
323 else:
324 self[key] = conflict_solve[key](self[key],data_dict[key])
324 self[key] = conflict_solve[key](self[key],data_dict[key])
325
325
326 def has_key(self,key):
326 def has_key(self,key):
327 """Like has_key() dictionary method."""
327 """Like has_key() dictionary method."""
328 return self.__dict__.has_key(key)
328 return self.__dict__.has_key(key)
329
329
330 def hasattr(self,key):
330 def hasattr(self,key):
331 """hasattr function available as a method.
331 """hasattr function available as a method.
332
332
333 Implemented like has_key, to make sure that all available keys in the
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
334 internal dictionary of the Struct appear also as attributes (even
335 numeric keys)."""
335 numeric keys)."""
336 return self.__dict__.has_key(key)
336 return self.__dict__.has_key(key)
337
337
338 def items(self):
338 def items(self):
339 """Return the items in the Struct's dictionary, in the same format
339 """Return the items in the Struct's dictionary, in the same format
340 as a call to {}.items()."""
340 as a call to {}.items()."""
341 return self.__dict__.items()
341 return self.__dict__.items()
342
342
343 def keys(self):
343 def keys(self):
344 """Return the keys in the Struct's dictionary, in the same format
344 """Return the keys in the Struct's dictionary, in the same format
345 as a call to {}.keys()."""
345 as a call to {}.keys()."""
346 return self.__dict__.keys()
346 return self.__dict__.keys()
347
347
348 def values(self,keys=None):
348 def values(self,keys=None):
349 """Return the values in the Struct's dictionary, in the same format
349 """Return the values in the Struct's dictionary, in the same format
350 as a call to {}.values().
350 as a call to {}.values().
351
351
352 Can be called with an optional argument keys, which must be a list or
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
353 tuple of keys. In this case it returns only the values corresponding
354 to those keys (allowing a form of 'slicing' for Structs)."""
354 to those keys (allowing a form of 'slicing' for Structs)."""
355 if not keys:
355 if not keys:
356 return self.__dict__.values()
356 return self.__dict__.values()
357 else:
357 else:
358 ret=[]
358 ret=[]
359 for k in keys:
359 for k in keys:
360 ret.append(self[k])
360 ret.append(self[k])
361 return ret
361 return ret
362
362
363 def get(self,attr,val=None):
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."""
364 """S.get(k[,d]) -> S[k] if S.has_key(k), else d. d defaults to None."""
365 try:
365 try:
366 return self[attr]
366 return self[attr]
367 except KeyError:
367 except KeyError:
368 return val
368 return val
369
369
370 def setdefault(self,attr,val=None):
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)"""
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):
372 if not self.has_key(attr):
373 self[attr] = val
373 self[attr] = val
374 return self.get(attr,val)
374 return self.get(attr,val)
375 # end class Struct
375 # end class Struct
376
376
@@ -1,857 +1,857 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 ultraTB.py -- Spice up your tracebacks!
3 ultraTB.py -- Spice up your tracebacks!
4
4
5 * ColorTB
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
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
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
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
9 text editor.
10
10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB:
12 import sys,ultraTB
12 import sys,ultraTB
13 sys.excepthook = ultraTB.ColorTB()
13 sys.excepthook = ultraTB.ColorTB()
14
14
15 * VerboseTB
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
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
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
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,
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
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.
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.
22 Give it a shot--you'll love it or you'll hate it.
23
23
24 Note:
24 Note:
25
25
26 The Verbose mode prints the variables currently visible where the exception
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
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
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
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
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).
31 with Ctrl-C (maybe hitting it more than once).
32
32
33 If you encounter this kind of situation often, you may want to use the
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
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
35 variables (but otherwise includes the information and context given by
36 Verbose).
36 Verbose).
37
37
38
38
39 Installation instructions for ColorTB:
39 Installation instructions for ColorTB:
40 import sys,ultraTB
40 import sys,ultraTB
41 sys.excepthook = ultraTB.VerboseTB()
41 sys.excepthook = ultraTB.VerboseTB()
42
42
43 Note: Much of the code in this module was lifted verbatim from the standard
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'.
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
45
46 * Color schemes
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
48 ColorSchemeTable class. Currently the following exist:
49
49
50 - NoColor: allows all of this module to be used in any terminal (the color
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
51 escapes are just dummy blank strings).
52
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
54 or very dark background).
55
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
57 in light background terminals.
58
58
59 You can implement other color schemes easily, the syntax is fairly
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
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
61 possible inclusion in future releases.
62
62
63 $Id: ultraTB.py 994 2006-01-08 08:29:44Z fperez $"""
63 $Id: ultraTB.py 1005 2006-01-12 08:39:26Z fperez $"""
64
64
65 #*****************************************************************************
65 #*****************************************************************************
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68 #
68 #
69 # Distributed under the terms of the BSD License. The full license is in
69 # Distributed under the terms of the BSD License. The full license is in
70 # the file COPYING, distributed as part of this software.
70 # the file COPYING, distributed as part of this software.
71 #*****************************************************************************
71 #*****************************************************************************
72
72
73 from IPython import Release
73 from IPython import Release
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 Release.authors['Fernando'])
75 Release.authors['Fernando'])
76 __license__ = Release.license
76 __license__ = Release.license
77
77
78 # Required modules
78 # Required modules
79 import inspect
79 import inspect
80 import keyword
80 import keyword
81 import linecache
81 import linecache
82 import os
82 import os
83 import pydoc
83 import pydoc
84 import string
84 import string
85 import sys
85 import sys
86 import time
86 import time
87 import tokenize
87 import tokenize
88 import traceback
88 import traceback
89 import types
89 import types
90
90
91 # IPython's own modules
91 # IPython's own modules
92 # Modified pdb which doesn't damage IPython's readline handling
92 # Modified pdb which doesn't damage IPython's readline handling
93 from IPython import Debugger
93 from IPython import Debugger
94 from IPython.Struct import Struct
94 from IPython.ipstruct import Struct
95 from IPython.excolors import ExceptionColors
95 from IPython.excolors import ExceptionColors
96 from IPython.genutils import Term,uniq_stable,error,info
96 from IPython.genutils import Term,uniq_stable,error,info
97
97
98 # Globals
98 # Globals
99 # amount of space to put line numbers before verbose tracebacks
99 # amount of space to put line numbers before verbose tracebacks
100 INDENT_SIZE = 8
100 INDENT_SIZE = 8
101
101
102 #---------------------------------------------------------------------------
102 #---------------------------------------------------------------------------
103 # Code begins
103 # Code begins
104
104
105 # Utility functions
105 # Utility functions
106 def inspect_error():
106 def inspect_error():
107 """Print a message about internal inspect errors.
107 """Print a message about internal inspect errors.
108
108
109 These are unfortunately quite common."""
109 These are unfortunately quite common."""
110
110
111 error('Internal Python error in the inspect module.\n'
111 error('Internal Python error in the inspect module.\n'
112 'Below is the traceback from this internal error.\n')
112 'Below is the traceback from this internal error.\n')
113
113
114 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
114 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
115 import linecache
115 import linecache
116 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
116 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
117
117
118 records = inspect.getinnerframes(etb, context)
118 records = inspect.getinnerframes(etb, context)
119
119
120 # If the error is at the console, don't build any context, since it would
120 # If the error is at the console, don't build any context, since it would
121 # otherwise produce 5 blank lines printed out (there is no file at the
121 # otherwise produce 5 blank lines printed out (there is no file at the
122 # console)
122 # console)
123 rec_check = records[tb_offset:]
123 rec_check = records[tb_offset:]
124 try:
124 try:
125 rname = rec_check[0][1]
125 rname = rec_check[0][1]
126 if rname == '<ipython console>' or rname.endswith('<string>'):
126 if rname == '<ipython console>' or rname.endswith('<string>'):
127 return rec_check
127 return rec_check
128 except IndexError:
128 except IndexError:
129 pass
129 pass
130
130
131 aux = traceback.extract_tb(etb)
131 aux = traceback.extract_tb(etb)
132 assert len(records) == len(aux)
132 assert len(records) == len(aux)
133 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
133 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
134 maybeStart = lnum-1 - context//2
134 maybeStart = lnum-1 - context//2
135 start = max(maybeStart, 0)
135 start = max(maybeStart, 0)
136 end = start + context
136 end = start + context
137 lines = linecache.getlines(file)[start:end]
137 lines = linecache.getlines(file)[start:end]
138 # pad with empty lines if necessary
138 # pad with empty lines if necessary
139 if maybeStart < 0:
139 if maybeStart < 0:
140 lines = (['\n'] * -maybeStart) + lines
140 lines = (['\n'] * -maybeStart) + lines
141 if len(lines) < context:
141 if len(lines) < context:
142 lines += ['\n'] * (context - len(lines))
142 lines += ['\n'] * (context - len(lines))
143 buf = list(records[i])
143 buf = list(records[i])
144 buf[LNUM_POS] = lnum
144 buf[LNUM_POS] = lnum
145 buf[INDEX_POS] = lnum - 1 - start
145 buf[INDEX_POS] = lnum - 1 - start
146 buf[LINES_POS] = lines
146 buf[LINES_POS] = lines
147 records[i] = tuple(buf)
147 records[i] = tuple(buf)
148 return records[tb_offset:]
148 return records[tb_offset:]
149
149
150 # Helper function -- largely belongs to VerboseTB, but we need the same
150 # Helper function -- largely belongs to VerboseTB, but we need the same
151 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
151 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
152 # can be recognized properly by ipython.el's py-traceback-line-re
152 # can be recognized properly by ipython.el's py-traceback-line-re
153 # (SyntaxErrors have to be treated specially because they have no traceback)
153 # (SyntaxErrors have to be treated specially because they have no traceback)
154 def _formatTracebackLines(lnum, index, lines, Colors, lvals=None):
154 def _formatTracebackLines(lnum, index, lines, Colors, lvals=None):
155 numbers_width = INDENT_SIZE - 1
155 numbers_width = INDENT_SIZE - 1
156 res = []
156 res = []
157 i = lnum - index
157 i = lnum - index
158 for line in lines:
158 for line in lines:
159 if i == lnum:
159 if i == lnum:
160 # This is the line with the error
160 # This is the line with the error
161 pad = numbers_width - len(str(i))
161 pad = numbers_width - len(str(i))
162 if pad >= 3:
162 if pad >= 3:
163 marker = '-'*(pad-3) + '-> '
163 marker = '-'*(pad-3) + '-> '
164 elif pad == 2:
164 elif pad == 2:
165 marker = '> '
165 marker = '> '
166 elif pad == 1:
166 elif pad == 1:
167 marker = '>'
167 marker = '>'
168 else:
168 else:
169 marker = ''
169 marker = ''
170 num = marker + str(i)
170 num = marker + str(i)
171 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
171 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
172 Colors.line, line, Colors.Normal)
172 Colors.line, line, Colors.Normal)
173 else:
173 else:
174 num = '%*s' % (numbers_width,i)
174 num = '%*s' % (numbers_width,i)
175 line = '%s%s%s %s' %(Colors.lineno, num,
175 line = '%s%s%s %s' %(Colors.lineno, num,
176 Colors.Normal, line)
176 Colors.Normal, line)
177
177
178 res.append(line)
178 res.append(line)
179 if lvals and i == lnum:
179 if lvals and i == lnum:
180 res.append(lvals + '\n')
180 res.append(lvals + '\n')
181 i = i + 1
181 i = i + 1
182 return res
182 return res
183
183
184 #---------------------------------------------------------------------------
184 #---------------------------------------------------------------------------
185 # Module classes
185 # Module classes
186 class TBTools:
186 class TBTools:
187 """Basic tools used by all traceback printer classes."""
187 """Basic tools used by all traceback printer classes."""
188
188
189 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
189 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
190 # Whether to call the interactive pdb debugger after printing
190 # Whether to call the interactive pdb debugger after printing
191 # tracebacks or not
191 # tracebacks or not
192 self.call_pdb = call_pdb
192 self.call_pdb = call_pdb
193
193
194 # Create color table
194 # Create color table
195 self.color_scheme_table = ExceptionColors
195 self.color_scheme_table = ExceptionColors
196
196
197 self.set_colors(color_scheme)
197 self.set_colors(color_scheme)
198 self.old_scheme = color_scheme # save initial value for toggles
198 self.old_scheme = color_scheme # save initial value for toggles
199
199
200 if call_pdb:
200 if call_pdb:
201 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
201 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
202 else:
202 else:
203 self.pdb = None
203 self.pdb = None
204
204
205 def set_colors(self,*args,**kw):
205 def set_colors(self,*args,**kw):
206 """Shorthand access to the color table scheme selector method."""
206 """Shorthand access to the color table scheme selector method."""
207
207
208 self.color_scheme_table.set_active_scheme(*args,**kw)
208 self.color_scheme_table.set_active_scheme(*args,**kw)
209 # for convenience, set Colors to the active scheme
209 # for convenience, set Colors to the active scheme
210 self.Colors = self.color_scheme_table.active_colors
210 self.Colors = self.color_scheme_table.active_colors
211
211
212 def color_toggle(self):
212 def color_toggle(self):
213 """Toggle between the currently active color scheme and NoColor."""
213 """Toggle between the currently active color scheme and NoColor."""
214
214
215 if self.color_scheme_table.active_scheme_name == 'NoColor':
215 if self.color_scheme_table.active_scheme_name == 'NoColor':
216 self.color_scheme_table.set_active_scheme(self.old_scheme)
216 self.color_scheme_table.set_active_scheme(self.old_scheme)
217 self.Colors = self.color_scheme_table.active_colors
217 self.Colors = self.color_scheme_table.active_colors
218 else:
218 else:
219 self.old_scheme = self.color_scheme_table.active_scheme_name
219 self.old_scheme = self.color_scheme_table.active_scheme_name
220 self.color_scheme_table.set_active_scheme('NoColor')
220 self.color_scheme_table.set_active_scheme('NoColor')
221 self.Colors = self.color_scheme_table.active_colors
221 self.Colors = self.color_scheme_table.active_colors
222
222
223 #---------------------------------------------------------------------------
223 #---------------------------------------------------------------------------
224 class ListTB(TBTools):
224 class ListTB(TBTools):
225 """Print traceback information from a traceback list, with optional color.
225 """Print traceback information from a traceback list, with optional color.
226
226
227 Calling: requires 3 arguments:
227 Calling: requires 3 arguments:
228 (etype, evalue, elist)
228 (etype, evalue, elist)
229 as would be obtained by:
229 as would be obtained by:
230 etype, evalue, tb = sys.exc_info()
230 etype, evalue, tb = sys.exc_info()
231 if tb:
231 if tb:
232 elist = traceback.extract_tb(tb)
232 elist = traceback.extract_tb(tb)
233 else:
233 else:
234 elist = None
234 elist = None
235
235
236 It can thus be used by programs which need to process the traceback before
236 It can thus be used by programs which need to process the traceback before
237 printing (such as console replacements based on the code module from the
237 printing (such as console replacements based on the code module from the
238 standard library).
238 standard library).
239
239
240 Because they are meant to be called without a full traceback (only a
240 Because they are meant to be called without a full traceback (only a
241 list), instances of this class can't call the interactive pdb debugger."""
241 list), instances of this class can't call the interactive pdb debugger."""
242
242
243 def __init__(self,color_scheme = 'NoColor'):
243 def __init__(self,color_scheme = 'NoColor'):
244 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
244 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
245
245
246 def __call__(self, etype, value, elist):
246 def __call__(self, etype, value, elist):
247 print >> Term.cerr, self.text(etype,value,elist)
247 print >> Term.cerr, self.text(etype,value,elist)
248
248
249 def text(self,etype, value, elist,context=5):
249 def text(self,etype, value, elist,context=5):
250 """Return a color formatted string with the traceback info."""
250 """Return a color formatted string with the traceback info."""
251
251
252 Colors = self.Colors
252 Colors = self.Colors
253 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
253 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
254 if elist:
254 if elist:
255 out_string.append('Traceback %s(most recent call last)%s:' % \
255 out_string.append('Traceback %s(most recent call last)%s:' % \
256 (Colors.normalEm, Colors.Normal) + '\n')
256 (Colors.normalEm, Colors.Normal) + '\n')
257 out_string.extend(self._format_list(elist))
257 out_string.extend(self._format_list(elist))
258 lines = self._format_exception_only(etype, value)
258 lines = self._format_exception_only(etype, value)
259 for line in lines[:-1]:
259 for line in lines[:-1]:
260 out_string.append(" "+line)
260 out_string.append(" "+line)
261 out_string.append(lines[-1])
261 out_string.append(lines[-1])
262 return ''.join(out_string)
262 return ''.join(out_string)
263
263
264 def _format_list(self, extracted_list):
264 def _format_list(self, extracted_list):
265 """Format a list of traceback entry tuples for printing.
265 """Format a list of traceback entry tuples for printing.
266
266
267 Given a list of tuples as returned by extract_tb() or
267 Given a list of tuples as returned by extract_tb() or
268 extract_stack(), return a list of strings ready for printing.
268 extract_stack(), return a list of strings ready for printing.
269 Each string in the resulting list corresponds to the item with the
269 Each string in the resulting list corresponds to the item with the
270 same index in the argument list. Each string ends in a newline;
270 same index in the argument list. Each string ends in a newline;
271 the strings may contain internal newlines as well, for those items
271 the strings may contain internal newlines as well, for those items
272 whose source text line is not None.
272 whose source text line is not None.
273
273
274 Lifted almost verbatim from traceback.py
274 Lifted almost verbatim from traceback.py
275 """
275 """
276
276
277 Colors = self.Colors
277 Colors = self.Colors
278 list = []
278 list = []
279 for filename, lineno, name, line in extracted_list[:-1]:
279 for filename, lineno, name, line in extracted_list[:-1]:
280 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
280 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
281 (Colors.filename, filename, Colors.Normal,
281 (Colors.filename, filename, Colors.Normal,
282 Colors.lineno, lineno, Colors.Normal,
282 Colors.lineno, lineno, Colors.Normal,
283 Colors.name, name, Colors.Normal)
283 Colors.name, name, Colors.Normal)
284 if line:
284 if line:
285 item = item + ' %s\n' % line.strip()
285 item = item + ' %s\n' % line.strip()
286 list.append(item)
286 list.append(item)
287 # Emphasize the last entry
287 # Emphasize the last entry
288 filename, lineno, name, line = extracted_list[-1]
288 filename, lineno, name, line = extracted_list[-1]
289 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
289 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
290 (Colors.normalEm,
290 (Colors.normalEm,
291 Colors.filenameEm, filename, Colors.normalEm,
291 Colors.filenameEm, filename, Colors.normalEm,
292 Colors.linenoEm, lineno, Colors.normalEm,
292 Colors.linenoEm, lineno, Colors.normalEm,
293 Colors.nameEm, name, Colors.normalEm,
293 Colors.nameEm, name, Colors.normalEm,
294 Colors.Normal)
294 Colors.Normal)
295 if line:
295 if line:
296 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
296 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
297 Colors.Normal)
297 Colors.Normal)
298 list.append(item)
298 list.append(item)
299 return list
299 return list
300
300
301 def _format_exception_only(self, etype, value):
301 def _format_exception_only(self, etype, value):
302 """Format the exception part of a traceback.
302 """Format the exception part of a traceback.
303
303
304 The arguments are the exception type and value such as given by
304 The arguments are the exception type and value such as given by
305 sys.exc_info()[:2]. The return value is a list of strings, each ending
305 sys.exc_info()[:2]. The return value is a list of strings, each ending
306 in a newline. Normally, the list contains a single string; however,
306 in a newline. Normally, the list contains a single string; however,
307 for SyntaxError exceptions, it contains several lines that (when
307 for SyntaxError exceptions, it contains several lines that (when
308 printed) display detailed information about where the syntax error
308 printed) display detailed information about where the syntax error
309 occurred. The message indicating which exception occurred is the
309 occurred. The message indicating which exception occurred is the
310 always last string in the list.
310 always last string in the list.
311
311
312 Also lifted nearly verbatim from traceback.py
312 Also lifted nearly verbatim from traceback.py
313 """
313 """
314
314
315 Colors = self.Colors
315 Colors = self.Colors
316 list = []
316 list = []
317 if type(etype) == types.ClassType:
317 if type(etype) == types.ClassType:
318 stype = Colors.excName + etype.__name__ + Colors.Normal
318 stype = Colors.excName + etype.__name__ + Colors.Normal
319 else:
319 else:
320 stype = etype # String exceptions don't get special coloring
320 stype = etype # String exceptions don't get special coloring
321 if value is None:
321 if value is None:
322 list.append( str(stype) + '\n')
322 list.append( str(stype) + '\n')
323 else:
323 else:
324 if etype is SyntaxError:
324 if etype is SyntaxError:
325 try:
325 try:
326 msg, (filename, lineno, offset, line) = value
326 msg, (filename, lineno, offset, line) = value
327 except:
327 except:
328 pass
328 pass
329 else:
329 else:
330 #print 'filename is',filename # dbg
330 #print 'filename is',filename # dbg
331 if not filename: filename = "<string>"
331 if not filename: filename = "<string>"
332 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
332 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
333 (Colors.normalEm,
333 (Colors.normalEm,
334 Colors.filenameEm, filename, Colors.normalEm,
334 Colors.filenameEm, filename, Colors.normalEm,
335 Colors.linenoEm, lineno, Colors.Normal ))
335 Colors.linenoEm, lineno, Colors.Normal ))
336 if line is not None:
336 if line is not None:
337 i = 0
337 i = 0
338 while i < len(line) and line[i].isspace():
338 while i < len(line) and line[i].isspace():
339 i = i+1
339 i = i+1
340 list.append('%s %s%s\n' % (Colors.line,
340 list.append('%s %s%s\n' % (Colors.line,
341 line.strip(),
341 line.strip(),
342 Colors.Normal))
342 Colors.Normal))
343 if offset is not None:
343 if offset is not None:
344 s = ' '
344 s = ' '
345 for c in line[i:offset-1]:
345 for c in line[i:offset-1]:
346 if c.isspace():
346 if c.isspace():
347 s = s + c
347 s = s + c
348 else:
348 else:
349 s = s + ' '
349 s = s + ' '
350 list.append('%s%s^%s\n' % (Colors.caret, s,
350 list.append('%s%s^%s\n' % (Colors.caret, s,
351 Colors.Normal) )
351 Colors.Normal) )
352 value = msg
352 value = msg
353 s = self._some_str(value)
353 s = self._some_str(value)
354 if s:
354 if s:
355 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
355 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
356 Colors.Normal, s))
356 Colors.Normal, s))
357 else:
357 else:
358 list.append('%s\n' % str(stype))
358 list.append('%s\n' % str(stype))
359 return list
359 return list
360
360
361 def _some_str(self, value):
361 def _some_str(self, value):
362 # Lifted from traceback.py
362 # Lifted from traceback.py
363 try:
363 try:
364 return str(value)
364 return str(value)
365 except:
365 except:
366 return '<unprintable %s object>' % type(value).__name__
366 return '<unprintable %s object>' % type(value).__name__
367
367
368 #----------------------------------------------------------------------------
368 #----------------------------------------------------------------------------
369 class VerboseTB(TBTools):
369 class VerboseTB(TBTools):
370 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
370 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
371 of HTML. Requires inspect and pydoc. Crazy, man.
371 of HTML. Requires inspect and pydoc. Crazy, man.
372
372
373 Modified version which optionally strips the topmost entries from the
373 Modified version which optionally strips the topmost entries from the
374 traceback, to be used with alternate interpreters (because their own code
374 traceback, to be used with alternate interpreters (because their own code
375 would appear in the traceback)."""
375 would appear in the traceback)."""
376
376
377 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
377 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
378 call_pdb = 0, include_vars=1):
378 call_pdb = 0, include_vars=1):
379 """Specify traceback offset, headers and color scheme.
379 """Specify traceback offset, headers and color scheme.
380
380
381 Define how many frames to drop from the tracebacks. Calling it with
381 Define how many frames to drop from the tracebacks. Calling it with
382 tb_offset=1 allows use of this handler in interpreters which will have
382 tb_offset=1 allows use of this handler in interpreters which will have
383 their own code at the top of the traceback (VerboseTB will first
383 their own code at the top of the traceback (VerboseTB will first
384 remove that frame before printing the traceback info)."""
384 remove that frame before printing the traceback info)."""
385 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
385 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
386 self.tb_offset = tb_offset
386 self.tb_offset = tb_offset
387 self.long_header = long_header
387 self.long_header = long_header
388 self.include_vars = include_vars
388 self.include_vars = include_vars
389
389
390 def text(self, etype, evalue, etb, context=5):
390 def text(self, etype, evalue, etb, context=5):
391 """Return a nice text document describing the traceback."""
391 """Return a nice text document describing the traceback."""
392
392
393 # some locals
393 # some locals
394 Colors = self.Colors # just a shorthand + quicker name lookup
394 Colors = self.Colors # just a shorthand + quicker name lookup
395 ColorsNormal = Colors.Normal # used a lot
395 ColorsNormal = Colors.Normal # used a lot
396 indent = ' '*INDENT_SIZE
396 indent = ' '*INDENT_SIZE
397 text_repr = pydoc.text.repr
397 text_repr = pydoc.text.repr
398 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
398 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
399 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
399 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
400 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
400 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
401
401
402 # some internal-use functions
402 # some internal-use functions
403 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
403 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
404 def nullrepr(value, repr=text_repr): return ''
404 def nullrepr(value, repr=text_repr): return ''
405
405
406 # meat of the code begins
406 # meat of the code begins
407 if type(etype) is types.ClassType:
407 if type(etype) is types.ClassType:
408 etype = etype.__name__
408 etype = etype.__name__
409
409
410 if self.long_header:
410 if self.long_header:
411 # Header with the exception type, python version, and date
411 # Header with the exception type, python version, and date
412 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
412 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
413 date = time.ctime(time.time())
413 date = time.ctime(time.time())
414
414
415 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
415 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
416 exc, ' '*(75-len(str(etype))-len(pyver)),
416 exc, ' '*(75-len(str(etype))-len(pyver)),
417 pyver, string.rjust(date, 75) )
417 pyver, string.rjust(date, 75) )
418 head += "\nA problem occured executing Python code. Here is the sequence of function"\
418 head += "\nA problem occured executing Python code. Here is the sequence of function"\
419 "\ncalls leading up to the error, with the most recent (innermost) call last."
419 "\ncalls leading up to the error, with the most recent (innermost) call last."
420 else:
420 else:
421 # Simplified header
421 # Simplified header
422 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
422 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
423 string.rjust('Traceback (most recent call last)',
423 string.rjust('Traceback (most recent call last)',
424 75 - len(str(etype)) ) )
424 75 - len(str(etype)) ) )
425 frames = []
425 frames = []
426 # Flush cache before calling inspect. This helps alleviate some of the
426 # Flush cache before calling inspect. This helps alleviate some of the
427 # problems with python 2.3's inspect.py.
427 # problems with python 2.3's inspect.py.
428 linecache.checkcache()
428 linecache.checkcache()
429 # Drop topmost frames if requested
429 # Drop topmost frames if requested
430 try:
430 try:
431 # Try the default getinnerframes and Alex's: Alex's fixes some
431 # Try the default getinnerframes and Alex's: Alex's fixes some
432 # problems, but it generates empty tracebacks for console errors
432 # problems, but it generates empty tracebacks for console errors
433 # (5 blanks lines) where none should be returned.
433 # (5 blanks lines) where none should be returned.
434 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
434 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
435 #print 'python records:', records # dbg
435 #print 'python records:', records # dbg
436 records = _fixed_getinnerframes(etb, context,self.tb_offset)
436 records = _fixed_getinnerframes(etb, context,self.tb_offset)
437 #print 'alex records:', records # dbg
437 #print 'alex records:', records # dbg
438 except:
438 except:
439
439
440 # FIXME: I've been getting many crash reports from python 2.3
440 # FIXME: I've been getting many crash reports from python 2.3
441 # users, traceable to inspect.py. If I can find a small test-case
441 # users, traceable to inspect.py. If I can find a small test-case
442 # to reproduce this, I should either write a better workaround or
442 # to reproduce this, I should either write a better workaround or
443 # file a bug report against inspect (if that's the real problem).
443 # file a bug report against inspect (if that's the real problem).
444 # So far, I haven't been able to find an isolated example to
444 # So far, I haven't been able to find an isolated example to
445 # reproduce the problem.
445 # reproduce the problem.
446 inspect_error()
446 inspect_error()
447 traceback.print_exc(file=Term.cerr)
447 traceback.print_exc(file=Term.cerr)
448 info('\nUnfortunately, your original traceback can not be constructed.\n')
448 info('\nUnfortunately, your original traceback can not be constructed.\n')
449 return ''
449 return ''
450
450
451 # build some color string templates outside these nested loops
451 # build some color string templates outside these nested loops
452 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
452 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
453 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
453 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
454 ColorsNormal)
454 ColorsNormal)
455 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
455 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
456 (Colors.vName, Colors.valEm, ColorsNormal)
456 (Colors.vName, Colors.valEm, ColorsNormal)
457 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
457 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
458 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
458 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
459 Colors.vName, ColorsNormal)
459 Colors.vName, ColorsNormal)
460 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
460 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
461 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
461 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
462 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
462 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
463 ColorsNormal)
463 ColorsNormal)
464
464
465 # now, loop over all records printing context and info
465 # now, loop over all records printing context and info
466 abspath = os.path.abspath
466 abspath = os.path.abspath
467 for frame, file, lnum, func, lines, index in records:
467 for frame, file, lnum, func, lines, index in records:
468 #print '*** record:',file,lnum,func,lines,index # dbg
468 #print '*** record:',file,lnum,func,lines,index # dbg
469 try:
469 try:
470 file = file and abspath(file) or '?'
470 file = file and abspath(file) or '?'
471 except OSError:
471 except OSError:
472 # if file is '<console>' or something not in the filesystem,
472 # if file is '<console>' or something not in the filesystem,
473 # the abspath call will throw an OSError. Just ignore it and
473 # the abspath call will throw an OSError. Just ignore it and
474 # keep the original file string.
474 # keep the original file string.
475 pass
475 pass
476 link = tpl_link % file
476 link = tpl_link % file
477 try:
477 try:
478 args, varargs, varkw, locals = inspect.getargvalues(frame)
478 args, varargs, varkw, locals = inspect.getargvalues(frame)
479 except:
479 except:
480 # This can happen due to a bug in python2.3. We should be
480 # This can happen due to a bug in python2.3. We should be
481 # able to remove this try/except when 2.4 becomes a
481 # able to remove this try/except when 2.4 becomes a
482 # requirement. Bug details at http://python.org/sf/1005466
482 # requirement. Bug details at http://python.org/sf/1005466
483 inspect_error()
483 inspect_error()
484 traceback.print_exc(file=Term.cerr)
484 traceback.print_exc(file=Term.cerr)
485 info("\nIPython's exception reporting continues...\n")
485 info("\nIPython's exception reporting continues...\n")
486
486
487 if func == '?':
487 if func == '?':
488 call = ''
488 call = ''
489 else:
489 else:
490 # Decide whether to include variable details or not
490 # Decide whether to include variable details or not
491 var_repr = self.include_vars and eqrepr or nullrepr
491 var_repr = self.include_vars and eqrepr or nullrepr
492 try:
492 try:
493 call = tpl_call % (func,inspect.formatargvalues(args,
493 call = tpl_call % (func,inspect.formatargvalues(args,
494 varargs, varkw,
494 varargs, varkw,
495 locals,formatvalue=var_repr))
495 locals,formatvalue=var_repr))
496 except KeyError:
496 except KeyError:
497 # Very odd crash from inspect.formatargvalues(). The
497 # Very odd crash from inspect.formatargvalues(). The
498 # scenario under which it appeared was a call to
498 # scenario under which it appeared was a call to
499 # view(array,scale) in NumTut.view.view(), where scale had
499 # view(array,scale) in NumTut.view.view(), where scale had
500 # been defined as a scalar (it should be a tuple). Somehow
500 # been defined as a scalar (it should be a tuple). Somehow
501 # inspect messes up resolving the argument list of view()
501 # inspect messes up resolving the argument list of view()
502 # and barfs out. At some point I should dig into this one
502 # and barfs out. At some point I should dig into this one
503 # and file a bug report about it.
503 # and file a bug report about it.
504 inspect_error()
504 inspect_error()
505 traceback.print_exc(file=Term.cerr)
505 traceback.print_exc(file=Term.cerr)
506 info("\nIPython's exception reporting continues...\n")
506 info("\nIPython's exception reporting continues...\n")
507 call = tpl_call_fail % func
507 call = tpl_call_fail % func
508
508
509 # Initialize a list of names on the current line, which the
509 # Initialize a list of names on the current line, which the
510 # tokenizer below will populate.
510 # tokenizer below will populate.
511 names = []
511 names = []
512
512
513 def tokeneater(token_type, token, start, end, line):
513 def tokeneater(token_type, token, start, end, line):
514 """Stateful tokeneater which builds dotted names.
514 """Stateful tokeneater which builds dotted names.
515
515
516 The list of names it appends to (from the enclosing scope) can
516 The list of names it appends to (from the enclosing scope) can
517 contain repeated composite names. This is unavoidable, since
517 contain repeated composite names. This is unavoidable, since
518 there is no way to disambguate partial dotted structures until
518 there is no way to disambguate partial dotted structures until
519 the full list is known. The caller is responsible for pruning
519 the full list is known. The caller is responsible for pruning
520 the final list of duplicates before using it."""
520 the final list of duplicates before using it."""
521
521
522 # build composite names
522 # build composite names
523 if token == '.':
523 if token == '.':
524 try:
524 try:
525 names[-1] += '.'
525 names[-1] += '.'
526 # store state so the next token is added for x.y.z names
526 # store state so the next token is added for x.y.z names
527 tokeneater.name_cont = True
527 tokeneater.name_cont = True
528 return
528 return
529 except IndexError:
529 except IndexError:
530 pass
530 pass
531 if token_type == tokenize.NAME and token not in keyword.kwlist:
531 if token_type == tokenize.NAME and token not in keyword.kwlist:
532 if tokeneater.name_cont:
532 if tokeneater.name_cont:
533 # Dotted names
533 # Dotted names
534 names[-1] += token
534 names[-1] += token
535 tokeneater.name_cont = False
535 tokeneater.name_cont = False
536 else:
536 else:
537 # Regular new names. We append everything, the caller
537 # Regular new names. We append everything, the caller
538 # will be responsible for pruning the list later. It's
538 # will be responsible for pruning the list later. It's
539 # very tricky to try to prune as we go, b/c composite
539 # very tricky to try to prune as we go, b/c composite
540 # names can fool us. The pruning at the end is easy
540 # names can fool us. The pruning at the end is easy
541 # to do (or the caller can print a list with repeated
541 # to do (or the caller can print a list with repeated
542 # names if so desired.
542 # names if so desired.
543 names.append(token)
543 names.append(token)
544 elif token_type == tokenize.NEWLINE:
544 elif token_type == tokenize.NEWLINE:
545 raise IndexError
545 raise IndexError
546 # we need to store a bit of state in the tokenizer to build
546 # we need to store a bit of state in the tokenizer to build
547 # dotted names
547 # dotted names
548 tokeneater.name_cont = False
548 tokeneater.name_cont = False
549
549
550 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
550 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
551 line = getline(file, lnum[0])
551 line = getline(file, lnum[0])
552 lnum[0] += 1
552 lnum[0] += 1
553 return line
553 return line
554
554
555 # Build the list of names on this line of code where the exception
555 # Build the list of names on this line of code where the exception
556 # occurred.
556 # occurred.
557 try:
557 try:
558 # This builds the names list in-place by capturing it from the
558 # This builds the names list in-place by capturing it from the
559 # enclosing scope.
559 # enclosing scope.
560 tokenize.tokenize(linereader, tokeneater)
560 tokenize.tokenize(linereader, tokeneater)
561 except IndexError:
561 except IndexError:
562 # signals exit of tokenizer
562 # signals exit of tokenizer
563 pass
563 pass
564 except tokenize.TokenError,msg:
564 except tokenize.TokenError,msg:
565 _m = ("An unexpected error occurred while tokenizing input\n"
565 _m = ("An unexpected error occurred while tokenizing input\n"
566 "The following traceback may be corrupted or invalid\n"
566 "The following traceback may be corrupted or invalid\n"
567 "The error message is: %s\n" % msg)
567 "The error message is: %s\n" % msg)
568 error(_m)
568 error(_m)
569
569
570 # prune names list of duplicates, but keep the right order
570 # prune names list of duplicates, but keep the right order
571 unique_names = uniq_stable(names)
571 unique_names = uniq_stable(names)
572
572
573 # Start loop over vars
573 # Start loop over vars
574 lvals = []
574 lvals = []
575 if self.include_vars:
575 if self.include_vars:
576 for name_full in unique_names:
576 for name_full in unique_names:
577 name_base = name_full.split('.',1)[0]
577 name_base = name_full.split('.',1)[0]
578 if name_base in frame.f_code.co_varnames:
578 if name_base in frame.f_code.co_varnames:
579 if locals.has_key(name_base):
579 if locals.has_key(name_base):
580 try:
580 try:
581 value = repr(eval(name_full,locals))
581 value = repr(eval(name_full,locals))
582 except:
582 except:
583 value = undefined
583 value = undefined
584 else:
584 else:
585 value = undefined
585 value = undefined
586 name = tpl_local_var % name_full
586 name = tpl_local_var % name_full
587 else:
587 else:
588 if frame.f_globals.has_key(name_base):
588 if frame.f_globals.has_key(name_base):
589 try:
589 try:
590 value = repr(eval(name_full,frame.f_globals))
590 value = repr(eval(name_full,frame.f_globals))
591 except:
591 except:
592 value = undefined
592 value = undefined
593 else:
593 else:
594 value = undefined
594 value = undefined
595 name = tpl_global_var % name_full
595 name = tpl_global_var % name_full
596 lvals.append(tpl_name_val % (name,value))
596 lvals.append(tpl_name_val % (name,value))
597 if lvals:
597 if lvals:
598 lvals = '%s%s' % (indent,em_normal.join(lvals))
598 lvals = '%s%s' % (indent,em_normal.join(lvals))
599 else:
599 else:
600 lvals = ''
600 lvals = ''
601
601
602 level = '%s %s\n' % (link,call)
602 level = '%s %s\n' % (link,call)
603
603
604 if index is None:
604 if index is None:
605 frames.append(level)
605 frames.append(level)
606 else:
606 else:
607 frames.append('%s%s' % (level,''.join(
607 frames.append('%s%s' % (level,''.join(
608 _formatTracebackLines(lnum,index,lines,self.Colors,lvals))))
608 _formatTracebackLines(lnum,index,lines,self.Colors,lvals))))
609
609
610 # Get (safely) a string form of the exception info
610 # Get (safely) a string form of the exception info
611 try:
611 try:
612 etype_str,evalue_str = map(str,(etype,evalue))
612 etype_str,evalue_str = map(str,(etype,evalue))
613 except:
613 except:
614 # User exception is improperly defined.
614 # User exception is improperly defined.
615 etype,evalue = str,sys.exc_info()[:2]
615 etype,evalue = str,sys.exc_info()[:2]
616 etype_str,evalue_str = map(str,(etype,evalue))
616 etype_str,evalue_str = map(str,(etype,evalue))
617 # ... and format it
617 # ... and format it
618 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
618 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
619 ColorsNormal, evalue_str)]
619 ColorsNormal, evalue_str)]
620 if type(evalue) is types.InstanceType:
620 if type(evalue) is types.InstanceType:
621 try:
621 try:
622 names = [w for w in dir(evalue) if isinstance(w, basestring)]
622 names = [w for w in dir(evalue) if isinstance(w, basestring)]
623 except:
623 except:
624 # Every now and then, an object with funny inernals blows up
624 # Every now and then, an object with funny inernals blows up
625 # when dir() is called on it. We do the best we can to report
625 # when dir() is called on it. We do the best we can to report
626 # the problem and continue
626 # the problem and continue
627 _m = '%sException reporting error (object with broken dir())%s:'
627 _m = '%sException reporting error (object with broken dir())%s:'
628 exception.append(_m % (Colors.excName,ColorsNormal))
628 exception.append(_m % (Colors.excName,ColorsNormal))
629 etype_str,evalue_str = map(str,sys.exc_info()[:2])
629 etype_str,evalue_str = map(str,sys.exc_info()[:2])
630 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
630 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
631 ColorsNormal, evalue_str))
631 ColorsNormal, evalue_str))
632 names = []
632 names = []
633 for name in names:
633 for name in names:
634 value = text_repr(getattr(evalue, name))
634 value = text_repr(getattr(evalue, name))
635 exception.append('\n%s%s = %s' % (indent, name, value))
635 exception.append('\n%s%s = %s' % (indent, name, value))
636 # return all our info assembled as a single string
636 # return all our info assembled as a single string
637 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
637 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
638
638
639 def debugger(self):
639 def debugger(self):
640 """Call up the pdb debugger if desired, always clean up the tb reference.
640 """Call up the pdb debugger if desired, always clean up the tb reference.
641
641
642 If the call_pdb flag is set, the pdb interactive debugger is
642 If the call_pdb flag is set, the pdb interactive debugger is
643 invoked. In all cases, the self.tb reference to the current traceback
643 invoked. In all cases, the self.tb reference to the current traceback
644 is deleted to prevent lingering references which hamper memory
644 is deleted to prevent lingering references which hamper memory
645 management.
645 management.
646
646
647 Note that each call to pdb() does an 'import readline', so if your app
647 Note that each call to pdb() does an 'import readline', so if your app
648 requires a special setup for the readline completers, you'll have to
648 requires a special setup for the readline completers, you'll have to
649 fix that by hand after invoking the exception handler."""
649 fix that by hand after invoking the exception handler."""
650
650
651 if self.call_pdb:
651 if self.call_pdb:
652 if self.pdb is None:
652 if self.pdb is None:
653 self.pdb = Debugger.Pdb(
653 self.pdb = Debugger.Pdb(
654 self.color_scheme_table.active_scheme_name)
654 self.color_scheme_table.active_scheme_name)
655 # the system displayhook may have changed, restore the original
655 # the system displayhook may have changed, restore the original
656 # for pdb
656 # for pdb
657 dhook = sys.displayhook
657 dhook = sys.displayhook
658 sys.displayhook = sys.__displayhook__
658 sys.displayhook = sys.__displayhook__
659 self.pdb.reset()
659 self.pdb.reset()
660 # Find the right frame so we don't pop up inside ipython itself
660 # Find the right frame so we don't pop up inside ipython itself
661 etb = self.tb
661 etb = self.tb
662 while self.tb.tb_next is not None:
662 while self.tb.tb_next is not None:
663 self.tb = self.tb.tb_next
663 self.tb = self.tb.tb_next
664 try:
664 try:
665 if etb and etb.tb_next:
665 if etb and etb.tb_next:
666 etb = etb.tb_next
666 etb = etb.tb_next
667 self.pdb.botframe = etb.tb_frame
667 self.pdb.botframe = etb.tb_frame
668 self.pdb.interaction(self.tb.tb_frame, self.tb)
668 self.pdb.interaction(self.tb.tb_frame, self.tb)
669 except:
669 except:
670 print '*** ERROR ***'
670 print '*** ERROR ***'
671 print 'This version of pdb has a bug and crashed.'
671 print 'This version of pdb has a bug and crashed.'
672 print 'Returning to IPython...'
672 print 'Returning to IPython...'
673 sys.displayhook = dhook
673 sys.displayhook = dhook
674 del self.tb
674 del self.tb
675
675
676 def handler(self, info=None):
676 def handler(self, info=None):
677 (etype, evalue, etb) = info or sys.exc_info()
677 (etype, evalue, etb) = info or sys.exc_info()
678 self.tb = etb
678 self.tb = etb
679 print >> Term.cerr, self.text(etype, evalue, etb)
679 print >> Term.cerr, self.text(etype, evalue, etb)
680
680
681 # Changed so an instance can just be called as VerboseTB_inst() and print
681 # Changed so an instance can just be called as VerboseTB_inst() and print
682 # out the right info on its own.
682 # out the right info on its own.
683 def __call__(self, etype=None, evalue=None, etb=None):
683 def __call__(self, etype=None, evalue=None, etb=None):
684 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
684 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
685 if etb is None:
685 if etb is None:
686 self.handler()
686 self.handler()
687 else:
687 else:
688 self.handler((etype, evalue, etb))
688 self.handler((etype, evalue, etb))
689 self.debugger()
689 self.debugger()
690
690
691 #----------------------------------------------------------------------------
691 #----------------------------------------------------------------------------
692 class FormattedTB(VerboseTB,ListTB):
692 class FormattedTB(VerboseTB,ListTB):
693 """Subclass ListTB but allow calling with a traceback.
693 """Subclass ListTB but allow calling with a traceback.
694
694
695 It can thus be used as a sys.excepthook for Python > 2.1.
695 It can thus be used as a sys.excepthook for Python > 2.1.
696
696
697 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
697 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
698
698
699 Allows a tb_offset to be specified. This is useful for situations where
699 Allows a tb_offset to be specified. This is useful for situations where
700 one needs to remove a number of topmost frames from the traceback (such as
700 one needs to remove a number of topmost frames from the traceback (such as
701 occurs with python programs that themselves execute other python code,
701 occurs with python programs that themselves execute other python code,
702 like Python shells). """
702 like Python shells). """
703
703
704 def __init__(self, mode = 'Plain', color_scheme='Linux',
704 def __init__(self, mode = 'Plain', color_scheme='Linux',
705 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
705 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
706
706
707 # NEVER change the order of this list. Put new modes at the end:
707 # NEVER change the order of this list. Put new modes at the end:
708 self.valid_modes = ['Plain','Context','Verbose']
708 self.valid_modes = ['Plain','Context','Verbose']
709 self.verbose_modes = self.valid_modes[1:3]
709 self.verbose_modes = self.valid_modes[1:3]
710
710
711 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
711 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
712 call_pdb=call_pdb,include_vars=include_vars)
712 call_pdb=call_pdb,include_vars=include_vars)
713 self.set_mode(mode)
713 self.set_mode(mode)
714
714
715 def _extract_tb(self,tb):
715 def _extract_tb(self,tb):
716 if tb:
716 if tb:
717 return traceback.extract_tb(tb)
717 return traceback.extract_tb(tb)
718 else:
718 else:
719 return None
719 return None
720
720
721 def text(self, etype, value, tb,context=5,mode=None):
721 def text(self, etype, value, tb,context=5,mode=None):
722 """Return formatted traceback.
722 """Return formatted traceback.
723
723
724 If the optional mode parameter is given, it overrides the current
724 If the optional mode parameter is given, it overrides the current
725 mode."""
725 mode."""
726
726
727 if mode is None:
727 if mode is None:
728 mode = self.mode
728 mode = self.mode
729 if mode in self.verbose_modes:
729 if mode in self.verbose_modes:
730 # verbose modes need a full traceback
730 # verbose modes need a full traceback
731 return VerboseTB.text(self,etype, value, tb,context=5)
731 return VerboseTB.text(self,etype, value, tb,context=5)
732 else:
732 else:
733 # We must check the source cache because otherwise we can print
733 # We must check the source cache because otherwise we can print
734 # out-of-date source code.
734 # out-of-date source code.
735 linecache.checkcache()
735 linecache.checkcache()
736 # Now we can extract and format the exception
736 # Now we can extract and format the exception
737 elist = self._extract_tb(tb)
737 elist = self._extract_tb(tb)
738 if len(elist) > self.tb_offset:
738 if len(elist) > self.tb_offset:
739 del elist[:self.tb_offset]
739 del elist[:self.tb_offset]
740 return ListTB.text(self,etype,value,elist)
740 return ListTB.text(self,etype,value,elist)
741
741
742 def set_mode(self,mode=None):
742 def set_mode(self,mode=None):
743 """Switch to the desired mode.
743 """Switch to the desired mode.
744
744
745 If mode is not specified, cycles through the available modes."""
745 If mode is not specified, cycles through the available modes."""
746
746
747 if not mode:
747 if not mode:
748 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
748 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
749 len(self.valid_modes)
749 len(self.valid_modes)
750 self.mode = self.valid_modes[new_idx]
750 self.mode = self.valid_modes[new_idx]
751 elif mode not in self.valid_modes:
751 elif mode not in self.valid_modes:
752 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
752 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
753 'Valid modes: '+str(self.valid_modes)
753 'Valid modes: '+str(self.valid_modes)
754 else:
754 else:
755 self.mode = mode
755 self.mode = mode
756 # include variable details only in 'Verbose' mode
756 # include variable details only in 'Verbose' mode
757 self.include_vars = (self.mode == self.valid_modes[2])
757 self.include_vars = (self.mode == self.valid_modes[2])
758
758
759 # some convenient shorcuts
759 # some convenient shorcuts
760 def plain(self):
760 def plain(self):
761 self.set_mode(self.valid_modes[0])
761 self.set_mode(self.valid_modes[0])
762
762
763 def context(self):
763 def context(self):
764 self.set_mode(self.valid_modes[1])
764 self.set_mode(self.valid_modes[1])
765
765
766 def verbose(self):
766 def verbose(self):
767 self.set_mode(self.valid_modes[2])
767 self.set_mode(self.valid_modes[2])
768
768
769 #----------------------------------------------------------------------------
769 #----------------------------------------------------------------------------
770 class AutoFormattedTB(FormattedTB):
770 class AutoFormattedTB(FormattedTB):
771 """A traceback printer which can be called on the fly.
771 """A traceback printer which can be called on the fly.
772
772
773 It will find out about exceptions by itself.
773 It will find out about exceptions by itself.
774
774
775 A brief example:
775 A brief example:
776
776
777 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
777 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
778 try:
778 try:
779 ...
779 ...
780 except:
780 except:
781 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
781 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
782 """
782 """
783 def __call__(self,etype=None,evalue=None,etb=None,
783 def __call__(self,etype=None,evalue=None,etb=None,
784 out=None,tb_offset=None):
784 out=None,tb_offset=None):
785 """Print out a formatted exception traceback.
785 """Print out a formatted exception traceback.
786
786
787 Optional arguments:
787 Optional arguments:
788 - out: an open file-like object to direct output to.
788 - out: an open file-like object to direct output to.
789
789
790 - tb_offset: the number of frames to skip over in the stack, on a
790 - tb_offset: the number of frames to skip over in the stack, on a
791 per-call basis (this overrides temporarily the instance's tb_offset
791 per-call basis (this overrides temporarily the instance's tb_offset
792 given at initialization time. """
792 given at initialization time. """
793
793
794 if out is None:
794 if out is None:
795 out = Term.cerr
795 out = Term.cerr
796 if tb_offset is not None:
796 if tb_offset is not None:
797 tb_offset, self.tb_offset = self.tb_offset, tb_offset
797 tb_offset, self.tb_offset = self.tb_offset, tb_offset
798 print >> out, self.text(etype, evalue, etb)
798 print >> out, self.text(etype, evalue, etb)
799 self.tb_offset = tb_offset
799 self.tb_offset = tb_offset
800 else:
800 else:
801 print >> out, self.text(etype, evalue, etb)
801 print >> out, self.text(etype, evalue, etb)
802 self.debugger()
802 self.debugger()
803
803
804 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
804 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
805 if etype is None:
805 if etype is None:
806 etype,value,tb = sys.exc_info()
806 etype,value,tb = sys.exc_info()
807 self.tb = tb
807 self.tb = tb
808 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
808 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
809
809
810 #---------------------------------------------------------------------------
810 #---------------------------------------------------------------------------
811 # A simple class to preserve Nathan's original functionality.
811 # A simple class to preserve Nathan's original functionality.
812 class ColorTB(FormattedTB):
812 class ColorTB(FormattedTB):
813 """Shorthand to initialize a FormattedTB in Linux colors mode."""
813 """Shorthand to initialize a FormattedTB in Linux colors mode."""
814 def __init__(self,color_scheme='Linux',call_pdb=0):
814 def __init__(self,color_scheme='Linux',call_pdb=0):
815 FormattedTB.__init__(self,color_scheme=color_scheme,
815 FormattedTB.__init__(self,color_scheme=color_scheme,
816 call_pdb=call_pdb)
816 call_pdb=call_pdb)
817
817
818 #----------------------------------------------------------------------------
818 #----------------------------------------------------------------------------
819 # module testing (minimal)
819 # module testing (minimal)
820 if __name__ == "__main__":
820 if __name__ == "__main__":
821 def spam(c, (d, e)):
821 def spam(c, (d, e)):
822 x = c + d
822 x = c + d
823 y = c * d
823 y = c * d
824 foo(x, y)
824 foo(x, y)
825
825
826 def foo(a, b, bar=1):
826 def foo(a, b, bar=1):
827 eggs(a, b + bar)
827 eggs(a, b + bar)
828
828
829 def eggs(f, g, z=globals()):
829 def eggs(f, g, z=globals()):
830 h = f + g
830 h = f + g
831 i = f - g
831 i = f - g
832 return h / i
832 return h / i
833
833
834 print ''
834 print ''
835 print '*** Before ***'
835 print '*** Before ***'
836 try:
836 try:
837 print spam(1, (2, 3))
837 print spam(1, (2, 3))
838 except:
838 except:
839 traceback.print_exc()
839 traceback.print_exc()
840 print ''
840 print ''
841
841
842 handler = ColorTB()
842 handler = ColorTB()
843 print '*** ColorTB ***'
843 print '*** ColorTB ***'
844 try:
844 try:
845 print spam(1, (2, 3))
845 print spam(1, (2, 3))
846 except:
846 except:
847 apply(handler, sys.exc_info() )
847 apply(handler, sys.exc_info() )
848 print ''
848 print ''
849
849
850 handler = VerboseTB()
850 handler = VerboseTB()
851 print '*** VerboseTB ***'
851 print '*** VerboseTB ***'
852 try:
852 try:
853 print spam(1, (2, 3))
853 print spam(1, (2, 3))
854 except:
854 except:
855 apply(handler, sys.exc_info() )
855 apply(handler, sys.exc_info() )
856 print ''
856 print ''
857
857
@@ -1,4822 +1,4833 b''
1 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
4 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
5 module in case-insensitive installation. Was causing crashes
6 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
7
8 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
9 <marienz-AT-gentoo.org>, closes
10 http://www.scipy.net/roundup/ipython/issue51.
11
1 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
12 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
2
13
3 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the the
14 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the the
4 problem of excessive CPU usage under *nix and keyboard lag under
15 problem of excessive CPU usage under *nix and keyboard lag under
5 win32.
16 win32.
6
17
7 2006-01-10 *** Released version 0.7.0
18 2006-01-10 *** Released version 0.7.0
8
19
9 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
20 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
10
21
11 * IPython/Release.py (revision): tag version number to 0.7.0,
22 * IPython/Release.py (revision): tag version number to 0.7.0,
12 ready for release.
23 ready for release.
13
24
14 * IPython/Magic.py (magic_edit): Add print statement to %edit so
25 * IPython/Magic.py (magic_edit): Add print statement to %edit so
15 it informs the user of the name of the temp. file used. This can
26 it informs the user of the name of the temp. file used. This can
16 help if you decide later to reuse that same file, so you know
27 help if you decide later to reuse that same file, so you know
17 where to copy the info from.
28 where to copy the info from.
18
29
19 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
30 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
20
31
21 * setup_bdist_egg.py: little script to build an egg. Added
32 * setup_bdist_egg.py: little script to build an egg. Added
22 support in the release tools as well.
33 support in the release tools as well.
23
34
24 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
35 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
25
36
26 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
37 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
27 version selection (new -wxversion command line and ipythonrc
38 version selection (new -wxversion command line and ipythonrc
28 parameter). Patch contributed by Arnd Baecker
39 parameter). Patch contributed by Arnd Baecker
29 <arnd.baecker-AT-web.de>.
40 <arnd.baecker-AT-web.de>.
30
41
31 * IPython/iplib.py (embed_mainloop): fix tab-completion in
42 * IPython/iplib.py (embed_mainloop): fix tab-completion in
32 embedded instances, for variables defined at the interactive
43 embedded instances, for variables defined at the interactive
33 prompt of the embedded ipython. Reported by Arnd.
44 prompt of the embedded ipython. Reported by Arnd.
34
45
35 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
46 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
36 it can be used as a (stateful) toggle, or with a direct parameter.
47 it can be used as a (stateful) toggle, or with a direct parameter.
37
48
38 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
49 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
39 could be triggered in certain cases and cause the traceback
50 could be triggered in certain cases and cause the traceback
40 printer not to work.
51 printer not to work.
41
52
42 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
53 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
43
54
44 * IPython/iplib.py (_should_recompile): Small fix, closes
55 * IPython/iplib.py (_should_recompile): Small fix, closes
45 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
56 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
46
57
47 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
58 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
48
59
49 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
60 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
50 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
61 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
51 Moad for help with tracking it down.
62 Moad for help with tracking it down.
52
63
53 * IPython/iplib.py (handle_auto): fix autocall handling for
64 * IPython/iplib.py (handle_auto): fix autocall handling for
54 objects which support BOTH __getitem__ and __call__ (so that f [x]
65 objects which support BOTH __getitem__ and __call__ (so that f [x]
55 is left alone, instead of becoming f([x]) automatically).
66 is left alone, instead of becoming f([x]) automatically).
56
67
57 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
68 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
58 Ville's patch.
69 Ville's patch.
59
70
60 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
71 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
61
72
62 * IPython/iplib.py (handle_auto): changed autocall semantics to
73 * IPython/iplib.py (handle_auto): changed autocall semantics to
63 include 'smart' mode, where the autocall transformation is NOT
74 include 'smart' mode, where the autocall transformation is NOT
64 applied if there are no arguments on the line. This allows you to
75 applied if there are no arguments on the line. This allows you to
65 just type 'foo' if foo is a callable to see its internal form,
76 just type 'foo' if foo is a callable to see its internal form,
66 instead of having it called with no arguments (typically a
77 instead of having it called with no arguments (typically a
67 mistake). The old 'full' autocall still exists: for that, you
78 mistake). The old 'full' autocall still exists: for that, you
68 need to set the 'autocall' parameter to 2 in your ipythonrc file.
79 need to set the 'autocall' parameter to 2 in your ipythonrc file.
69
80
70 * IPython/completer.py (Completer.attr_matches): add
81 * IPython/completer.py (Completer.attr_matches): add
71 tab-completion support for Enthoughts' traits. After a report by
82 tab-completion support for Enthoughts' traits. After a report by
72 Arnd and a patch by Prabhu.
83 Arnd and a patch by Prabhu.
73
84
74 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
85 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
75
86
76 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
87 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
77 Schmolck's patch to fix inspect.getinnerframes().
88 Schmolck's patch to fix inspect.getinnerframes().
78
89
79 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
90 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
80 for embedded instances, regarding handling of namespaces and items
91 for embedded instances, regarding handling of namespaces and items
81 added to the __builtin__ one. Multiple embedded instances and
92 added to the __builtin__ one. Multiple embedded instances and
82 recursive embeddings should work better now (though I'm not sure
93 recursive embeddings should work better now (though I'm not sure
83 I've got all the corner cases fixed, that code is a bit of a brain
94 I've got all the corner cases fixed, that code is a bit of a brain
84 twister).
95 twister).
85
96
86 * IPython/Magic.py (magic_edit): added support to edit in-memory
97 * IPython/Magic.py (magic_edit): added support to edit in-memory
87 macros (automatically creates the necessary temp files). %edit
98 macros (automatically creates the necessary temp files). %edit
88 also doesn't return the file contents anymore, it's just noise.
99 also doesn't return the file contents anymore, it's just noise.
89
100
90 * IPython/completer.py (Completer.attr_matches): revert change to
101 * IPython/completer.py (Completer.attr_matches): revert change to
91 complete only on attributes listed in __all__. I realized it
102 complete only on attributes listed in __all__. I realized it
92 cripples the tab-completion system as a tool for exploring the
103 cripples the tab-completion system as a tool for exploring the
93 internals of unknown libraries (it renders any non-__all__
104 internals of unknown libraries (it renders any non-__all__
94 attribute off-limits). I got bit by this when trying to see
105 attribute off-limits). I got bit by this when trying to see
95 something inside the dis module.
106 something inside the dis module.
96
107
97 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
108 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
98
109
99 * IPython/iplib.py (InteractiveShell.__init__): add .meta
110 * IPython/iplib.py (InteractiveShell.__init__): add .meta
100 namespace for users and extension writers to hold data in. This
111 namespace for users and extension writers to hold data in. This
101 follows the discussion in
112 follows the discussion in
102 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
113 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
103
114
104 * IPython/completer.py (IPCompleter.complete): small patch to help
115 * IPython/completer.py (IPCompleter.complete): small patch to help
105 tab-completion under Emacs, after a suggestion by John Barnard
116 tab-completion under Emacs, after a suggestion by John Barnard
106 <barnarj-AT-ccf.org>.
117 <barnarj-AT-ccf.org>.
107
118
108 * IPython/Magic.py (Magic.extract_input_slices): added support for
119 * IPython/Magic.py (Magic.extract_input_slices): added support for
109 the slice notation in magics to use N-M to represent numbers N...M
120 the slice notation in magics to use N-M to represent numbers N...M
110 (closed endpoints). This is used by %macro and %save.
121 (closed endpoints). This is used by %macro and %save.
111
122
112 * IPython/completer.py (Completer.attr_matches): for modules which
123 * IPython/completer.py (Completer.attr_matches): for modules which
113 define __all__, complete only on those. After a patch by Jeffrey
124 define __all__, complete only on those. After a patch by Jeffrey
114 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
125 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
115 speed up this routine.
126 speed up this routine.
116
127
117 * IPython/Logger.py (Logger.log): fix a history handling bug. I
128 * IPython/Logger.py (Logger.log): fix a history handling bug. I
118 don't know if this is the end of it, but the behavior now is
129 don't know if this is the end of it, but the behavior now is
119 certainly much more correct. Note that coupled with macros,
130 certainly much more correct. Note that coupled with macros,
120 slightly surprising (at first) behavior may occur: a macro will in
131 slightly surprising (at first) behavior may occur: a macro will in
121 general expand to multiple lines of input, so upon exiting, the
132 general expand to multiple lines of input, so upon exiting, the
122 in/out counters will both be bumped by the corresponding amount
133 in/out counters will both be bumped by the corresponding amount
123 (as if the macro's contents had been typed interactively). Typing
134 (as if the macro's contents had been typed interactively). Typing
124 %hist will reveal the intermediate (silently processed) lines.
135 %hist will reveal the intermediate (silently processed) lines.
125
136
126 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
137 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
127 pickle to fail (%run was overwriting __main__ and not restoring
138 pickle to fail (%run was overwriting __main__ and not restoring
128 it, but pickle relies on __main__ to operate).
139 it, but pickle relies on __main__ to operate).
129
140
130 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
141 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
131 using properties, but forgot to make the main InteractiveShell
142 using properties, but forgot to make the main InteractiveShell
132 class a new-style class. Properties fail silently, and
143 class a new-style class. Properties fail silently, and
133 misteriously, with old-style class (getters work, but
144 misteriously, with old-style class (getters work, but
134 setters don't do anything).
145 setters don't do anything).
135
146
136 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
147 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
137
148
138 * IPython/Magic.py (magic_history): fix history reporting bug (I
149 * IPython/Magic.py (magic_history): fix history reporting bug (I
139 know some nasties are still there, I just can't seem to find a
150 know some nasties are still there, I just can't seem to find a
140 reproducible test case to track them down; the input history is
151 reproducible test case to track them down; the input history is
141 falling out of sync...)
152 falling out of sync...)
142
153
143 * IPython/iplib.py (handle_shell_escape): fix bug where both
154 * IPython/iplib.py (handle_shell_escape): fix bug where both
144 aliases and system accesses where broken for indented code (such
155 aliases and system accesses where broken for indented code (such
145 as loops).
156 as loops).
146
157
147 * IPython/genutils.py (shell): fix small but critical bug for
158 * IPython/genutils.py (shell): fix small but critical bug for
148 win32 system access.
159 win32 system access.
149
160
150 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
161 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
151
162
152 * IPython/iplib.py (showtraceback): remove use of the
163 * IPython/iplib.py (showtraceback): remove use of the
153 sys.last_{type/value/traceback} structures, which are non
164 sys.last_{type/value/traceback} structures, which are non
154 thread-safe.
165 thread-safe.
155 (_prefilter): change control flow to ensure that we NEVER
166 (_prefilter): change control flow to ensure that we NEVER
156 introspect objects when autocall is off. This will guarantee that
167 introspect objects when autocall is off. This will guarantee that
157 having an input line of the form 'x.y', where access to attribute
168 having an input line of the form 'x.y', where access to attribute
158 'y' has side effects, doesn't trigger the side effect TWICE. It
169 'y' has side effects, doesn't trigger the side effect TWICE. It
159 is important to note that, with autocall on, these side effects
170 is important to note that, with autocall on, these side effects
160 can still happen.
171 can still happen.
161 (ipsystem): new builtin, to complete the ip{magic/alias/system}
172 (ipsystem): new builtin, to complete the ip{magic/alias/system}
162 trio. IPython offers these three kinds of special calls which are
173 trio. IPython offers these three kinds of special calls which are
163 not python code, and it's a good thing to have their call method
174 not python code, and it's a good thing to have their call method
164 be accessible as pure python functions (not just special syntax at
175 be accessible as pure python functions (not just special syntax at
165 the command line). It gives us a better internal implementation
176 the command line). It gives us a better internal implementation
166 structure, as well as exposing these for user scripting more
177 structure, as well as exposing these for user scripting more
167 cleanly.
178 cleanly.
168
179
169 * IPython/macro.py (Macro.__init__): moved macros to a standalone
180 * IPython/macro.py (Macro.__init__): moved macros to a standalone
170 file. Now that they'll be more likely to be used with the
181 file. Now that they'll be more likely to be used with the
171 persistance system (%store), I want to make sure their module path
182 persistance system (%store), I want to make sure their module path
172 doesn't change in the future, so that we don't break things for
183 doesn't change in the future, so that we don't break things for
173 users' persisted data.
184 users' persisted data.
174
185
175 * IPython/iplib.py (autoindent_update): move indentation
186 * IPython/iplib.py (autoindent_update): move indentation
176 management into the _text_ processing loop, not the keyboard
187 management into the _text_ processing loop, not the keyboard
177 interactive one. This is necessary to correctly process non-typed
188 interactive one. This is necessary to correctly process non-typed
178 multiline input (such as macros).
189 multiline input (such as macros).
179
190
180 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
191 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
181 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
192 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
182 which was producing problems in the resulting manual.
193 which was producing problems in the resulting manual.
183 (magic_whos): improve reporting of instances (show their class,
194 (magic_whos): improve reporting of instances (show their class,
184 instead of simply printing 'instance' which isn't terribly
195 instead of simply printing 'instance' which isn't terribly
185 informative).
196 informative).
186
197
187 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
198 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
188 (minor mods) to support network shares under win32.
199 (minor mods) to support network shares under win32.
189
200
190 * IPython/winconsole.py (get_console_size): add new winconsole
201 * IPython/winconsole.py (get_console_size): add new winconsole
191 module and fixes to page_dumb() to improve its behavior under
202 module and fixes to page_dumb() to improve its behavior under
192 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
203 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
193
204
194 * IPython/Magic.py (Macro): simplified Macro class to just
205 * IPython/Magic.py (Macro): simplified Macro class to just
195 subclass list. We've had only 2.2 compatibility for a very long
206 subclass list. We've had only 2.2 compatibility for a very long
196 time, yet I was still avoiding subclassing the builtin types. No
207 time, yet I was still avoiding subclassing the builtin types. No
197 more (I'm also starting to use properties, though I won't shift to
208 more (I'm also starting to use properties, though I won't shift to
198 2.3-specific features quite yet).
209 2.3-specific features quite yet).
199 (magic_store): added Ville's patch for lightweight variable
210 (magic_store): added Ville's patch for lightweight variable
200 persistence, after a request on the user list by Matt Wilkie
211 persistence, after a request on the user list by Matt Wilkie
201 <maphew-AT-gmail.com>. The new %store magic's docstring has full
212 <maphew-AT-gmail.com>. The new %store magic's docstring has full
202 details.
213 details.
203
214
204 * IPython/iplib.py (InteractiveShell.post_config_initialization):
215 * IPython/iplib.py (InteractiveShell.post_config_initialization):
205 changed the default logfile name from 'ipython.log' to
216 changed the default logfile name from 'ipython.log' to
206 'ipython_log.py'. These logs are real python files, and now that
217 'ipython_log.py'. These logs are real python files, and now that
207 we have much better multiline support, people are more likely to
218 we have much better multiline support, people are more likely to
208 want to use them as such. Might as well name them correctly.
219 want to use them as such. Might as well name them correctly.
209
220
210 * IPython/Magic.py: substantial cleanup. While we can't stop
221 * IPython/Magic.py: substantial cleanup. While we can't stop
211 using magics as mixins, due to the existing customizations 'out
222 using magics as mixins, due to the existing customizations 'out
212 there' which rely on the mixin naming conventions, at least I
223 there' which rely on the mixin naming conventions, at least I
213 cleaned out all cross-class name usage. So once we are OK with
224 cleaned out all cross-class name usage. So once we are OK with
214 breaking compatibility, the two systems can be separated.
225 breaking compatibility, the two systems can be separated.
215
226
216 * IPython/Logger.py: major cleanup. This one is NOT a mixin
227 * IPython/Logger.py: major cleanup. This one is NOT a mixin
217 anymore, and the class is a fair bit less hideous as well. New
228 anymore, and the class is a fair bit less hideous as well. New
218 features were also introduced: timestamping of input, and logging
229 features were also introduced: timestamping of input, and logging
219 of output results. These are user-visible with the -t and -o
230 of output results. These are user-visible with the -t and -o
220 options to %logstart. Closes
231 options to %logstart. Closes
221 http://www.scipy.net/roundup/ipython/issue11 and a request by
232 http://www.scipy.net/roundup/ipython/issue11 and a request by
222 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
233 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
223
234
224 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
235 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
225
236
226 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
237 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
227 better hadnle backslashes in paths. See the thread 'More Windows
238 better hadnle backslashes in paths. See the thread 'More Windows
228 questions part 2 - \/ characters revisited' on the iypthon user
239 questions part 2 - \/ characters revisited' on the iypthon user
229 list:
240 list:
230 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
241 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
231
242
232 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
243 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
233
244
234 (InteractiveShell.__init__): change threaded shells to not use the
245 (InteractiveShell.__init__): change threaded shells to not use the
235 ipython crash handler. This was causing more problems than not,
246 ipython crash handler. This was causing more problems than not,
236 as exceptions in the main thread (GUI code, typically) would
247 as exceptions in the main thread (GUI code, typically) would
237 always show up as a 'crash', when they really weren't.
248 always show up as a 'crash', when they really weren't.
238
249
239 The colors and exception mode commands (%colors/%xmode) have been
250 The colors and exception mode commands (%colors/%xmode) have been
240 synchronized to also take this into account, so users can get
251 synchronized to also take this into account, so users can get
241 verbose exceptions for their threaded code as well. I also added
252 verbose exceptions for their threaded code as well. I also added
242 support for activating pdb inside this exception handler as well,
253 support for activating pdb inside this exception handler as well,
243 so now GUI authors can use IPython's enhanced pdb at runtime.
254 so now GUI authors can use IPython's enhanced pdb at runtime.
244
255
245 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
256 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
246 true by default, and add it to the shipped ipythonrc file. Since
257 true by default, and add it to the shipped ipythonrc file. Since
247 this asks the user before proceeding, I think it's OK to make it
258 this asks the user before proceeding, I think it's OK to make it
248 true by default.
259 true by default.
249
260
250 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
261 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
251 of the previous special-casing of input in the eval loop. I think
262 of the previous special-casing of input in the eval loop. I think
252 this is cleaner, as they really are commands and shouldn't have
263 this is cleaner, as they really are commands and shouldn't have
253 a special role in the middle of the core code.
264 a special role in the middle of the core code.
254
265
255 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
266 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
256
267
257 * IPython/iplib.py (edit_syntax_error): added support for
268 * IPython/iplib.py (edit_syntax_error): added support for
258 automatically reopening the editor if the file had a syntax error
269 automatically reopening the editor if the file had a syntax error
259 in it. Thanks to scottt who provided the patch at:
270 in it. Thanks to scottt who provided the patch at:
260 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
271 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
261 version committed).
272 version committed).
262
273
263 * IPython/iplib.py (handle_normal): add suport for multi-line
274 * IPython/iplib.py (handle_normal): add suport for multi-line
264 input with emtpy lines. This fixes
275 input with emtpy lines. This fixes
265 http://www.scipy.net/roundup/ipython/issue43 and a similar
276 http://www.scipy.net/roundup/ipython/issue43 and a similar
266 discussion on the user list.
277 discussion on the user list.
267
278
268 WARNING: a behavior change is necessarily introduced to support
279 WARNING: a behavior change is necessarily introduced to support
269 blank lines: now a single blank line with whitespace does NOT
280 blank lines: now a single blank line with whitespace does NOT
270 break the input loop, which means that when autoindent is on, by
281 break the input loop, which means that when autoindent is on, by
271 default hitting return on the next (indented) line does NOT exit.
282 default hitting return on the next (indented) line does NOT exit.
272
283
273 Instead, to exit a multiline input you can either have:
284 Instead, to exit a multiline input you can either have:
274
285
275 - TWO whitespace lines (just hit return again), or
286 - TWO whitespace lines (just hit return again), or
276 - a single whitespace line of a different length than provided
287 - a single whitespace line of a different length than provided
277 by the autoindent (add or remove a space).
288 by the autoindent (add or remove a space).
278
289
279 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
290 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
280 module to better organize all readline-related functionality.
291 module to better organize all readline-related functionality.
281 I've deleted FlexCompleter and put all completion clases here.
292 I've deleted FlexCompleter and put all completion clases here.
282
293
283 * IPython/iplib.py (raw_input): improve indentation management.
294 * IPython/iplib.py (raw_input): improve indentation management.
284 It is now possible to paste indented code with autoindent on, and
295 It is now possible to paste indented code with autoindent on, and
285 the code is interpreted correctly (though it still looks bad on
296 the code is interpreted correctly (though it still looks bad on
286 screen, due to the line-oriented nature of ipython).
297 screen, due to the line-oriented nature of ipython).
287 (MagicCompleter.complete): change behavior so that a TAB key on an
298 (MagicCompleter.complete): change behavior so that a TAB key on an
288 otherwise empty line actually inserts a tab, instead of completing
299 otherwise empty line actually inserts a tab, instead of completing
289 on the entire global namespace. This makes it easier to use the
300 on the entire global namespace. This makes it easier to use the
290 TAB key for indentation. After a request by Hans Meine
301 TAB key for indentation. After a request by Hans Meine
291 <hans_meine-AT-gmx.net>
302 <hans_meine-AT-gmx.net>
292 (_prefilter): add support so that typing plain 'exit' or 'quit'
303 (_prefilter): add support so that typing plain 'exit' or 'quit'
293 does a sensible thing. Originally I tried to deviate as little as
304 does a sensible thing. Originally I tried to deviate as little as
294 possible from the default python behavior, but even that one may
305 possible from the default python behavior, but even that one may
295 change in this direction (thread on python-dev to that effect).
306 change in this direction (thread on python-dev to that effect).
296 Regardless, ipython should do the right thing even if CPython's
307 Regardless, ipython should do the right thing even if CPython's
297 '>>>' prompt doesn't.
308 '>>>' prompt doesn't.
298 (InteractiveShell): removed subclassing code.InteractiveConsole
309 (InteractiveShell): removed subclassing code.InteractiveConsole
299 class. By now we'd overridden just about all of its methods: I've
310 class. By now we'd overridden just about all of its methods: I've
300 copied the remaining two over, and now ipython is a standalone
311 copied the remaining two over, and now ipython is a standalone
301 class. This will provide a clearer picture for the chainsaw
312 class. This will provide a clearer picture for the chainsaw
302 branch refactoring.
313 branch refactoring.
303
314
304 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
315 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
305
316
306 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
317 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
307 failures for objects which break when dir() is called on them.
318 failures for objects which break when dir() is called on them.
308
319
309 * IPython/FlexCompleter.py (Completer.__init__): Added support for
320 * IPython/FlexCompleter.py (Completer.__init__): Added support for
310 distinct local and global namespaces in the completer API. This
321 distinct local and global namespaces in the completer API. This
311 change allows us top properly handle completion with distinct
322 change allows us top properly handle completion with distinct
312 scopes, including in embedded instances (this had never really
323 scopes, including in embedded instances (this had never really
313 worked correctly).
324 worked correctly).
314
325
315 Note: this introduces a change in the constructor for
326 Note: this introduces a change in the constructor for
316 MagicCompleter, as a new global_namespace parameter is now the
327 MagicCompleter, as a new global_namespace parameter is now the
317 second argument (the others were bumped one position).
328 second argument (the others were bumped one position).
318
329
319 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
330 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
320
331
321 * IPython/iplib.py (embed_mainloop): fix tab-completion in
332 * IPython/iplib.py (embed_mainloop): fix tab-completion in
322 embedded instances (which can be done now thanks to Vivian's
333 embedded instances (which can be done now thanks to Vivian's
323 frame-handling fixes for pdb).
334 frame-handling fixes for pdb).
324 (InteractiveShell.__init__): Fix namespace handling problem in
335 (InteractiveShell.__init__): Fix namespace handling problem in
325 embedded instances. We were overwriting __main__ unconditionally,
336 embedded instances. We were overwriting __main__ unconditionally,
326 and this should only be done for 'full' (non-embedded) IPython;
337 and this should only be done for 'full' (non-embedded) IPython;
327 embedded instances must respect the caller's __main__. Thanks to
338 embedded instances must respect the caller's __main__. Thanks to
328 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
339 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
329
340
330 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
341 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
331
342
332 * setup.py: added download_url to setup(). This registers the
343 * setup.py: added download_url to setup(). This registers the
333 download address at PyPI, which is not only useful to humans
344 download address at PyPI, which is not only useful to humans
334 browsing the site, but is also picked up by setuptools (the Eggs
345 browsing the site, but is also picked up by setuptools (the Eggs
335 machinery). Thanks to Ville and R. Kern for the info/discussion
346 machinery). Thanks to Ville and R. Kern for the info/discussion
336 on this.
347 on this.
337
348
338 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
349 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
339
350
340 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
351 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
341 This brings a lot of nice functionality to the pdb mode, which now
352 This brings a lot of nice functionality to the pdb mode, which now
342 has tab-completion, syntax highlighting, and better stack handling
353 has tab-completion, syntax highlighting, and better stack handling
343 than before. Many thanks to Vivian De Smedt
354 than before. Many thanks to Vivian De Smedt
344 <vivian-AT-vdesmedt.com> for the original patches.
355 <vivian-AT-vdesmedt.com> for the original patches.
345
356
346 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
357 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
347
358
348 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
359 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
349 sequence to consistently accept the banner argument. The
360 sequence to consistently accept the banner argument. The
350 inconsistency was tripping SAGE, thanks to Gary Zablackis
361 inconsistency was tripping SAGE, thanks to Gary Zablackis
351 <gzabl-AT-yahoo.com> for the report.
362 <gzabl-AT-yahoo.com> for the report.
352
363
353 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
364 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
354
365
355 * IPython/iplib.py (InteractiveShell.post_config_initialization):
366 * IPython/iplib.py (InteractiveShell.post_config_initialization):
356 Fix bug where a naked 'alias' call in the ipythonrc file would
367 Fix bug where a naked 'alias' call in the ipythonrc file would
357 cause a crash. Bug reported by Jorgen Stenarson.
368 cause a crash. Bug reported by Jorgen Stenarson.
358
369
359 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
370 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
360
371
361 * IPython/ipmaker.py (make_IPython): cleanups which should improve
372 * IPython/ipmaker.py (make_IPython): cleanups which should improve
362 startup time.
373 startup time.
363
374
364 * IPython/iplib.py (runcode): my globals 'fix' for embedded
375 * IPython/iplib.py (runcode): my globals 'fix' for embedded
365 instances had introduced a bug with globals in normal code. Now
376 instances had introduced a bug with globals in normal code. Now
366 it's working in all cases.
377 it's working in all cases.
367
378
368 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
379 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
369 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
380 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
370 has been introduced to set the default case sensitivity of the
381 has been introduced to set the default case sensitivity of the
371 searches. Users can still select either mode at runtime on a
382 searches. Users can still select either mode at runtime on a
372 per-search basis.
383 per-search basis.
373
384
374 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
385 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
375
386
376 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
387 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
377 attributes in wildcard searches for subclasses. Modified version
388 attributes in wildcard searches for subclasses. Modified version
378 of a patch by Jorgen.
389 of a patch by Jorgen.
379
390
380 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
391 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
381
392
382 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
393 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
383 embedded instances. I added a user_global_ns attribute to the
394 embedded instances. I added a user_global_ns attribute to the
384 InteractiveShell class to handle this.
395 InteractiveShell class to handle this.
385
396
386 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
397 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
387
398
388 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
399 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
389 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
400 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
390 (reported under win32, but may happen also in other platforms).
401 (reported under win32, but may happen also in other platforms).
391 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
402 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
392
403
393 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
404 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
394
405
395 * IPython/Magic.py (magic_psearch): new support for wildcard
406 * IPython/Magic.py (magic_psearch): new support for wildcard
396 patterns. Now, typing ?a*b will list all names which begin with a
407 patterns. Now, typing ?a*b will list all names which begin with a
397 and end in b, for example. The %psearch magic has full
408 and end in b, for example. The %psearch magic has full
398 docstrings. Many thanks to JΓΆrgen Stenarson
409 docstrings. Many thanks to JΓΆrgen Stenarson
399 <jorgen.stenarson-AT-bostream.nu>, author of the patches
410 <jorgen.stenarson-AT-bostream.nu>, author of the patches
400 implementing this functionality.
411 implementing this functionality.
401
412
402 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
413 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
403
414
404 * Manual: fixed long-standing annoyance of double-dashes (as in
415 * Manual: fixed long-standing annoyance of double-dashes (as in
405 --prefix=~, for example) being stripped in the HTML version. This
416 --prefix=~, for example) being stripped in the HTML version. This
406 is a latex2html bug, but a workaround was provided. Many thanks
417 is a latex2html bug, but a workaround was provided. Many thanks
407 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
418 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
408 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
419 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
409 rolling. This seemingly small issue had tripped a number of users
420 rolling. This seemingly small issue had tripped a number of users
410 when first installing, so I'm glad to see it gone.
421 when first installing, so I'm glad to see it gone.
411
422
412 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
423 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
413
424
414 * IPython/Extensions/numeric_formats.py: fix missing import,
425 * IPython/Extensions/numeric_formats.py: fix missing import,
415 reported by Stephen Walton.
426 reported by Stephen Walton.
416
427
417 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
428 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
418
429
419 * IPython/demo.py: finish demo module, fully documented now.
430 * IPython/demo.py: finish demo module, fully documented now.
420
431
421 * IPython/genutils.py (file_read): simple little utility to read a
432 * IPython/genutils.py (file_read): simple little utility to read a
422 file and ensure it's closed afterwards.
433 file and ensure it's closed afterwards.
423
434
424 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
435 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
425
436
426 * IPython/demo.py (Demo.__init__): added support for individually
437 * IPython/demo.py (Demo.__init__): added support for individually
427 tagging blocks for automatic execution.
438 tagging blocks for automatic execution.
428
439
429 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
440 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
430 syntax-highlighted python sources, requested by John.
441 syntax-highlighted python sources, requested by John.
431
442
432 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
443 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
433
444
434 * IPython/demo.py (Demo.again): fix bug where again() blocks after
445 * IPython/demo.py (Demo.again): fix bug where again() blocks after
435 finishing.
446 finishing.
436
447
437 * IPython/genutils.py (shlex_split): moved from Magic to here,
448 * IPython/genutils.py (shlex_split): moved from Magic to here,
438 where all 2.2 compatibility stuff lives. I needed it for demo.py.
449 where all 2.2 compatibility stuff lives. I needed it for demo.py.
439
450
440 * IPython/demo.py (Demo.__init__): added support for silent
451 * IPython/demo.py (Demo.__init__): added support for silent
441 blocks, improved marks as regexps, docstrings written.
452 blocks, improved marks as regexps, docstrings written.
442 (Demo.__init__): better docstring, added support for sys.argv.
453 (Demo.__init__): better docstring, added support for sys.argv.
443
454
444 * IPython/genutils.py (marquee): little utility used by the demo
455 * IPython/genutils.py (marquee): little utility used by the demo
445 code, handy in general.
456 code, handy in general.
446
457
447 * IPython/demo.py (Demo.__init__): new class for interactive
458 * IPython/demo.py (Demo.__init__): new class for interactive
448 demos. Not documented yet, I just wrote it in a hurry for
459 demos. Not documented yet, I just wrote it in a hurry for
449 scipy'05. Will docstring later.
460 scipy'05. Will docstring later.
450
461
451 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
462 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
452
463
453 * IPython/Shell.py (sigint_handler): Drastic simplification which
464 * IPython/Shell.py (sigint_handler): Drastic simplification which
454 also seems to make Ctrl-C work correctly across threads! This is
465 also seems to make Ctrl-C work correctly across threads! This is
455 so simple, that I can't beleive I'd missed it before. Needs more
466 so simple, that I can't beleive I'd missed it before. Needs more
456 testing, though.
467 testing, though.
457 (KBINT): Never mind, revert changes. I'm sure I'd tried something
468 (KBINT): Never mind, revert changes. I'm sure I'd tried something
458 like this before...
469 like this before...
459
470
460 * IPython/genutils.py (get_home_dir): add protection against
471 * IPython/genutils.py (get_home_dir): add protection against
461 non-dirs in win32 registry.
472 non-dirs in win32 registry.
462
473
463 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
474 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
464 bug where dict was mutated while iterating (pysh crash).
475 bug where dict was mutated while iterating (pysh crash).
465
476
466 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
477 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
467
478
468 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
479 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
469 spurious newlines added by this routine. After a report by
480 spurious newlines added by this routine. After a report by
470 F. Mantegazza.
481 F. Mantegazza.
471
482
472 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
483 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
473
484
474 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
485 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
475 calls. These were a leftover from the GTK 1.x days, and can cause
486 calls. These were a leftover from the GTK 1.x days, and can cause
476 problems in certain cases (after a report by John Hunter).
487 problems in certain cases (after a report by John Hunter).
477
488
478 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
489 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
479 os.getcwd() fails at init time. Thanks to patch from David Remahl
490 os.getcwd() fails at init time. Thanks to patch from David Remahl
480 <chmod007-AT-mac.com>.
491 <chmod007-AT-mac.com>.
481 (InteractiveShell.__init__): prevent certain special magics from
492 (InteractiveShell.__init__): prevent certain special magics from
482 being shadowed by aliases. Closes
493 being shadowed by aliases. Closes
483 http://www.scipy.net/roundup/ipython/issue41.
494 http://www.scipy.net/roundup/ipython/issue41.
484
495
485 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
496 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
486
497
487 * IPython/iplib.py (InteractiveShell.complete): Added new
498 * IPython/iplib.py (InteractiveShell.complete): Added new
488 top-level completion method to expose the completion mechanism
499 top-level completion method to expose the completion mechanism
489 beyond readline-based environments.
500 beyond readline-based environments.
490
501
491 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
502 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
492
503
493 * tools/ipsvnc (svnversion): fix svnversion capture.
504 * tools/ipsvnc (svnversion): fix svnversion capture.
494
505
495 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
506 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
496 attribute to self, which was missing. Before, it was set by a
507 attribute to self, which was missing. Before, it was set by a
497 routine which in certain cases wasn't being called, so the
508 routine which in certain cases wasn't being called, so the
498 instance could end up missing the attribute. This caused a crash.
509 instance could end up missing the attribute. This caused a crash.
499 Closes http://www.scipy.net/roundup/ipython/issue40.
510 Closes http://www.scipy.net/roundup/ipython/issue40.
500
511
501 2005-08-16 Fernando Perez <fperez@colorado.edu>
512 2005-08-16 Fernando Perez <fperez@colorado.edu>
502
513
503 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
514 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
504 contains non-string attribute. Closes
515 contains non-string attribute. Closes
505 http://www.scipy.net/roundup/ipython/issue38.
516 http://www.scipy.net/roundup/ipython/issue38.
506
517
507 2005-08-14 Fernando Perez <fperez@colorado.edu>
518 2005-08-14 Fernando Perez <fperez@colorado.edu>
508
519
509 * tools/ipsvnc: Minor improvements, to add changeset info.
520 * tools/ipsvnc: Minor improvements, to add changeset info.
510
521
511 2005-08-12 Fernando Perez <fperez@colorado.edu>
522 2005-08-12 Fernando Perez <fperez@colorado.edu>
512
523
513 * IPython/iplib.py (runsource): remove self.code_to_run_src
524 * IPython/iplib.py (runsource): remove self.code_to_run_src
514 attribute. I realized this is nothing more than
525 attribute. I realized this is nothing more than
515 '\n'.join(self.buffer), and having the same data in two different
526 '\n'.join(self.buffer), and having the same data in two different
516 places is just asking for synchronization bugs. This may impact
527 places is just asking for synchronization bugs. This may impact
517 people who have custom exception handlers, so I need to warn
528 people who have custom exception handlers, so I need to warn
518 ipython-dev about it (F. Mantegazza may use them).
529 ipython-dev about it (F. Mantegazza may use them).
519
530
520 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
531 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
521
532
522 * IPython/genutils.py: fix 2.2 compatibility (generators)
533 * IPython/genutils.py: fix 2.2 compatibility (generators)
523
534
524 2005-07-18 Fernando Perez <fperez@colorado.edu>
535 2005-07-18 Fernando Perez <fperez@colorado.edu>
525
536
526 * IPython/genutils.py (get_home_dir): fix to help users with
537 * IPython/genutils.py (get_home_dir): fix to help users with
527 invalid $HOME under win32.
538 invalid $HOME under win32.
528
539
529 2005-07-17 Fernando Perez <fperez@colorado.edu>
540 2005-07-17 Fernando Perez <fperez@colorado.edu>
530
541
531 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
542 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
532 some old hacks and clean up a bit other routines; code should be
543 some old hacks and clean up a bit other routines; code should be
533 simpler and a bit faster.
544 simpler and a bit faster.
534
545
535 * IPython/iplib.py (interact): removed some last-resort attempts
546 * IPython/iplib.py (interact): removed some last-resort attempts
536 to survive broken stdout/stderr. That code was only making it
547 to survive broken stdout/stderr. That code was only making it
537 harder to abstract out the i/o (necessary for gui integration),
548 harder to abstract out the i/o (necessary for gui integration),
538 and the crashes it could prevent were extremely rare in practice
549 and the crashes it could prevent were extremely rare in practice
539 (besides being fully user-induced in a pretty violent manner).
550 (besides being fully user-induced in a pretty violent manner).
540
551
541 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
552 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
542 Nothing major yet, but the code is simpler to read; this should
553 Nothing major yet, but the code is simpler to read; this should
543 make it easier to do more serious modifications in the future.
554 make it easier to do more serious modifications in the future.
544
555
545 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
556 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
546 which broke in .15 (thanks to a report by Ville).
557 which broke in .15 (thanks to a report by Ville).
547
558
548 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
559 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
549 be quite correct, I know next to nothing about unicode). This
560 be quite correct, I know next to nothing about unicode). This
550 will allow unicode strings to be used in prompts, amongst other
561 will allow unicode strings to be used in prompts, amongst other
551 cases. It also will prevent ipython from crashing when unicode
562 cases. It also will prevent ipython from crashing when unicode
552 shows up unexpectedly in many places. If ascii encoding fails, we
563 shows up unexpectedly in many places. If ascii encoding fails, we
553 assume utf_8. Currently the encoding is not a user-visible
564 assume utf_8. Currently the encoding is not a user-visible
554 setting, though it could be made so if there is demand for it.
565 setting, though it could be made so if there is demand for it.
555
566
556 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
567 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
557
568
558 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
569 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
559
570
560 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
571 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
561
572
562 * IPython/genutils.py: Add 2.2 compatibility here, so all other
573 * IPython/genutils.py: Add 2.2 compatibility here, so all other
563 code can work transparently for 2.2/2.3.
574 code can work transparently for 2.2/2.3.
564
575
565 2005-07-16 Fernando Perez <fperez@colorado.edu>
576 2005-07-16 Fernando Perez <fperez@colorado.edu>
566
577
567 * IPython/ultraTB.py (ExceptionColors): Make a global variable
578 * IPython/ultraTB.py (ExceptionColors): Make a global variable
568 out of the color scheme table used for coloring exception
579 out of the color scheme table used for coloring exception
569 tracebacks. This allows user code to add new schemes at runtime.
580 tracebacks. This allows user code to add new schemes at runtime.
570 This is a minimally modified version of the patch at
581 This is a minimally modified version of the patch at
571 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
582 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
572 for the contribution.
583 for the contribution.
573
584
574 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
585 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
575 slightly modified version of the patch in
586 slightly modified version of the patch in
576 http://www.scipy.net/roundup/ipython/issue34, which also allows me
587 http://www.scipy.net/roundup/ipython/issue34, which also allows me
577 to remove the previous try/except solution (which was costlier).
588 to remove the previous try/except solution (which was costlier).
578 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
589 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
579
590
580 2005-06-08 Fernando Perez <fperez@colorado.edu>
591 2005-06-08 Fernando Perez <fperez@colorado.edu>
581
592
582 * IPython/iplib.py (write/write_err): Add methods to abstract all
593 * IPython/iplib.py (write/write_err): Add methods to abstract all
583 I/O a bit more.
594 I/O a bit more.
584
595
585 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
596 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
586 warning, reported by Aric Hagberg, fix by JD Hunter.
597 warning, reported by Aric Hagberg, fix by JD Hunter.
587
598
588 2005-06-02 *** Released version 0.6.15
599 2005-06-02 *** Released version 0.6.15
589
600
590 2005-06-01 Fernando Perez <fperez@colorado.edu>
601 2005-06-01 Fernando Perez <fperez@colorado.edu>
591
602
592 * IPython/iplib.py (MagicCompleter.file_matches): Fix
603 * IPython/iplib.py (MagicCompleter.file_matches): Fix
593 tab-completion of filenames within open-quoted strings. Note that
604 tab-completion of filenames within open-quoted strings. Note that
594 this requires that in ~/.ipython/ipythonrc, users change the
605 this requires that in ~/.ipython/ipythonrc, users change the
595 readline delimiters configuration to read:
606 readline delimiters configuration to read:
596
607
597 readline_remove_delims -/~
608 readline_remove_delims -/~
598
609
599
610
600 2005-05-31 *** Released version 0.6.14
611 2005-05-31 *** Released version 0.6.14
601
612
602 2005-05-29 Fernando Perez <fperez@colorado.edu>
613 2005-05-29 Fernando Perez <fperez@colorado.edu>
603
614
604 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
615 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
605 with files not on the filesystem. Reported by Eliyahu Sandler
616 with files not on the filesystem. Reported by Eliyahu Sandler
606 <eli@gondolin.net>
617 <eli@gondolin.net>
607
618
608 2005-05-22 Fernando Perez <fperez@colorado.edu>
619 2005-05-22 Fernando Perez <fperez@colorado.edu>
609
620
610 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
621 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
611 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
622 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
612
623
613 2005-05-19 Fernando Perez <fperez@colorado.edu>
624 2005-05-19 Fernando Perez <fperez@colorado.edu>
614
625
615 * IPython/iplib.py (safe_execfile): close a file which could be
626 * IPython/iplib.py (safe_execfile): close a file which could be
616 left open (causing problems in win32, which locks open files).
627 left open (causing problems in win32, which locks open files).
617 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
628 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
618
629
619 2005-05-18 Fernando Perez <fperez@colorado.edu>
630 2005-05-18 Fernando Perez <fperez@colorado.edu>
620
631
621 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
632 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
622 keyword arguments correctly to safe_execfile().
633 keyword arguments correctly to safe_execfile().
623
634
624 2005-05-13 Fernando Perez <fperez@colorado.edu>
635 2005-05-13 Fernando Perez <fperez@colorado.edu>
625
636
626 * ipython.1: Added info about Qt to manpage, and threads warning
637 * ipython.1: Added info about Qt to manpage, and threads warning
627 to usage page (invoked with --help).
638 to usage page (invoked with --help).
628
639
629 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
640 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
630 new matcher (it goes at the end of the priority list) to do
641 new matcher (it goes at the end of the priority list) to do
631 tab-completion on named function arguments. Submitted by George
642 tab-completion on named function arguments. Submitted by George
632 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
643 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
633 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
644 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
634 for more details.
645 for more details.
635
646
636 * IPython/Magic.py (magic_run): Added new -e flag to ignore
647 * IPython/Magic.py (magic_run): Added new -e flag to ignore
637 SystemExit exceptions in the script being run. Thanks to a report
648 SystemExit exceptions in the script being run. Thanks to a report
638 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
649 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
639 producing very annoying behavior when running unit tests.
650 producing very annoying behavior when running unit tests.
640
651
641 2005-05-12 Fernando Perez <fperez@colorado.edu>
652 2005-05-12 Fernando Perez <fperez@colorado.edu>
642
653
643 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
654 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
644 which I'd broken (again) due to a changed regexp. In the process,
655 which I'd broken (again) due to a changed regexp. In the process,
645 added ';' as an escape to auto-quote the whole line without
656 added ';' as an escape to auto-quote the whole line without
646 splitting its arguments. Thanks to a report by Jerry McRae
657 splitting its arguments. Thanks to a report by Jerry McRae
647 <qrs0xyc02-AT-sneakemail.com>.
658 <qrs0xyc02-AT-sneakemail.com>.
648
659
649 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
660 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
650 possible crashes caused by a TokenError. Reported by Ed Schofield
661 possible crashes caused by a TokenError. Reported by Ed Schofield
651 <schofield-AT-ftw.at>.
662 <schofield-AT-ftw.at>.
652
663
653 2005-05-06 Fernando Perez <fperez@colorado.edu>
664 2005-05-06 Fernando Perez <fperez@colorado.edu>
654
665
655 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
666 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
656
667
657 2005-04-29 Fernando Perez <fperez@colorado.edu>
668 2005-04-29 Fernando Perez <fperez@colorado.edu>
658
669
659 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
670 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
660 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
671 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
661 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
672 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
662 which provides support for Qt interactive usage (similar to the
673 which provides support for Qt interactive usage (similar to the
663 existing one for WX and GTK). This had been often requested.
674 existing one for WX and GTK). This had been often requested.
664
675
665 2005-04-14 *** Released version 0.6.13
676 2005-04-14 *** Released version 0.6.13
666
677
667 2005-04-08 Fernando Perez <fperez@colorado.edu>
678 2005-04-08 Fernando Perez <fperez@colorado.edu>
668
679
669 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
680 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
670 from _ofind, which gets called on almost every input line. Now,
681 from _ofind, which gets called on almost every input line. Now,
671 we only try to get docstrings if they are actually going to be
682 we only try to get docstrings if they are actually going to be
672 used (the overhead of fetching unnecessary docstrings can be
683 used (the overhead of fetching unnecessary docstrings can be
673 noticeable for certain objects, such as Pyro proxies).
684 noticeable for certain objects, such as Pyro proxies).
674
685
675 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
686 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
676 for completers. For some reason I had been passing them the state
687 for completers. For some reason I had been passing them the state
677 variable, which completers never actually need, and was in
688 variable, which completers never actually need, and was in
678 conflict with the rlcompleter API. Custom completers ONLY need to
689 conflict with the rlcompleter API. Custom completers ONLY need to
679 take the text parameter.
690 take the text parameter.
680
691
681 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
692 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
682 work correctly in pysh. I've also moved all the logic which used
693 work correctly in pysh. I've also moved all the logic which used
683 to be in pysh.py here, which will prevent problems with future
694 to be in pysh.py here, which will prevent problems with future
684 upgrades. However, this time I must warn users to update their
695 upgrades. However, this time I must warn users to update their
685 pysh profile to include the line
696 pysh profile to include the line
686
697
687 import_all IPython.Extensions.InterpreterExec
698 import_all IPython.Extensions.InterpreterExec
688
699
689 because otherwise things won't work for them. They MUST also
700 because otherwise things won't work for them. They MUST also
690 delete pysh.py and the line
701 delete pysh.py and the line
691
702
692 execfile pysh.py
703 execfile pysh.py
693
704
694 from their ipythonrc-pysh.
705 from their ipythonrc-pysh.
695
706
696 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
707 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
697 robust in the face of objects whose dir() returns non-strings
708 robust in the face of objects whose dir() returns non-strings
698 (which it shouldn't, but some broken libs like ITK do). Thanks to
709 (which it shouldn't, but some broken libs like ITK do). Thanks to
699 a patch by John Hunter (implemented differently, though). Also
710 a patch by John Hunter (implemented differently, though). Also
700 minor improvements by using .extend instead of + on lists.
711 minor improvements by using .extend instead of + on lists.
701
712
702 * pysh.py:
713 * pysh.py:
703
714
704 2005-04-06 Fernando Perez <fperez@colorado.edu>
715 2005-04-06 Fernando Perez <fperez@colorado.edu>
705
716
706 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
717 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
707 by default, so that all users benefit from it. Those who don't
718 by default, so that all users benefit from it. Those who don't
708 want it can still turn it off.
719 want it can still turn it off.
709
720
710 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
721 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
711 config file, I'd forgotten about this, so users were getting it
722 config file, I'd forgotten about this, so users were getting it
712 off by default.
723 off by default.
713
724
714 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
725 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
715 consistency. Now magics can be called in multiline statements,
726 consistency. Now magics can be called in multiline statements,
716 and python variables can be expanded in magic calls via $var.
727 and python variables can be expanded in magic calls via $var.
717 This makes the magic system behave just like aliases or !system
728 This makes the magic system behave just like aliases or !system
718 calls.
729 calls.
719
730
720 2005-03-28 Fernando Perez <fperez@colorado.edu>
731 2005-03-28 Fernando Perez <fperez@colorado.edu>
721
732
722 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
733 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
723 expensive string additions for building command. Add support for
734 expensive string additions for building command. Add support for
724 trailing ';' when autocall is used.
735 trailing ';' when autocall is used.
725
736
726 2005-03-26 Fernando Perez <fperez@colorado.edu>
737 2005-03-26 Fernando Perez <fperez@colorado.edu>
727
738
728 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
739 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
729 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
740 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
730 ipython.el robust against prompts with any number of spaces
741 ipython.el robust against prompts with any number of spaces
731 (including 0) after the ':' character.
742 (including 0) after the ':' character.
732
743
733 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
744 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
734 continuation prompt, which misled users to think the line was
745 continuation prompt, which misled users to think the line was
735 already indented. Closes debian Bug#300847, reported to me by
746 already indented. Closes debian Bug#300847, reported to me by
736 Norbert Tretkowski <tretkowski-AT-inittab.de>.
747 Norbert Tretkowski <tretkowski-AT-inittab.de>.
737
748
738 2005-03-23 Fernando Perez <fperez@colorado.edu>
749 2005-03-23 Fernando Perez <fperez@colorado.edu>
739
750
740 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
751 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
741 properly aligned if they have embedded newlines.
752 properly aligned if they have embedded newlines.
742
753
743 * IPython/iplib.py (runlines): Add a public method to expose
754 * IPython/iplib.py (runlines): Add a public method to expose
744 IPython's code execution machinery, so that users can run strings
755 IPython's code execution machinery, so that users can run strings
745 as if they had been typed at the prompt interactively.
756 as if they had been typed at the prompt interactively.
746 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
757 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
747 methods which can call the system shell, but with python variable
758 methods which can call the system shell, but with python variable
748 expansion. The three such methods are: __IPYTHON__.system,
759 expansion. The three such methods are: __IPYTHON__.system,
749 .getoutput and .getoutputerror. These need to be documented in a
760 .getoutput and .getoutputerror. These need to be documented in a
750 'public API' section (to be written) of the manual.
761 'public API' section (to be written) of the manual.
751
762
752 2005-03-20 Fernando Perez <fperez@colorado.edu>
763 2005-03-20 Fernando Perez <fperez@colorado.edu>
753
764
754 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
765 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
755 for custom exception handling. This is quite powerful, and it
766 for custom exception handling. This is quite powerful, and it
756 allows for user-installable exception handlers which can trap
767 allows for user-installable exception handlers which can trap
757 custom exceptions at runtime and treat them separately from
768 custom exceptions at runtime and treat them separately from
758 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
769 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
759 Mantegazza <mantegazza-AT-ill.fr>.
770 Mantegazza <mantegazza-AT-ill.fr>.
760 (InteractiveShell.set_custom_completer): public API function to
771 (InteractiveShell.set_custom_completer): public API function to
761 add new completers at runtime.
772 add new completers at runtime.
762
773
763 2005-03-19 Fernando Perez <fperez@colorado.edu>
774 2005-03-19 Fernando Perez <fperez@colorado.edu>
764
775
765 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
776 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
766 allow objects which provide their docstrings via non-standard
777 allow objects which provide their docstrings via non-standard
767 mechanisms (like Pyro proxies) to still be inspected by ipython's
778 mechanisms (like Pyro proxies) to still be inspected by ipython's
768 ? system.
779 ? system.
769
780
770 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
781 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
771 automatic capture system. I tried quite hard to make it work
782 automatic capture system. I tried quite hard to make it work
772 reliably, and simply failed. I tried many combinations with the
783 reliably, and simply failed. I tried many combinations with the
773 subprocess module, but eventually nothing worked in all needed
784 subprocess module, but eventually nothing worked in all needed
774 cases (not blocking stdin for the child, duplicating stdout
785 cases (not blocking stdin for the child, duplicating stdout
775 without blocking, etc). The new %sc/%sx still do capture to these
786 without blocking, etc). The new %sc/%sx still do capture to these
776 magical list/string objects which make shell use much more
787 magical list/string objects which make shell use much more
777 conveninent, so not all is lost.
788 conveninent, so not all is lost.
778
789
779 XXX - FIX MANUAL for the change above!
790 XXX - FIX MANUAL for the change above!
780
791
781 (runsource): I copied code.py's runsource() into ipython to modify
792 (runsource): I copied code.py's runsource() into ipython to modify
782 it a bit. Now the code object and source to be executed are
793 it a bit. Now the code object and source to be executed are
783 stored in ipython. This makes this info accessible to third-party
794 stored in ipython. This makes this info accessible to third-party
784 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
795 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
785 Mantegazza <mantegazza-AT-ill.fr>.
796 Mantegazza <mantegazza-AT-ill.fr>.
786
797
787 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
798 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
788 history-search via readline (like C-p/C-n). I'd wanted this for a
799 history-search via readline (like C-p/C-n). I'd wanted this for a
789 long time, but only recently found out how to do it. For users
800 long time, but only recently found out how to do it. For users
790 who already have their ipythonrc files made and want this, just
801 who already have their ipythonrc files made and want this, just
791 add:
802 add:
792
803
793 readline_parse_and_bind "\e[A": history-search-backward
804 readline_parse_and_bind "\e[A": history-search-backward
794 readline_parse_and_bind "\e[B": history-search-forward
805 readline_parse_and_bind "\e[B": history-search-forward
795
806
796 2005-03-18 Fernando Perez <fperez@colorado.edu>
807 2005-03-18 Fernando Perez <fperez@colorado.edu>
797
808
798 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
809 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
799 LSString and SList classes which allow transparent conversions
810 LSString and SList classes which allow transparent conversions
800 between list mode and whitespace-separated string.
811 between list mode and whitespace-separated string.
801 (magic_r): Fix recursion problem in %r.
812 (magic_r): Fix recursion problem in %r.
802
813
803 * IPython/genutils.py (LSString): New class to be used for
814 * IPython/genutils.py (LSString): New class to be used for
804 automatic storage of the results of all alias/system calls in _o
815 automatic storage of the results of all alias/system calls in _o
805 and _e (stdout/err). These provide a .l/.list attribute which
816 and _e (stdout/err). These provide a .l/.list attribute which
806 does automatic splitting on newlines. This means that for most
817 does automatic splitting on newlines. This means that for most
807 uses, you'll never need to do capturing of output with %sc/%sx
818 uses, you'll never need to do capturing of output with %sc/%sx
808 anymore, since ipython keeps this always done for you. Note that
819 anymore, since ipython keeps this always done for you. Note that
809 only the LAST results are stored, the _o/e variables are
820 only the LAST results are stored, the _o/e variables are
810 overwritten on each call. If you need to save their contents
821 overwritten on each call. If you need to save their contents
811 further, simply bind them to any other name.
822 further, simply bind them to any other name.
812
823
813 2005-03-17 Fernando Perez <fperez@colorado.edu>
824 2005-03-17 Fernando Perez <fperez@colorado.edu>
814
825
815 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
826 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
816 prompt namespace handling.
827 prompt namespace handling.
817
828
818 2005-03-16 Fernando Perez <fperez@colorado.edu>
829 2005-03-16 Fernando Perez <fperez@colorado.edu>
819
830
820 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
831 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
821 classic prompts to be '>>> ' (final space was missing, and it
832 classic prompts to be '>>> ' (final space was missing, and it
822 trips the emacs python mode).
833 trips the emacs python mode).
823 (BasePrompt.__str__): Added safe support for dynamic prompt
834 (BasePrompt.__str__): Added safe support for dynamic prompt
824 strings. Now you can set your prompt string to be '$x', and the
835 strings. Now you can set your prompt string to be '$x', and the
825 value of x will be printed from your interactive namespace. The
836 value of x will be printed from your interactive namespace. The
826 interpolation syntax includes the full Itpl support, so
837 interpolation syntax includes the full Itpl support, so
827 ${foo()+x+bar()} is a valid prompt string now, and the function
838 ${foo()+x+bar()} is a valid prompt string now, and the function
828 calls will be made at runtime.
839 calls will be made at runtime.
829
840
830 2005-03-15 Fernando Perez <fperez@colorado.edu>
841 2005-03-15 Fernando Perez <fperez@colorado.edu>
831
842
832 * IPython/Magic.py (magic_history): renamed %hist to %history, to
843 * IPython/Magic.py (magic_history): renamed %hist to %history, to
833 avoid name clashes in pylab. %hist still works, it just forwards
844 avoid name clashes in pylab. %hist still works, it just forwards
834 the call to %history.
845 the call to %history.
835
846
836 2005-03-02 *** Released version 0.6.12
847 2005-03-02 *** Released version 0.6.12
837
848
838 2005-03-02 Fernando Perez <fperez@colorado.edu>
849 2005-03-02 Fernando Perez <fperez@colorado.edu>
839
850
840 * IPython/iplib.py (handle_magic): log magic calls properly as
851 * IPython/iplib.py (handle_magic): log magic calls properly as
841 ipmagic() function calls.
852 ipmagic() function calls.
842
853
843 * IPython/Magic.py (magic_time): Improved %time to support
854 * IPython/Magic.py (magic_time): Improved %time to support
844 statements and provide wall-clock as well as CPU time.
855 statements and provide wall-clock as well as CPU time.
845
856
846 2005-02-27 Fernando Perez <fperez@colorado.edu>
857 2005-02-27 Fernando Perez <fperez@colorado.edu>
847
858
848 * IPython/hooks.py: New hooks module, to expose user-modifiable
859 * IPython/hooks.py: New hooks module, to expose user-modifiable
849 IPython functionality in a clean manner. For now only the editor
860 IPython functionality in a clean manner. For now only the editor
850 hook is actually written, and other thigns which I intend to turn
861 hook is actually written, and other thigns which I intend to turn
851 into proper hooks aren't yet there. The display and prefilter
862 into proper hooks aren't yet there. The display and prefilter
852 stuff, for example, should be hooks. But at least now the
863 stuff, for example, should be hooks. But at least now the
853 framework is in place, and the rest can be moved here with more
864 framework is in place, and the rest can be moved here with more
854 time later. IPython had had a .hooks variable for a long time for
865 time later. IPython had had a .hooks variable for a long time for
855 this purpose, but I'd never actually used it for anything.
866 this purpose, but I'd never actually used it for anything.
856
867
857 2005-02-26 Fernando Perez <fperez@colorado.edu>
868 2005-02-26 Fernando Perez <fperez@colorado.edu>
858
869
859 * IPython/ipmaker.py (make_IPython): make the default ipython
870 * IPython/ipmaker.py (make_IPython): make the default ipython
860 directory be called _ipython under win32, to follow more the
871 directory be called _ipython under win32, to follow more the
861 naming peculiarities of that platform (where buggy software like
872 naming peculiarities of that platform (where buggy software like
862 Visual Sourcesafe breaks with .named directories). Reported by
873 Visual Sourcesafe breaks with .named directories). Reported by
863 Ville Vainio.
874 Ville Vainio.
864
875
865 2005-02-23 Fernando Perez <fperez@colorado.edu>
876 2005-02-23 Fernando Perez <fperez@colorado.edu>
866
877
867 * IPython/iplib.py (InteractiveShell.__init__): removed a few
878 * IPython/iplib.py (InteractiveShell.__init__): removed a few
868 auto_aliases for win32 which were causing problems. Users can
879 auto_aliases for win32 which were causing problems. Users can
869 define the ones they personally like.
880 define the ones they personally like.
870
881
871 2005-02-21 Fernando Perez <fperez@colorado.edu>
882 2005-02-21 Fernando Perez <fperez@colorado.edu>
872
883
873 * IPython/Magic.py (magic_time): new magic to time execution of
884 * IPython/Magic.py (magic_time): new magic to time execution of
874 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
885 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
875
886
876 2005-02-19 Fernando Perez <fperez@colorado.edu>
887 2005-02-19 Fernando Perez <fperez@colorado.edu>
877
888
878 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
889 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
879 into keys (for prompts, for example).
890 into keys (for prompts, for example).
880
891
881 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
892 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
882 prompts in case users want them. This introduces a small behavior
893 prompts in case users want them. This introduces a small behavior
883 change: ipython does not automatically add a space to all prompts
894 change: ipython does not automatically add a space to all prompts
884 anymore. To get the old prompts with a space, users should add it
895 anymore. To get the old prompts with a space, users should add it
885 manually to their ipythonrc file, so for example prompt_in1 should
896 manually to their ipythonrc file, so for example prompt_in1 should
886 now read 'In [\#]: ' instead of 'In [\#]:'.
897 now read 'In [\#]: ' instead of 'In [\#]:'.
887 (BasePrompt.__init__): New option prompts_pad_left (only in rc
898 (BasePrompt.__init__): New option prompts_pad_left (only in rc
888 file) to control left-padding of secondary prompts.
899 file) to control left-padding of secondary prompts.
889
900
890 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
901 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
891 the profiler can't be imported. Fix for Debian, which removed
902 the profiler can't be imported. Fix for Debian, which removed
892 profile.py because of License issues. I applied a slightly
903 profile.py because of License issues. I applied a slightly
893 modified version of the original Debian patch at
904 modified version of the original Debian patch at
894 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
905 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
895
906
896 2005-02-17 Fernando Perez <fperez@colorado.edu>
907 2005-02-17 Fernando Perez <fperez@colorado.edu>
897
908
898 * IPython/genutils.py (native_line_ends): Fix bug which would
909 * IPython/genutils.py (native_line_ends): Fix bug which would
899 cause improper line-ends under win32 b/c I was not opening files
910 cause improper line-ends under win32 b/c I was not opening files
900 in binary mode. Bug report and fix thanks to Ville.
911 in binary mode. Bug report and fix thanks to Ville.
901
912
902 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
913 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
903 trying to catch spurious foo[1] autocalls. My fix actually broke
914 trying to catch spurious foo[1] autocalls. My fix actually broke
904 ',/' autoquote/call with explicit escape (bad regexp).
915 ',/' autoquote/call with explicit escape (bad regexp).
905
916
906 2005-02-15 *** Released version 0.6.11
917 2005-02-15 *** Released version 0.6.11
907
918
908 2005-02-14 Fernando Perez <fperez@colorado.edu>
919 2005-02-14 Fernando Perez <fperez@colorado.edu>
909
920
910 * IPython/background_jobs.py: New background job management
921 * IPython/background_jobs.py: New background job management
911 subsystem. This is implemented via a new set of classes, and
922 subsystem. This is implemented via a new set of classes, and
912 IPython now provides a builtin 'jobs' object for background job
923 IPython now provides a builtin 'jobs' object for background job
913 execution. A convenience %bg magic serves as a lightweight
924 execution. A convenience %bg magic serves as a lightweight
914 frontend for starting the more common type of calls. This was
925 frontend for starting the more common type of calls. This was
915 inspired by discussions with B. Granger and the BackgroundCommand
926 inspired by discussions with B. Granger and the BackgroundCommand
916 class described in the book Python Scripting for Computational
927 class described in the book Python Scripting for Computational
917 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
928 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
918 (although ultimately no code from this text was used, as IPython's
929 (although ultimately no code from this text was used, as IPython's
919 system is a separate implementation).
930 system is a separate implementation).
920
931
921 * IPython/iplib.py (MagicCompleter.python_matches): add new option
932 * IPython/iplib.py (MagicCompleter.python_matches): add new option
922 to control the completion of single/double underscore names
933 to control the completion of single/double underscore names
923 separately. As documented in the example ipytonrc file, the
934 separately. As documented in the example ipytonrc file, the
924 readline_omit__names variable can now be set to 2, to omit even
935 readline_omit__names variable can now be set to 2, to omit even
925 single underscore names. Thanks to a patch by Brian Wong
936 single underscore names. Thanks to a patch by Brian Wong
926 <BrianWong-AT-AirgoNetworks.Com>.
937 <BrianWong-AT-AirgoNetworks.Com>.
927 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
938 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
928 be autocalled as foo([1]) if foo were callable. A problem for
939 be autocalled as foo([1]) if foo were callable. A problem for
929 things which are both callable and implement __getitem__.
940 things which are both callable and implement __getitem__.
930 (init_readline): Fix autoindentation for win32. Thanks to a patch
941 (init_readline): Fix autoindentation for win32. Thanks to a patch
931 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
942 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
932
943
933 2005-02-12 Fernando Perez <fperez@colorado.edu>
944 2005-02-12 Fernando Perez <fperez@colorado.edu>
934
945
935 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
946 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
936 which I had written long ago to sort out user error messages which
947 which I had written long ago to sort out user error messages which
937 may occur during startup. This seemed like a good idea initially,
948 may occur during startup. This seemed like a good idea initially,
938 but it has proven a disaster in retrospect. I don't want to
949 but it has proven a disaster in retrospect. I don't want to
939 change much code for now, so my fix is to set the internal 'debug'
950 change much code for now, so my fix is to set the internal 'debug'
940 flag to true everywhere, whose only job was precisely to control
951 flag to true everywhere, whose only job was precisely to control
941 this subsystem. This closes issue 28 (as well as avoiding all
952 this subsystem. This closes issue 28 (as well as avoiding all
942 sorts of strange hangups which occur from time to time).
953 sorts of strange hangups which occur from time to time).
943
954
944 2005-02-07 Fernando Perez <fperez@colorado.edu>
955 2005-02-07 Fernando Perez <fperez@colorado.edu>
945
956
946 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
957 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
947 previous call produced a syntax error.
958 previous call produced a syntax error.
948
959
949 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
960 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
950 classes without constructor.
961 classes without constructor.
951
962
952 2005-02-06 Fernando Perez <fperez@colorado.edu>
963 2005-02-06 Fernando Perez <fperez@colorado.edu>
953
964
954 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
965 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
955 completions with the results of each matcher, so we return results
966 completions with the results of each matcher, so we return results
956 to the user from all namespaces. This breaks with ipython
967 to the user from all namespaces. This breaks with ipython
957 tradition, but I think it's a nicer behavior. Now you get all
968 tradition, but I think it's a nicer behavior. Now you get all
958 possible completions listed, from all possible namespaces (python,
969 possible completions listed, from all possible namespaces (python,
959 filesystem, magics...) After a request by John Hunter
970 filesystem, magics...) After a request by John Hunter
960 <jdhunter-AT-nitace.bsd.uchicago.edu>.
971 <jdhunter-AT-nitace.bsd.uchicago.edu>.
961
972
962 2005-02-05 Fernando Perez <fperez@colorado.edu>
973 2005-02-05 Fernando Perez <fperez@colorado.edu>
963
974
964 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
975 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
965 the call had quote characters in it (the quotes were stripped).
976 the call had quote characters in it (the quotes were stripped).
966
977
967 2005-01-31 Fernando Perez <fperez@colorado.edu>
978 2005-01-31 Fernando Perez <fperez@colorado.edu>
968
979
969 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
980 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
970 Itpl.itpl() to make the code more robust against psyco
981 Itpl.itpl() to make the code more robust against psyco
971 optimizations.
982 optimizations.
972
983
973 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
984 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
974 of causing an exception. Quicker, cleaner.
985 of causing an exception. Quicker, cleaner.
975
986
976 2005-01-28 Fernando Perez <fperez@colorado.edu>
987 2005-01-28 Fernando Perez <fperez@colorado.edu>
977
988
978 * scripts/ipython_win_post_install.py (install): hardcode
989 * scripts/ipython_win_post_install.py (install): hardcode
979 sys.prefix+'python.exe' as the executable path. It turns out that
990 sys.prefix+'python.exe' as the executable path. It turns out that
980 during the post-installation run, sys.executable resolves to the
991 during the post-installation run, sys.executable resolves to the
981 name of the binary installer! I should report this as a distutils
992 name of the binary installer! I should report this as a distutils
982 bug, I think. I updated the .10 release with this tiny fix, to
993 bug, I think. I updated the .10 release with this tiny fix, to
983 avoid annoying the lists further.
994 avoid annoying the lists further.
984
995
985 2005-01-27 *** Released version 0.6.10
996 2005-01-27 *** Released version 0.6.10
986
997
987 2005-01-27 Fernando Perez <fperez@colorado.edu>
998 2005-01-27 Fernando Perez <fperez@colorado.edu>
988
999
989 * IPython/numutils.py (norm): Added 'inf' as optional name for
1000 * IPython/numutils.py (norm): Added 'inf' as optional name for
990 L-infinity norm, included references to mathworld.com for vector
1001 L-infinity norm, included references to mathworld.com for vector
991 norm definitions.
1002 norm definitions.
992 (amin/amax): added amin/amax for array min/max. Similar to what
1003 (amin/amax): added amin/amax for array min/max. Similar to what
993 pylab ships with after the recent reorganization of names.
1004 pylab ships with after the recent reorganization of names.
994 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1005 (spike/spike_odd): removed deprecated spike/spike_odd functions.
995
1006
996 * ipython.el: committed Alex's recent fixes and improvements.
1007 * ipython.el: committed Alex's recent fixes and improvements.
997 Tested with python-mode from CVS, and it looks excellent. Since
1008 Tested with python-mode from CVS, and it looks excellent. Since
998 python-mode hasn't released anything in a while, I'm temporarily
1009 python-mode hasn't released anything in a while, I'm temporarily
999 putting a copy of today's CVS (v 4.70) of python-mode in:
1010 putting a copy of today's CVS (v 4.70) of python-mode in:
1000 http://ipython.scipy.org/tmp/python-mode.el
1011 http://ipython.scipy.org/tmp/python-mode.el
1001
1012
1002 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1013 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1003 sys.executable for the executable name, instead of assuming it's
1014 sys.executable for the executable name, instead of assuming it's
1004 called 'python.exe' (the post-installer would have produced broken
1015 called 'python.exe' (the post-installer would have produced broken
1005 setups on systems with a differently named python binary).
1016 setups on systems with a differently named python binary).
1006
1017
1007 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1018 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1008 references to os.linesep, to make the code more
1019 references to os.linesep, to make the code more
1009 platform-independent. This is also part of the win32 coloring
1020 platform-independent. This is also part of the win32 coloring
1010 fixes.
1021 fixes.
1011
1022
1012 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1023 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1013 lines, which actually cause coloring bugs because the length of
1024 lines, which actually cause coloring bugs because the length of
1014 the line is very difficult to correctly compute with embedded
1025 the line is very difficult to correctly compute with embedded
1015 escapes. This was the source of all the coloring problems under
1026 escapes. This was the source of all the coloring problems under
1016 Win32. I think that _finally_, Win32 users have a properly
1027 Win32. I think that _finally_, Win32 users have a properly
1017 working ipython in all respects. This would never have happened
1028 working ipython in all respects. This would never have happened
1018 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1029 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1019
1030
1020 2005-01-26 *** Released version 0.6.9
1031 2005-01-26 *** Released version 0.6.9
1021
1032
1022 2005-01-25 Fernando Perez <fperez@colorado.edu>
1033 2005-01-25 Fernando Perez <fperez@colorado.edu>
1023
1034
1024 * setup.py: finally, we have a true Windows installer, thanks to
1035 * setup.py: finally, we have a true Windows installer, thanks to
1025 the excellent work of Viktor Ransmayr
1036 the excellent work of Viktor Ransmayr
1026 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1037 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1027 Windows users. The setup routine is quite a bit cleaner thanks to
1038 Windows users. The setup routine is quite a bit cleaner thanks to
1028 this, and the post-install script uses the proper functions to
1039 this, and the post-install script uses the proper functions to
1029 allow a clean de-installation using the standard Windows Control
1040 allow a clean de-installation using the standard Windows Control
1030 Panel.
1041 Panel.
1031
1042
1032 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1043 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1033 environment variable under all OSes (including win32) if
1044 environment variable under all OSes (including win32) if
1034 available. This will give consistency to win32 users who have set
1045 available. This will give consistency to win32 users who have set
1035 this variable for any reason. If os.environ['HOME'] fails, the
1046 this variable for any reason. If os.environ['HOME'] fails, the
1036 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1047 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1037
1048
1038 2005-01-24 Fernando Perez <fperez@colorado.edu>
1049 2005-01-24 Fernando Perez <fperez@colorado.edu>
1039
1050
1040 * IPython/numutils.py (empty_like): add empty_like(), similar to
1051 * IPython/numutils.py (empty_like): add empty_like(), similar to
1041 zeros_like() but taking advantage of the new empty() Numeric routine.
1052 zeros_like() but taking advantage of the new empty() Numeric routine.
1042
1053
1043 2005-01-23 *** Released version 0.6.8
1054 2005-01-23 *** Released version 0.6.8
1044
1055
1045 2005-01-22 Fernando Perez <fperez@colorado.edu>
1056 2005-01-22 Fernando Perez <fperez@colorado.edu>
1046
1057
1047 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1058 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1048 automatic show() calls. After discussing things with JDH, it
1059 automatic show() calls. After discussing things with JDH, it
1049 turns out there are too many corner cases where this can go wrong.
1060 turns out there are too many corner cases where this can go wrong.
1050 It's best not to try to be 'too smart', and simply have ipython
1061 It's best not to try to be 'too smart', and simply have ipython
1051 reproduce as much as possible the default behavior of a normal
1062 reproduce as much as possible the default behavior of a normal
1052 python shell.
1063 python shell.
1053
1064
1054 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1065 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1055 line-splitting regexp and _prefilter() to avoid calling getattr()
1066 line-splitting regexp and _prefilter() to avoid calling getattr()
1056 on assignments. This closes
1067 on assignments. This closes
1057 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1068 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1058 readline uses getattr(), so a simple <TAB> keypress is still
1069 readline uses getattr(), so a simple <TAB> keypress is still
1059 enough to trigger getattr() calls on an object.
1070 enough to trigger getattr() calls on an object.
1060
1071
1061 2005-01-21 Fernando Perez <fperez@colorado.edu>
1072 2005-01-21 Fernando Perez <fperez@colorado.edu>
1062
1073
1063 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1074 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1064 docstring under pylab so it doesn't mask the original.
1075 docstring under pylab so it doesn't mask the original.
1065
1076
1066 2005-01-21 *** Released version 0.6.7
1077 2005-01-21 *** Released version 0.6.7
1067
1078
1068 2005-01-21 Fernando Perez <fperez@colorado.edu>
1079 2005-01-21 Fernando Perez <fperez@colorado.edu>
1069
1080
1070 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1081 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1071 signal handling for win32 users in multithreaded mode.
1082 signal handling for win32 users in multithreaded mode.
1072
1083
1073 2005-01-17 Fernando Perez <fperez@colorado.edu>
1084 2005-01-17 Fernando Perez <fperez@colorado.edu>
1074
1085
1075 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1086 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1076 instances with no __init__. After a crash report by Norbert Nemec
1087 instances with no __init__. After a crash report by Norbert Nemec
1077 <Norbert-AT-nemec-online.de>.
1088 <Norbert-AT-nemec-online.de>.
1078
1089
1079 2005-01-14 Fernando Perez <fperez@colorado.edu>
1090 2005-01-14 Fernando Perez <fperez@colorado.edu>
1080
1091
1081 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1092 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1082 names for verbose exceptions, when multiple dotted names and the
1093 names for verbose exceptions, when multiple dotted names and the
1083 'parent' object were present on the same line.
1094 'parent' object were present on the same line.
1084
1095
1085 2005-01-11 Fernando Perez <fperez@colorado.edu>
1096 2005-01-11 Fernando Perez <fperez@colorado.edu>
1086
1097
1087 * IPython/genutils.py (flag_calls): new utility to trap and flag
1098 * IPython/genutils.py (flag_calls): new utility to trap and flag
1088 calls in functions. I need it to clean up matplotlib support.
1099 calls in functions. I need it to clean up matplotlib support.
1089 Also removed some deprecated code in genutils.
1100 Also removed some deprecated code in genutils.
1090
1101
1091 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1102 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1092 that matplotlib scripts called with %run, which don't call show()
1103 that matplotlib scripts called with %run, which don't call show()
1093 themselves, still have their plotting windows open.
1104 themselves, still have their plotting windows open.
1094
1105
1095 2005-01-05 Fernando Perez <fperez@colorado.edu>
1106 2005-01-05 Fernando Perez <fperez@colorado.edu>
1096
1107
1097 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1108 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1098 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1109 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1099
1110
1100 2004-12-19 Fernando Perez <fperez@colorado.edu>
1111 2004-12-19 Fernando Perez <fperez@colorado.edu>
1101
1112
1102 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1113 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1103 parent_runcode, which was an eyesore. The same result can be
1114 parent_runcode, which was an eyesore. The same result can be
1104 obtained with Python's regular superclass mechanisms.
1115 obtained with Python's regular superclass mechanisms.
1105
1116
1106 2004-12-17 Fernando Perez <fperez@colorado.edu>
1117 2004-12-17 Fernando Perez <fperez@colorado.edu>
1107
1118
1108 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1119 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1109 reported by Prabhu.
1120 reported by Prabhu.
1110 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1121 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1111 sys.stderr) instead of explicitly calling sys.stderr. This helps
1122 sys.stderr) instead of explicitly calling sys.stderr. This helps
1112 maintain our I/O abstractions clean, for future GUI embeddings.
1123 maintain our I/O abstractions clean, for future GUI embeddings.
1113
1124
1114 * IPython/genutils.py (info): added new utility for sys.stderr
1125 * IPython/genutils.py (info): added new utility for sys.stderr
1115 unified info message handling (thin wrapper around warn()).
1126 unified info message handling (thin wrapper around warn()).
1116
1127
1117 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1128 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1118 composite (dotted) names on verbose exceptions.
1129 composite (dotted) names on verbose exceptions.
1119 (VerboseTB.nullrepr): harden against another kind of errors which
1130 (VerboseTB.nullrepr): harden against another kind of errors which
1120 Python's inspect module can trigger, and which were crashing
1131 Python's inspect module can trigger, and which were crashing
1121 IPython. Thanks to a report by Marco Lombardi
1132 IPython. Thanks to a report by Marco Lombardi
1122 <mlombard-AT-ma010192.hq.eso.org>.
1133 <mlombard-AT-ma010192.hq.eso.org>.
1123
1134
1124 2004-12-13 *** Released version 0.6.6
1135 2004-12-13 *** Released version 0.6.6
1125
1136
1126 2004-12-12 Fernando Perez <fperez@colorado.edu>
1137 2004-12-12 Fernando Perez <fperez@colorado.edu>
1127
1138
1128 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1139 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1129 generated by pygtk upon initialization if it was built without
1140 generated by pygtk upon initialization if it was built without
1130 threads (for matplotlib users). After a crash reported by
1141 threads (for matplotlib users). After a crash reported by
1131 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1142 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1132
1143
1133 * IPython/ipmaker.py (make_IPython): fix small bug in the
1144 * IPython/ipmaker.py (make_IPython): fix small bug in the
1134 import_some parameter for multiple imports.
1145 import_some parameter for multiple imports.
1135
1146
1136 * IPython/iplib.py (ipmagic): simplified the interface of
1147 * IPython/iplib.py (ipmagic): simplified the interface of
1137 ipmagic() to take a single string argument, just as it would be
1148 ipmagic() to take a single string argument, just as it would be
1138 typed at the IPython cmd line.
1149 typed at the IPython cmd line.
1139 (ipalias): Added new ipalias() with an interface identical to
1150 (ipalias): Added new ipalias() with an interface identical to
1140 ipmagic(). This completes exposing a pure python interface to the
1151 ipmagic(). This completes exposing a pure python interface to the
1141 alias and magic system, which can be used in loops or more complex
1152 alias and magic system, which can be used in loops or more complex
1142 code where IPython's automatic line mangling is not active.
1153 code where IPython's automatic line mangling is not active.
1143
1154
1144 * IPython/genutils.py (timing): changed interface of timing to
1155 * IPython/genutils.py (timing): changed interface of timing to
1145 simply run code once, which is the most common case. timings()
1156 simply run code once, which is the most common case. timings()
1146 remains unchanged, for the cases where you want multiple runs.
1157 remains unchanged, for the cases where you want multiple runs.
1147
1158
1148 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1159 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1149 bug where Python2.2 crashes with exec'ing code which does not end
1160 bug where Python2.2 crashes with exec'ing code which does not end
1150 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1161 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1151 before.
1162 before.
1152
1163
1153 2004-12-10 Fernando Perez <fperez@colorado.edu>
1164 2004-12-10 Fernando Perez <fperez@colorado.edu>
1154
1165
1155 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1166 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1156 -t to -T, to accomodate the new -t flag in %run (the %run and
1167 -t to -T, to accomodate the new -t flag in %run (the %run and
1157 %prun options are kind of intermixed, and it's not easy to change
1168 %prun options are kind of intermixed, and it's not easy to change
1158 this with the limitations of python's getopt).
1169 this with the limitations of python's getopt).
1159
1170
1160 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1171 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1161 the execution of scripts. It's not as fine-tuned as timeit.py,
1172 the execution of scripts. It's not as fine-tuned as timeit.py,
1162 but it works from inside ipython (and under 2.2, which lacks
1173 but it works from inside ipython (and under 2.2, which lacks
1163 timeit.py). Optionally a number of runs > 1 can be given for
1174 timeit.py). Optionally a number of runs > 1 can be given for
1164 timing very short-running code.
1175 timing very short-running code.
1165
1176
1166 * IPython/genutils.py (uniq_stable): new routine which returns a
1177 * IPython/genutils.py (uniq_stable): new routine which returns a
1167 list of unique elements in any iterable, but in stable order of
1178 list of unique elements in any iterable, but in stable order of
1168 appearance. I needed this for the ultraTB fixes, and it's a handy
1179 appearance. I needed this for the ultraTB fixes, and it's a handy
1169 utility.
1180 utility.
1170
1181
1171 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1182 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1172 dotted names in Verbose exceptions. This had been broken since
1183 dotted names in Verbose exceptions. This had been broken since
1173 the very start, now x.y will properly be printed in a Verbose
1184 the very start, now x.y will properly be printed in a Verbose
1174 traceback, instead of x being shown and y appearing always as an
1185 traceback, instead of x being shown and y appearing always as an
1175 'undefined global'. Getting this to work was a bit tricky,
1186 'undefined global'. Getting this to work was a bit tricky,
1176 because by default python tokenizers are stateless. Saved by
1187 because by default python tokenizers are stateless. Saved by
1177 python's ability to easily add a bit of state to an arbitrary
1188 python's ability to easily add a bit of state to an arbitrary
1178 function (without needing to build a full-blown callable object).
1189 function (without needing to build a full-blown callable object).
1179
1190
1180 Also big cleanup of this code, which had horrendous runtime
1191 Also big cleanup of this code, which had horrendous runtime
1181 lookups of zillions of attributes for colorization. Moved all
1192 lookups of zillions of attributes for colorization. Moved all
1182 this code into a few templates, which make it cleaner and quicker.
1193 this code into a few templates, which make it cleaner and quicker.
1183
1194
1184 Printout quality was also improved for Verbose exceptions: one
1195 Printout quality was also improved for Verbose exceptions: one
1185 variable per line, and memory addresses are printed (this can be
1196 variable per line, and memory addresses are printed (this can be
1186 quite handy in nasty debugging situations, which is what Verbose
1197 quite handy in nasty debugging situations, which is what Verbose
1187 is for).
1198 is for).
1188
1199
1189 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1200 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1190 the command line as scripts to be loaded by embedded instances.
1201 the command line as scripts to be loaded by embedded instances.
1191 Doing so has the potential for an infinite recursion if there are
1202 Doing so has the potential for an infinite recursion if there are
1192 exceptions thrown in the process. This fixes a strange crash
1203 exceptions thrown in the process. This fixes a strange crash
1193 reported by Philippe MULLER <muller-AT-irit.fr>.
1204 reported by Philippe MULLER <muller-AT-irit.fr>.
1194
1205
1195 2004-12-09 Fernando Perez <fperez@colorado.edu>
1206 2004-12-09 Fernando Perez <fperez@colorado.edu>
1196
1207
1197 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1208 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1198 to reflect new names in matplotlib, which now expose the
1209 to reflect new names in matplotlib, which now expose the
1199 matlab-compatible interface via a pylab module instead of the
1210 matlab-compatible interface via a pylab module instead of the
1200 'matlab' name. The new code is backwards compatible, so users of
1211 'matlab' name. The new code is backwards compatible, so users of
1201 all matplotlib versions are OK. Patch by J. Hunter.
1212 all matplotlib versions are OK. Patch by J. Hunter.
1202
1213
1203 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1214 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1204 of __init__ docstrings for instances (class docstrings are already
1215 of __init__ docstrings for instances (class docstrings are already
1205 automatically printed). Instances with customized docstrings
1216 automatically printed). Instances with customized docstrings
1206 (indep. of the class) are also recognized and all 3 separate
1217 (indep. of the class) are also recognized and all 3 separate
1207 docstrings are printed (instance, class, constructor). After some
1218 docstrings are printed (instance, class, constructor). After some
1208 comments/suggestions by J. Hunter.
1219 comments/suggestions by J. Hunter.
1209
1220
1210 2004-12-05 Fernando Perez <fperez@colorado.edu>
1221 2004-12-05 Fernando Perez <fperez@colorado.edu>
1211
1222
1212 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1223 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1213 warnings when tab-completion fails and triggers an exception.
1224 warnings when tab-completion fails and triggers an exception.
1214
1225
1215 2004-12-03 Fernando Perez <fperez@colorado.edu>
1226 2004-12-03 Fernando Perez <fperez@colorado.edu>
1216
1227
1217 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1228 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1218 be triggered when using 'run -p'. An incorrect option flag was
1229 be triggered when using 'run -p'. An incorrect option flag was
1219 being set ('d' instead of 'D').
1230 being set ('d' instead of 'D').
1220 (manpage): fix missing escaped \- sign.
1231 (manpage): fix missing escaped \- sign.
1221
1232
1222 2004-11-30 *** Released version 0.6.5
1233 2004-11-30 *** Released version 0.6.5
1223
1234
1224 2004-11-30 Fernando Perez <fperez@colorado.edu>
1235 2004-11-30 Fernando Perez <fperez@colorado.edu>
1225
1236
1226 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1237 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1227 setting with -d option.
1238 setting with -d option.
1228
1239
1229 * setup.py (docfiles): Fix problem where the doc glob I was using
1240 * setup.py (docfiles): Fix problem where the doc glob I was using
1230 was COMPLETELY BROKEN. It was giving the right files by pure
1241 was COMPLETELY BROKEN. It was giving the right files by pure
1231 accident, but failed once I tried to include ipython.el. Note:
1242 accident, but failed once I tried to include ipython.el. Note:
1232 glob() does NOT allow you to do exclusion on multiple endings!
1243 glob() does NOT allow you to do exclusion on multiple endings!
1233
1244
1234 2004-11-29 Fernando Perez <fperez@colorado.edu>
1245 2004-11-29 Fernando Perez <fperez@colorado.edu>
1235
1246
1236 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1247 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1237 the manpage as the source. Better formatting & consistency.
1248 the manpage as the source. Better formatting & consistency.
1238
1249
1239 * IPython/Magic.py (magic_run): Added new -d option, to run
1250 * IPython/Magic.py (magic_run): Added new -d option, to run
1240 scripts under the control of the python pdb debugger. Note that
1251 scripts under the control of the python pdb debugger. Note that
1241 this required changing the %prun option -d to -D, to avoid a clash
1252 this required changing the %prun option -d to -D, to avoid a clash
1242 (since %run must pass options to %prun, and getopt is too dumb to
1253 (since %run must pass options to %prun, and getopt is too dumb to
1243 handle options with string values with embedded spaces). Thanks
1254 handle options with string values with embedded spaces). Thanks
1244 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1255 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1245 (magic_who_ls): added type matching to %who and %whos, so that one
1256 (magic_who_ls): added type matching to %who and %whos, so that one
1246 can filter their output to only include variables of certain
1257 can filter their output to only include variables of certain
1247 types. Another suggestion by Matthew.
1258 types. Another suggestion by Matthew.
1248 (magic_whos): Added memory summaries in kb and Mb for arrays.
1259 (magic_whos): Added memory summaries in kb and Mb for arrays.
1249 (magic_who): Improve formatting (break lines every 9 vars).
1260 (magic_who): Improve formatting (break lines every 9 vars).
1250
1261
1251 2004-11-28 Fernando Perez <fperez@colorado.edu>
1262 2004-11-28 Fernando Perez <fperez@colorado.edu>
1252
1263
1253 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1264 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1254 cache when empty lines were present.
1265 cache when empty lines were present.
1255
1266
1256 2004-11-24 Fernando Perez <fperez@colorado.edu>
1267 2004-11-24 Fernando Perez <fperez@colorado.edu>
1257
1268
1258 * IPython/usage.py (__doc__): document the re-activated threading
1269 * IPython/usage.py (__doc__): document the re-activated threading
1259 options for WX and GTK.
1270 options for WX and GTK.
1260
1271
1261 2004-11-23 Fernando Perez <fperez@colorado.edu>
1272 2004-11-23 Fernando Perez <fperez@colorado.edu>
1262
1273
1263 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1274 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1264 the -wthread and -gthread options, along with a new -tk one to try
1275 the -wthread and -gthread options, along with a new -tk one to try
1265 and coordinate Tk threading with wx/gtk. The tk support is very
1276 and coordinate Tk threading with wx/gtk. The tk support is very
1266 platform dependent, since it seems to require Tcl and Tk to be
1277 platform dependent, since it seems to require Tcl and Tk to be
1267 built with threads (Fedora1/2 appears NOT to have it, but in
1278 built with threads (Fedora1/2 appears NOT to have it, but in
1268 Prabhu's Debian boxes it works OK). But even with some Tk
1279 Prabhu's Debian boxes it works OK). But even with some Tk
1269 limitations, this is a great improvement.
1280 limitations, this is a great improvement.
1270
1281
1271 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1282 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1272 info in user prompts. Patch by Prabhu.
1283 info in user prompts. Patch by Prabhu.
1273
1284
1274 2004-11-18 Fernando Perez <fperez@colorado.edu>
1285 2004-11-18 Fernando Perez <fperez@colorado.edu>
1275
1286
1276 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1287 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1277 EOFErrors and bail, to avoid infinite loops if a non-terminating
1288 EOFErrors and bail, to avoid infinite loops if a non-terminating
1278 file is fed into ipython. Patch submitted in issue 19 by user,
1289 file is fed into ipython. Patch submitted in issue 19 by user,
1279 many thanks.
1290 many thanks.
1280
1291
1281 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1292 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1282 autoquote/parens in continuation prompts, which can cause lots of
1293 autoquote/parens in continuation prompts, which can cause lots of
1283 problems. Closes roundup issue 20.
1294 problems. Closes roundup issue 20.
1284
1295
1285 2004-11-17 Fernando Perez <fperez@colorado.edu>
1296 2004-11-17 Fernando Perez <fperez@colorado.edu>
1286
1297
1287 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1298 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1288 reported as debian bug #280505. I'm not sure my local changelog
1299 reported as debian bug #280505. I'm not sure my local changelog
1289 entry has the proper debian format (Jack?).
1300 entry has the proper debian format (Jack?).
1290
1301
1291 2004-11-08 *** Released version 0.6.4
1302 2004-11-08 *** Released version 0.6.4
1292
1303
1293 2004-11-08 Fernando Perez <fperez@colorado.edu>
1304 2004-11-08 Fernando Perez <fperez@colorado.edu>
1294
1305
1295 * IPython/iplib.py (init_readline): Fix exit message for Windows
1306 * IPython/iplib.py (init_readline): Fix exit message for Windows
1296 when readline is active. Thanks to a report by Eric Jones
1307 when readline is active. Thanks to a report by Eric Jones
1297 <eric-AT-enthought.com>.
1308 <eric-AT-enthought.com>.
1298
1309
1299 2004-11-07 Fernando Perez <fperez@colorado.edu>
1310 2004-11-07 Fernando Perez <fperez@colorado.edu>
1300
1311
1301 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1312 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1302 sometimes seen by win2k/cygwin users.
1313 sometimes seen by win2k/cygwin users.
1303
1314
1304 2004-11-06 Fernando Perez <fperez@colorado.edu>
1315 2004-11-06 Fernando Perez <fperez@colorado.edu>
1305
1316
1306 * IPython/iplib.py (interact): Change the handling of %Exit from
1317 * IPython/iplib.py (interact): Change the handling of %Exit from
1307 trying to propagate a SystemExit to an internal ipython flag.
1318 trying to propagate a SystemExit to an internal ipython flag.
1308 This is less elegant than using Python's exception mechanism, but
1319 This is less elegant than using Python's exception mechanism, but
1309 I can't get that to work reliably with threads, so under -pylab
1320 I can't get that to work reliably with threads, so under -pylab
1310 %Exit was hanging IPython. Cross-thread exception handling is
1321 %Exit was hanging IPython. Cross-thread exception handling is
1311 really a bitch. Thaks to a bug report by Stephen Walton
1322 really a bitch. Thaks to a bug report by Stephen Walton
1312 <stephen.walton-AT-csun.edu>.
1323 <stephen.walton-AT-csun.edu>.
1313
1324
1314 2004-11-04 Fernando Perez <fperez@colorado.edu>
1325 2004-11-04 Fernando Perez <fperez@colorado.edu>
1315
1326
1316 * IPython/iplib.py (raw_input_original): store a pointer to the
1327 * IPython/iplib.py (raw_input_original): store a pointer to the
1317 true raw_input to harden against code which can modify it
1328 true raw_input to harden against code which can modify it
1318 (wx.py.PyShell does this and would otherwise crash ipython).
1329 (wx.py.PyShell does this and would otherwise crash ipython).
1319 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1330 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1320
1331
1321 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1332 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1322 Ctrl-C problem, which does not mess up the input line.
1333 Ctrl-C problem, which does not mess up the input line.
1323
1334
1324 2004-11-03 Fernando Perez <fperez@colorado.edu>
1335 2004-11-03 Fernando Perez <fperez@colorado.edu>
1325
1336
1326 * IPython/Release.py: Changed licensing to BSD, in all files.
1337 * IPython/Release.py: Changed licensing to BSD, in all files.
1327 (name): lowercase name for tarball/RPM release.
1338 (name): lowercase name for tarball/RPM release.
1328
1339
1329 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1340 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1330 use throughout ipython.
1341 use throughout ipython.
1331
1342
1332 * IPython/Magic.py (Magic._ofind): Switch to using the new
1343 * IPython/Magic.py (Magic._ofind): Switch to using the new
1333 OInspect.getdoc() function.
1344 OInspect.getdoc() function.
1334
1345
1335 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1346 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1336 of the line currently being canceled via Ctrl-C. It's extremely
1347 of the line currently being canceled via Ctrl-C. It's extremely
1337 ugly, but I don't know how to do it better (the problem is one of
1348 ugly, but I don't know how to do it better (the problem is one of
1338 handling cross-thread exceptions).
1349 handling cross-thread exceptions).
1339
1350
1340 2004-10-28 Fernando Perez <fperez@colorado.edu>
1351 2004-10-28 Fernando Perez <fperez@colorado.edu>
1341
1352
1342 * IPython/Shell.py (signal_handler): add signal handlers to trap
1353 * IPython/Shell.py (signal_handler): add signal handlers to trap
1343 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1354 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1344 report by Francesc Alted.
1355 report by Francesc Alted.
1345
1356
1346 2004-10-21 Fernando Perez <fperez@colorado.edu>
1357 2004-10-21 Fernando Perez <fperez@colorado.edu>
1347
1358
1348 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1359 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1349 to % for pysh syntax extensions.
1360 to % for pysh syntax extensions.
1350
1361
1351 2004-10-09 Fernando Perez <fperez@colorado.edu>
1362 2004-10-09 Fernando Perez <fperez@colorado.edu>
1352
1363
1353 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1364 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1354 arrays to print a more useful summary, without calling str(arr).
1365 arrays to print a more useful summary, without calling str(arr).
1355 This avoids the problem of extremely lengthy computations which
1366 This avoids the problem of extremely lengthy computations which
1356 occur if arr is large, and appear to the user as a system lockup
1367 occur if arr is large, and appear to the user as a system lockup
1357 with 100% cpu activity. After a suggestion by Kristian Sandberg
1368 with 100% cpu activity. After a suggestion by Kristian Sandberg
1358 <Kristian.Sandberg@colorado.edu>.
1369 <Kristian.Sandberg@colorado.edu>.
1359 (Magic.__init__): fix bug in global magic escapes not being
1370 (Magic.__init__): fix bug in global magic escapes not being
1360 correctly set.
1371 correctly set.
1361
1372
1362 2004-10-08 Fernando Perez <fperez@colorado.edu>
1373 2004-10-08 Fernando Perez <fperez@colorado.edu>
1363
1374
1364 * IPython/Magic.py (__license__): change to absolute imports of
1375 * IPython/Magic.py (__license__): change to absolute imports of
1365 ipython's own internal packages, to start adapting to the absolute
1376 ipython's own internal packages, to start adapting to the absolute
1366 import requirement of PEP-328.
1377 import requirement of PEP-328.
1367
1378
1368 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1379 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1369 files, and standardize author/license marks through the Release
1380 files, and standardize author/license marks through the Release
1370 module instead of having per/file stuff (except for files with
1381 module instead of having per/file stuff (except for files with
1371 particular licenses, like the MIT/PSF-licensed codes).
1382 particular licenses, like the MIT/PSF-licensed codes).
1372
1383
1373 * IPython/Debugger.py: remove dead code for python 2.1
1384 * IPython/Debugger.py: remove dead code for python 2.1
1374
1385
1375 2004-10-04 Fernando Perez <fperez@colorado.edu>
1386 2004-10-04 Fernando Perez <fperez@colorado.edu>
1376
1387
1377 * IPython/iplib.py (ipmagic): New function for accessing magics
1388 * IPython/iplib.py (ipmagic): New function for accessing magics
1378 via a normal python function call.
1389 via a normal python function call.
1379
1390
1380 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1391 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1381 from '@' to '%', to accomodate the new @decorator syntax of python
1392 from '@' to '%', to accomodate the new @decorator syntax of python
1382 2.4.
1393 2.4.
1383
1394
1384 2004-09-29 Fernando Perez <fperez@colorado.edu>
1395 2004-09-29 Fernando Perez <fperez@colorado.edu>
1385
1396
1386 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1397 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1387 matplotlib.use to prevent running scripts which try to switch
1398 matplotlib.use to prevent running scripts which try to switch
1388 interactive backends from within ipython. This will just crash
1399 interactive backends from within ipython. This will just crash
1389 the python interpreter, so we can't allow it (but a detailed error
1400 the python interpreter, so we can't allow it (but a detailed error
1390 is given to the user).
1401 is given to the user).
1391
1402
1392 2004-09-28 Fernando Perez <fperez@colorado.edu>
1403 2004-09-28 Fernando Perez <fperez@colorado.edu>
1393
1404
1394 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1405 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1395 matplotlib-related fixes so that using @run with non-matplotlib
1406 matplotlib-related fixes so that using @run with non-matplotlib
1396 scripts doesn't pop up spurious plot windows. This requires
1407 scripts doesn't pop up spurious plot windows. This requires
1397 matplotlib >= 0.63, where I had to make some changes as well.
1408 matplotlib >= 0.63, where I had to make some changes as well.
1398
1409
1399 * IPython/ipmaker.py (make_IPython): update version requirement to
1410 * IPython/ipmaker.py (make_IPython): update version requirement to
1400 python 2.2.
1411 python 2.2.
1401
1412
1402 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1413 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1403 banner arg for embedded customization.
1414 banner arg for embedded customization.
1404
1415
1405 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1416 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1406 explicit uses of __IP as the IPython's instance name. Now things
1417 explicit uses of __IP as the IPython's instance name. Now things
1407 are properly handled via the shell.name value. The actual code
1418 are properly handled via the shell.name value. The actual code
1408 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1419 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1409 is much better than before. I'll clean things completely when the
1420 is much better than before. I'll clean things completely when the
1410 magic stuff gets a real overhaul.
1421 magic stuff gets a real overhaul.
1411
1422
1412 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1423 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1413 minor changes to debian dir.
1424 minor changes to debian dir.
1414
1425
1415 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1426 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1416 pointer to the shell itself in the interactive namespace even when
1427 pointer to the shell itself in the interactive namespace even when
1417 a user-supplied dict is provided. This is needed for embedding
1428 a user-supplied dict is provided. This is needed for embedding
1418 purposes (found by tests with Michel Sanner).
1429 purposes (found by tests with Michel Sanner).
1419
1430
1420 2004-09-27 Fernando Perez <fperez@colorado.edu>
1431 2004-09-27 Fernando Perez <fperez@colorado.edu>
1421
1432
1422 * IPython/UserConfig/ipythonrc: remove []{} from
1433 * IPython/UserConfig/ipythonrc: remove []{} from
1423 readline_remove_delims, so that things like [modname.<TAB> do
1434 readline_remove_delims, so that things like [modname.<TAB> do
1424 proper completion. This disables [].TAB, but that's a less common
1435 proper completion. This disables [].TAB, but that's a less common
1425 case than module names in list comprehensions, for example.
1436 case than module names in list comprehensions, for example.
1426 Thanks to a report by Andrea Riciputi.
1437 Thanks to a report by Andrea Riciputi.
1427
1438
1428 2004-09-09 Fernando Perez <fperez@colorado.edu>
1439 2004-09-09 Fernando Perez <fperez@colorado.edu>
1429
1440
1430 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1441 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1431 blocking problems in win32 and osx. Fix by John.
1442 blocking problems in win32 and osx. Fix by John.
1432
1443
1433 2004-09-08 Fernando Perez <fperez@colorado.edu>
1444 2004-09-08 Fernando Perez <fperez@colorado.edu>
1434
1445
1435 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1446 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1436 for Win32 and OSX. Fix by John Hunter.
1447 for Win32 and OSX. Fix by John Hunter.
1437
1448
1438 2004-08-30 *** Released version 0.6.3
1449 2004-08-30 *** Released version 0.6.3
1439
1450
1440 2004-08-30 Fernando Perez <fperez@colorado.edu>
1451 2004-08-30 Fernando Perez <fperez@colorado.edu>
1441
1452
1442 * setup.py (isfile): Add manpages to list of dependent files to be
1453 * setup.py (isfile): Add manpages to list of dependent files to be
1443 updated.
1454 updated.
1444
1455
1445 2004-08-27 Fernando Perez <fperez@colorado.edu>
1456 2004-08-27 Fernando Perez <fperez@colorado.edu>
1446
1457
1447 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1458 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1448 for now. They don't really work with standalone WX/GTK code
1459 for now. They don't really work with standalone WX/GTK code
1449 (though matplotlib IS working fine with both of those backends).
1460 (though matplotlib IS working fine with both of those backends).
1450 This will neeed much more testing. I disabled most things with
1461 This will neeed much more testing. I disabled most things with
1451 comments, so turning it back on later should be pretty easy.
1462 comments, so turning it back on later should be pretty easy.
1452
1463
1453 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1464 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1454 autocalling of expressions like r'foo', by modifying the line
1465 autocalling of expressions like r'foo', by modifying the line
1455 split regexp. Closes
1466 split regexp. Closes
1456 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1467 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1457 Riley <ipythonbugs-AT-sabi.net>.
1468 Riley <ipythonbugs-AT-sabi.net>.
1458 (InteractiveShell.mainloop): honor --nobanner with banner
1469 (InteractiveShell.mainloop): honor --nobanner with banner
1459 extensions.
1470 extensions.
1460
1471
1461 * IPython/Shell.py: Significant refactoring of all classes, so
1472 * IPython/Shell.py: Significant refactoring of all classes, so
1462 that we can really support ALL matplotlib backends and threading
1473 that we can really support ALL matplotlib backends and threading
1463 models (John spotted a bug with Tk which required this). Now we
1474 models (John spotted a bug with Tk which required this). Now we
1464 should support single-threaded, WX-threads and GTK-threads, both
1475 should support single-threaded, WX-threads and GTK-threads, both
1465 for generic code and for matplotlib.
1476 for generic code and for matplotlib.
1466
1477
1467 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1478 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1468 -pylab, to simplify things for users. Will also remove the pylab
1479 -pylab, to simplify things for users. Will also remove the pylab
1469 profile, since now all of matplotlib configuration is directly
1480 profile, since now all of matplotlib configuration is directly
1470 handled here. This also reduces startup time.
1481 handled here. This also reduces startup time.
1471
1482
1472 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1483 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1473 shell wasn't being correctly called. Also in IPShellWX.
1484 shell wasn't being correctly called. Also in IPShellWX.
1474
1485
1475 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1486 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1476 fine-tune banner.
1487 fine-tune banner.
1477
1488
1478 * IPython/numutils.py (spike): Deprecate these spike functions,
1489 * IPython/numutils.py (spike): Deprecate these spike functions,
1479 delete (long deprecated) gnuplot_exec handler.
1490 delete (long deprecated) gnuplot_exec handler.
1480
1491
1481 2004-08-26 Fernando Perez <fperez@colorado.edu>
1492 2004-08-26 Fernando Perez <fperez@colorado.edu>
1482
1493
1483 * ipython.1: Update for threading options, plus some others which
1494 * ipython.1: Update for threading options, plus some others which
1484 were missing.
1495 were missing.
1485
1496
1486 * IPython/ipmaker.py (__call__): Added -wthread option for
1497 * IPython/ipmaker.py (__call__): Added -wthread option for
1487 wxpython thread handling. Make sure threading options are only
1498 wxpython thread handling. Make sure threading options are only
1488 valid at the command line.
1499 valid at the command line.
1489
1500
1490 * scripts/ipython: moved shell selection into a factory function
1501 * scripts/ipython: moved shell selection into a factory function
1491 in Shell.py, to keep the starter script to a minimum.
1502 in Shell.py, to keep the starter script to a minimum.
1492
1503
1493 2004-08-25 Fernando Perez <fperez@colorado.edu>
1504 2004-08-25 Fernando Perez <fperez@colorado.edu>
1494
1505
1495 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1506 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1496 John. Along with some recent changes he made to matplotlib, the
1507 John. Along with some recent changes he made to matplotlib, the
1497 next versions of both systems should work very well together.
1508 next versions of both systems should work very well together.
1498
1509
1499 2004-08-24 Fernando Perez <fperez@colorado.edu>
1510 2004-08-24 Fernando Perez <fperez@colorado.edu>
1500
1511
1501 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1512 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1502 tried to switch the profiling to using hotshot, but I'm getting
1513 tried to switch the profiling to using hotshot, but I'm getting
1503 strange errors from prof.runctx() there. I may be misreading the
1514 strange errors from prof.runctx() there. I may be misreading the
1504 docs, but it looks weird. For now the profiling code will
1515 docs, but it looks weird. For now the profiling code will
1505 continue to use the standard profiler.
1516 continue to use the standard profiler.
1506
1517
1507 2004-08-23 Fernando Perez <fperez@colorado.edu>
1518 2004-08-23 Fernando Perez <fperez@colorado.edu>
1508
1519
1509 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1520 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1510 threaded shell, by John Hunter. It's not quite ready yet, but
1521 threaded shell, by John Hunter. It's not quite ready yet, but
1511 close.
1522 close.
1512
1523
1513 2004-08-22 Fernando Perez <fperez@colorado.edu>
1524 2004-08-22 Fernando Perez <fperez@colorado.edu>
1514
1525
1515 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1526 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1516 in Magic and ultraTB.
1527 in Magic and ultraTB.
1517
1528
1518 * ipython.1: document threading options in manpage.
1529 * ipython.1: document threading options in manpage.
1519
1530
1520 * scripts/ipython: Changed name of -thread option to -gthread,
1531 * scripts/ipython: Changed name of -thread option to -gthread,
1521 since this is GTK specific. I want to leave the door open for a
1532 since this is GTK specific. I want to leave the door open for a
1522 -wthread option for WX, which will most likely be necessary. This
1533 -wthread option for WX, which will most likely be necessary. This
1523 change affects usage and ipmaker as well.
1534 change affects usage and ipmaker as well.
1524
1535
1525 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1536 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1526 handle the matplotlib shell issues. Code by John Hunter
1537 handle the matplotlib shell issues. Code by John Hunter
1527 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1538 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1528 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1539 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1529 broken (and disabled for end users) for now, but it puts the
1540 broken (and disabled for end users) for now, but it puts the
1530 infrastructure in place.
1541 infrastructure in place.
1531
1542
1532 2004-08-21 Fernando Perez <fperez@colorado.edu>
1543 2004-08-21 Fernando Perez <fperez@colorado.edu>
1533
1544
1534 * ipythonrc-pylab: Add matplotlib support.
1545 * ipythonrc-pylab: Add matplotlib support.
1535
1546
1536 * matplotlib_config.py: new files for matplotlib support, part of
1547 * matplotlib_config.py: new files for matplotlib support, part of
1537 the pylab profile.
1548 the pylab profile.
1538
1549
1539 * IPython/usage.py (__doc__): documented the threading options.
1550 * IPython/usage.py (__doc__): documented the threading options.
1540
1551
1541 2004-08-20 Fernando Perez <fperez@colorado.edu>
1552 2004-08-20 Fernando Perez <fperez@colorado.edu>
1542
1553
1543 * ipython: Modified the main calling routine to handle the -thread
1554 * ipython: Modified the main calling routine to handle the -thread
1544 and -mpthread options. This needs to be done as a top-level hack,
1555 and -mpthread options. This needs to be done as a top-level hack,
1545 because it determines which class to instantiate for IPython
1556 because it determines which class to instantiate for IPython
1546 itself.
1557 itself.
1547
1558
1548 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1559 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1549 classes to support multithreaded GTK operation without blocking,
1560 classes to support multithreaded GTK operation without blocking,
1550 and matplotlib with all backends. This is a lot of still very
1561 and matplotlib with all backends. This is a lot of still very
1551 experimental code, and threads are tricky. So it may still have a
1562 experimental code, and threads are tricky. So it may still have a
1552 few rough edges... This code owes a lot to
1563 few rough edges... This code owes a lot to
1553 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1564 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1554 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1565 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1555 to John Hunter for all the matplotlib work.
1566 to John Hunter for all the matplotlib work.
1556
1567
1557 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1568 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1558 options for gtk thread and matplotlib support.
1569 options for gtk thread and matplotlib support.
1559
1570
1560 2004-08-16 Fernando Perez <fperez@colorado.edu>
1571 2004-08-16 Fernando Perez <fperez@colorado.edu>
1561
1572
1562 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1573 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1563 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1574 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1564 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1575 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1565
1576
1566 2004-08-11 Fernando Perez <fperez@colorado.edu>
1577 2004-08-11 Fernando Perez <fperez@colorado.edu>
1567
1578
1568 * setup.py (isfile): Fix build so documentation gets updated for
1579 * setup.py (isfile): Fix build so documentation gets updated for
1569 rpms (it was only done for .tgz builds).
1580 rpms (it was only done for .tgz builds).
1570
1581
1571 2004-08-10 Fernando Perez <fperez@colorado.edu>
1582 2004-08-10 Fernando Perez <fperez@colorado.edu>
1572
1583
1573 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1584 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1574
1585
1575 * iplib.py : Silence syntax error exceptions in tab-completion.
1586 * iplib.py : Silence syntax error exceptions in tab-completion.
1576
1587
1577 2004-08-05 Fernando Perez <fperez@colorado.edu>
1588 2004-08-05 Fernando Perez <fperez@colorado.edu>
1578
1589
1579 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1590 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1580 'color off' mark for continuation prompts. This was causing long
1591 'color off' mark for continuation prompts. This was causing long
1581 continuation lines to mis-wrap.
1592 continuation lines to mis-wrap.
1582
1593
1583 2004-08-01 Fernando Perez <fperez@colorado.edu>
1594 2004-08-01 Fernando Perez <fperez@colorado.edu>
1584
1595
1585 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1596 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1586 for building ipython to be a parameter. All this is necessary
1597 for building ipython to be a parameter. All this is necessary
1587 right now to have a multithreaded version, but this insane
1598 right now to have a multithreaded version, but this insane
1588 non-design will be cleaned up soon. For now, it's a hack that
1599 non-design will be cleaned up soon. For now, it's a hack that
1589 works.
1600 works.
1590
1601
1591 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1602 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1592 args in various places. No bugs so far, but it's a dangerous
1603 args in various places. No bugs so far, but it's a dangerous
1593 practice.
1604 practice.
1594
1605
1595 2004-07-31 Fernando Perez <fperez@colorado.edu>
1606 2004-07-31 Fernando Perez <fperez@colorado.edu>
1596
1607
1597 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1608 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1598 fix completion of files with dots in their names under most
1609 fix completion of files with dots in their names under most
1599 profiles (pysh was OK because the completion order is different).
1610 profiles (pysh was OK because the completion order is different).
1600
1611
1601 2004-07-27 Fernando Perez <fperez@colorado.edu>
1612 2004-07-27 Fernando Perez <fperez@colorado.edu>
1602
1613
1603 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1614 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1604 keywords manually, b/c the one in keyword.py was removed in python
1615 keywords manually, b/c the one in keyword.py was removed in python
1605 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1616 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1606 This is NOT a bug under python 2.3 and earlier.
1617 This is NOT a bug under python 2.3 and earlier.
1607
1618
1608 2004-07-26 Fernando Perez <fperez@colorado.edu>
1619 2004-07-26 Fernando Perez <fperez@colorado.edu>
1609
1620
1610 * IPython/ultraTB.py (VerboseTB.text): Add another
1621 * IPython/ultraTB.py (VerboseTB.text): Add another
1611 linecache.checkcache() call to try to prevent inspect.py from
1622 linecache.checkcache() call to try to prevent inspect.py from
1612 crashing under python 2.3. I think this fixes
1623 crashing under python 2.3. I think this fixes
1613 http://www.scipy.net/roundup/ipython/issue17.
1624 http://www.scipy.net/roundup/ipython/issue17.
1614
1625
1615 2004-07-26 *** Released version 0.6.2
1626 2004-07-26 *** Released version 0.6.2
1616
1627
1617 2004-07-26 Fernando Perez <fperez@colorado.edu>
1628 2004-07-26 Fernando Perez <fperez@colorado.edu>
1618
1629
1619 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1630 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1620 fail for any number.
1631 fail for any number.
1621 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1632 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1622 empty bookmarks.
1633 empty bookmarks.
1623
1634
1624 2004-07-26 *** Released version 0.6.1
1635 2004-07-26 *** Released version 0.6.1
1625
1636
1626 2004-07-26 Fernando Perez <fperez@colorado.edu>
1637 2004-07-26 Fernando Perez <fperez@colorado.edu>
1627
1638
1628 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1639 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1629
1640
1630 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1641 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1631 escaping '()[]{}' in filenames.
1642 escaping '()[]{}' in filenames.
1632
1643
1633 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1644 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1634 Python 2.2 users who lack a proper shlex.split.
1645 Python 2.2 users who lack a proper shlex.split.
1635
1646
1636 2004-07-19 Fernando Perez <fperez@colorado.edu>
1647 2004-07-19 Fernando Perez <fperez@colorado.edu>
1637
1648
1638 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1649 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1639 for reading readline's init file. I follow the normal chain:
1650 for reading readline's init file. I follow the normal chain:
1640 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1651 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1641 report by Mike Heeter. This closes
1652 report by Mike Heeter. This closes
1642 http://www.scipy.net/roundup/ipython/issue16.
1653 http://www.scipy.net/roundup/ipython/issue16.
1643
1654
1644 2004-07-18 Fernando Perez <fperez@colorado.edu>
1655 2004-07-18 Fernando Perez <fperez@colorado.edu>
1645
1656
1646 * IPython/iplib.py (__init__): Add better handling of '\' under
1657 * IPython/iplib.py (__init__): Add better handling of '\' under
1647 Win32 for filenames. After a patch by Ville.
1658 Win32 for filenames. After a patch by Ville.
1648
1659
1649 2004-07-17 Fernando Perez <fperez@colorado.edu>
1660 2004-07-17 Fernando Perez <fperez@colorado.edu>
1650
1661
1651 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1662 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1652 autocalling would be triggered for 'foo is bar' if foo is
1663 autocalling would be triggered for 'foo is bar' if foo is
1653 callable. I also cleaned up the autocall detection code to use a
1664 callable. I also cleaned up the autocall detection code to use a
1654 regexp, which is faster. Bug reported by Alexander Schmolck.
1665 regexp, which is faster. Bug reported by Alexander Schmolck.
1655
1666
1656 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1667 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1657 '?' in them would confuse the help system. Reported by Alex
1668 '?' in them would confuse the help system. Reported by Alex
1658 Schmolck.
1669 Schmolck.
1659
1670
1660 2004-07-16 Fernando Perez <fperez@colorado.edu>
1671 2004-07-16 Fernando Perez <fperez@colorado.edu>
1661
1672
1662 * IPython/GnuplotInteractive.py (__all__): added plot2.
1673 * IPython/GnuplotInteractive.py (__all__): added plot2.
1663
1674
1664 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1675 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1665 plotting dictionaries, lists or tuples of 1d arrays.
1676 plotting dictionaries, lists or tuples of 1d arrays.
1666
1677
1667 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1678 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1668 optimizations.
1679 optimizations.
1669
1680
1670 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1681 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1671 the information which was there from Janko's original IPP code:
1682 the information which was there from Janko's original IPP code:
1672
1683
1673 03.05.99 20:53 porto.ifm.uni-kiel.de
1684 03.05.99 20:53 porto.ifm.uni-kiel.de
1674 --Started changelog.
1685 --Started changelog.
1675 --make clear do what it say it does
1686 --make clear do what it say it does
1676 --added pretty output of lines from inputcache
1687 --added pretty output of lines from inputcache
1677 --Made Logger a mixin class, simplifies handling of switches
1688 --Made Logger a mixin class, simplifies handling of switches
1678 --Added own completer class. .string<TAB> expands to last history
1689 --Added own completer class. .string<TAB> expands to last history
1679 line which starts with string. The new expansion is also present
1690 line which starts with string. The new expansion is also present
1680 with Ctrl-r from the readline library. But this shows, who this
1691 with Ctrl-r from the readline library. But this shows, who this
1681 can be done for other cases.
1692 can be done for other cases.
1682 --Added convention that all shell functions should accept a
1693 --Added convention that all shell functions should accept a
1683 parameter_string This opens the door for different behaviour for
1694 parameter_string This opens the door for different behaviour for
1684 each function. @cd is a good example of this.
1695 each function. @cd is a good example of this.
1685
1696
1686 04.05.99 12:12 porto.ifm.uni-kiel.de
1697 04.05.99 12:12 porto.ifm.uni-kiel.de
1687 --added logfile rotation
1698 --added logfile rotation
1688 --added new mainloop method which freezes first the namespace
1699 --added new mainloop method which freezes first the namespace
1689
1700
1690 07.05.99 21:24 porto.ifm.uni-kiel.de
1701 07.05.99 21:24 porto.ifm.uni-kiel.de
1691 --added the docreader classes. Now there is a help system.
1702 --added the docreader classes. Now there is a help system.
1692 -This is only a first try. Currently it's not easy to put new
1703 -This is only a first try. Currently it's not easy to put new
1693 stuff in the indices. But this is the way to go. Info would be
1704 stuff in the indices. But this is the way to go. Info would be
1694 better, but HTML is every where and not everybody has an info
1705 better, but HTML is every where and not everybody has an info
1695 system installed and it's not so easy to change html-docs to info.
1706 system installed and it's not so easy to change html-docs to info.
1696 --added global logfile option
1707 --added global logfile option
1697 --there is now a hook for object inspection method pinfo needs to
1708 --there is now a hook for object inspection method pinfo needs to
1698 be provided for this. Can be reached by two '??'.
1709 be provided for this. Can be reached by two '??'.
1699
1710
1700 08.05.99 20:51 porto.ifm.uni-kiel.de
1711 08.05.99 20:51 porto.ifm.uni-kiel.de
1701 --added a README
1712 --added a README
1702 --bug in rc file. Something has changed so functions in the rc
1713 --bug in rc file. Something has changed so functions in the rc
1703 file need to reference the shell and not self. Not clear if it's a
1714 file need to reference the shell and not self. Not clear if it's a
1704 bug or feature.
1715 bug or feature.
1705 --changed rc file for new behavior
1716 --changed rc file for new behavior
1706
1717
1707 2004-07-15 Fernando Perez <fperez@colorado.edu>
1718 2004-07-15 Fernando Perez <fperez@colorado.edu>
1708
1719
1709 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1720 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1710 cache was falling out of sync in bizarre manners when multi-line
1721 cache was falling out of sync in bizarre manners when multi-line
1711 input was present. Minor optimizations and cleanup.
1722 input was present. Minor optimizations and cleanup.
1712
1723
1713 (Logger): Remove old Changelog info for cleanup. This is the
1724 (Logger): Remove old Changelog info for cleanup. This is the
1714 information which was there from Janko's original code:
1725 information which was there from Janko's original code:
1715
1726
1716 Changes to Logger: - made the default log filename a parameter
1727 Changes to Logger: - made the default log filename a parameter
1717
1728
1718 - put a check for lines beginning with !@? in log(). Needed
1729 - put a check for lines beginning with !@? in log(). Needed
1719 (even if the handlers properly log their lines) for mid-session
1730 (even if the handlers properly log their lines) for mid-session
1720 logging activation to work properly. Without this, lines logged
1731 logging activation to work properly. Without this, lines logged
1721 in mid session, which get read from the cache, would end up
1732 in mid session, which get read from the cache, would end up
1722 'bare' (with !@? in the open) in the log. Now they are caught
1733 'bare' (with !@? in the open) in the log. Now they are caught
1723 and prepended with a #.
1734 and prepended with a #.
1724
1735
1725 * IPython/iplib.py (InteractiveShell.init_readline): added check
1736 * IPython/iplib.py (InteractiveShell.init_readline): added check
1726 in case MagicCompleter fails to be defined, so we don't crash.
1737 in case MagicCompleter fails to be defined, so we don't crash.
1727
1738
1728 2004-07-13 Fernando Perez <fperez@colorado.edu>
1739 2004-07-13 Fernando Perez <fperez@colorado.edu>
1729
1740
1730 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1741 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1731 of EPS if the requested filename ends in '.eps'.
1742 of EPS if the requested filename ends in '.eps'.
1732
1743
1733 2004-07-04 Fernando Perez <fperez@colorado.edu>
1744 2004-07-04 Fernando Perez <fperez@colorado.edu>
1734
1745
1735 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1746 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1736 escaping of quotes when calling the shell.
1747 escaping of quotes when calling the shell.
1737
1748
1738 2004-07-02 Fernando Perez <fperez@colorado.edu>
1749 2004-07-02 Fernando Perez <fperez@colorado.edu>
1739
1750
1740 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1751 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1741 gettext not working because we were clobbering '_'. Fixes
1752 gettext not working because we were clobbering '_'. Fixes
1742 http://www.scipy.net/roundup/ipython/issue6.
1753 http://www.scipy.net/roundup/ipython/issue6.
1743
1754
1744 2004-07-01 Fernando Perez <fperez@colorado.edu>
1755 2004-07-01 Fernando Perez <fperez@colorado.edu>
1745
1756
1746 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1757 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1747 into @cd. Patch by Ville.
1758 into @cd. Patch by Ville.
1748
1759
1749 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1760 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1750 new function to store things after ipmaker runs. Patch by Ville.
1761 new function to store things after ipmaker runs. Patch by Ville.
1751 Eventually this will go away once ipmaker is removed and the class
1762 Eventually this will go away once ipmaker is removed and the class
1752 gets cleaned up, but for now it's ok. Key functionality here is
1763 gets cleaned up, but for now it's ok. Key functionality here is
1753 the addition of the persistent storage mechanism, a dict for
1764 the addition of the persistent storage mechanism, a dict for
1754 keeping data across sessions (for now just bookmarks, but more can
1765 keeping data across sessions (for now just bookmarks, but more can
1755 be implemented later).
1766 be implemented later).
1756
1767
1757 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1768 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1758 persistent across sections. Patch by Ville, I modified it
1769 persistent across sections. Patch by Ville, I modified it
1759 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1770 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1760 added a '-l' option to list all bookmarks.
1771 added a '-l' option to list all bookmarks.
1761
1772
1762 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1773 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1763 center for cleanup. Registered with atexit.register(). I moved
1774 center for cleanup. Registered with atexit.register(). I moved
1764 here the old exit_cleanup(). After a patch by Ville.
1775 here the old exit_cleanup(). After a patch by Ville.
1765
1776
1766 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1777 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1767 characters in the hacked shlex_split for python 2.2.
1778 characters in the hacked shlex_split for python 2.2.
1768
1779
1769 * IPython/iplib.py (file_matches): more fixes to filenames with
1780 * IPython/iplib.py (file_matches): more fixes to filenames with
1770 whitespace in them. It's not perfect, but limitations in python's
1781 whitespace in them. It's not perfect, but limitations in python's
1771 readline make it impossible to go further.
1782 readline make it impossible to go further.
1772
1783
1773 2004-06-29 Fernando Perez <fperez@colorado.edu>
1784 2004-06-29 Fernando Perez <fperez@colorado.edu>
1774
1785
1775 * IPython/iplib.py (file_matches): escape whitespace correctly in
1786 * IPython/iplib.py (file_matches): escape whitespace correctly in
1776 filename completions. Bug reported by Ville.
1787 filename completions. Bug reported by Ville.
1777
1788
1778 2004-06-28 Fernando Perez <fperez@colorado.edu>
1789 2004-06-28 Fernando Perez <fperez@colorado.edu>
1779
1790
1780 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1791 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1781 the history file will be called 'history-PROFNAME' (or just
1792 the history file will be called 'history-PROFNAME' (or just
1782 'history' if no profile is loaded). I was getting annoyed at
1793 'history' if no profile is loaded). I was getting annoyed at
1783 getting my Numerical work history clobbered by pysh sessions.
1794 getting my Numerical work history clobbered by pysh sessions.
1784
1795
1785 * IPython/iplib.py (InteractiveShell.__init__): Internal
1796 * IPython/iplib.py (InteractiveShell.__init__): Internal
1786 getoutputerror() function so that we can honor the system_verbose
1797 getoutputerror() function so that we can honor the system_verbose
1787 flag for _all_ system calls. I also added escaping of #
1798 flag for _all_ system calls. I also added escaping of #
1788 characters here to avoid confusing Itpl.
1799 characters here to avoid confusing Itpl.
1789
1800
1790 * IPython/Magic.py (shlex_split): removed call to shell in
1801 * IPython/Magic.py (shlex_split): removed call to shell in
1791 parse_options and replaced it with shlex.split(). The annoying
1802 parse_options and replaced it with shlex.split(). The annoying
1792 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1803 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1793 to backport it from 2.3, with several frail hacks (the shlex
1804 to backport it from 2.3, with several frail hacks (the shlex
1794 module is rather limited in 2.2). Thanks to a suggestion by Ville
1805 module is rather limited in 2.2). Thanks to a suggestion by Ville
1795 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1806 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1796 problem.
1807 problem.
1797
1808
1798 (Magic.magic_system_verbose): new toggle to print the actual
1809 (Magic.magic_system_verbose): new toggle to print the actual
1799 system calls made by ipython. Mainly for debugging purposes.
1810 system calls made by ipython. Mainly for debugging purposes.
1800
1811
1801 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1812 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1802 doesn't support persistence. Reported (and fix suggested) by
1813 doesn't support persistence. Reported (and fix suggested) by
1803 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1814 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1804
1815
1805 2004-06-26 Fernando Perez <fperez@colorado.edu>
1816 2004-06-26 Fernando Perez <fperez@colorado.edu>
1806
1817
1807 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1818 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1808 continue prompts.
1819 continue prompts.
1809
1820
1810 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1821 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1811 function (basically a big docstring) and a few more things here to
1822 function (basically a big docstring) and a few more things here to
1812 speedup startup. pysh.py is now very lightweight. We want because
1823 speedup startup. pysh.py is now very lightweight. We want because
1813 it gets execfile'd, while InterpreterExec gets imported, so
1824 it gets execfile'd, while InterpreterExec gets imported, so
1814 byte-compilation saves time.
1825 byte-compilation saves time.
1815
1826
1816 2004-06-25 Fernando Perez <fperez@colorado.edu>
1827 2004-06-25 Fernando Perez <fperez@colorado.edu>
1817
1828
1818 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1829 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1819 -NUM', which was recently broken.
1830 -NUM', which was recently broken.
1820
1831
1821 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1832 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1822 in multi-line input (but not !!, which doesn't make sense there).
1833 in multi-line input (but not !!, which doesn't make sense there).
1823
1834
1824 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1835 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1825 It's just too useful, and people can turn it off in the less
1836 It's just too useful, and people can turn it off in the less
1826 common cases where it's a problem.
1837 common cases where it's a problem.
1827
1838
1828 2004-06-24 Fernando Perez <fperez@colorado.edu>
1839 2004-06-24 Fernando Perez <fperez@colorado.edu>
1829
1840
1830 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1841 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1831 special syntaxes (like alias calling) is now allied in multi-line
1842 special syntaxes (like alias calling) is now allied in multi-line
1832 input. This is still _very_ experimental, but it's necessary for
1843 input. This is still _very_ experimental, but it's necessary for
1833 efficient shell usage combining python looping syntax with system
1844 efficient shell usage combining python looping syntax with system
1834 calls. For now it's restricted to aliases, I don't think it
1845 calls. For now it's restricted to aliases, I don't think it
1835 really even makes sense to have this for magics.
1846 really even makes sense to have this for magics.
1836
1847
1837 2004-06-23 Fernando Perez <fperez@colorado.edu>
1848 2004-06-23 Fernando Perez <fperez@colorado.edu>
1838
1849
1839 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1850 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1840 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1851 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1841
1852
1842 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1853 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1843 extensions under Windows (after code sent by Gary Bishop). The
1854 extensions under Windows (after code sent by Gary Bishop). The
1844 extensions considered 'executable' are stored in IPython's rc
1855 extensions considered 'executable' are stored in IPython's rc
1845 structure as win_exec_ext.
1856 structure as win_exec_ext.
1846
1857
1847 * IPython/genutils.py (shell): new function, like system() but
1858 * IPython/genutils.py (shell): new function, like system() but
1848 without return value. Very useful for interactive shell work.
1859 without return value. Very useful for interactive shell work.
1849
1860
1850 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1861 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1851 delete aliases.
1862 delete aliases.
1852
1863
1853 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1864 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1854 sure that the alias table doesn't contain python keywords.
1865 sure that the alias table doesn't contain python keywords.
1855
1866
1856 2004-06-21 Fernando Perez <fperez@colorado.edu>
1867 2004-06-21 Fernando Perez <fperez@colorado.edu>
1857
1868
1858 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1869 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1859 non-existent items are found in $PATH. Reported by Thorsten.
1870 non-existent items are found in $PATH. Reported by Thorsten.
1860
1871
1861 2004-06-20 Fernando Perez <fperez@colorado.edu>
1872 2004-06-20 Fernando Perez <fperez@colorado.edu>
1862
1873
1863 * IPython/iplib.py (complete): modified the completer so that the
1874 * IPython/iplib.py (complete): modified the completer so that the
1864 order of priorities can be easily changed at runtime.
1875 order of priorities can be easily changed at runtime.
1865
1876
1866 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1877 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1867 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1878 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1868
1879
1869 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1880 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1870 expand Python variables prepended with $ in all system calls. The
1881 expand Python variables prepended with $ in all system calls. The
1871 same was done to InteractiveShell.handle_shell_escape. Now all
1882 same was done to InteractiveShell.handle_shell_escape. Now all
1872 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1883 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1873 expansion of python variables and expressions according to the
1884 expansion of python variables and expressions according to the
1874 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1885 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1875
1886
1876 Though PEP-215 has been rejected, a similar (but simpler) one
1887 Though PEP-215 has been rejected, a similar (but simpler) one
1877 seems like it will go into Python 2.4, PEP-292 -
1888 seems like it will go into Python 2.4, PEP-292 -
1878 http://www.python.org/peps/pep-0292.html.
1889 http://www.python.org/peps/pep-0292.html.
1879
1890
1880 I'll keep the full syntax of PEP-215, since IPython has since the
1891 I'll keep the full syntax of PEP-215, since IPython has since the
1881 start used Ka-Ping Yee's reference implementation discussed there
1892 start used Ka-Ping Yee's reference implementation discussed there
1882 (Itpl), and I actually like the powerful semantics it offers.
1893 (Itpl), and I actually like the powerful semantics it offers.
1883
1894
1884 In order to access normal shell variables, the $ has to be escaped
1895 In order to access normal shell variables, the $ has to be escaped
1885 via an extra $. For example:
1896 via an extra $. For example:
1886
1897
1887 In [7]: PATH='a python variable'
1898 In [7]: PATH='a python variable'
1888
1899
1889 In [8]: !echo $PATH
1900 In [8]: !echo $PATH
1890 a python variable
1901 a python variable
1891
1902
1892 In [9]: !echo $$PATH
1903 In [9]: !echo $$PATH
1893 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1904 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1894
1905
1895 (Magic.parse_options): escape $ so the shell doesn't evaluate
1906 (Magic.parse_options): escape $ so the shell doesn't evaluate
1896 things prematurely.
1907 things prematurely.
1897
1908
1898 * IPython/iplib.py (InteractiveShell.call_alias): added the
1909 * IPython/iplib.py (InteractiveShell.call_alias): added the
1899 ability for aliases to expand python variables via $.
1910 ability for aliases to expand python variables via $.
1900
1911
1901 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1912 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1902 system, now there's a @rehash/@rehashx pair of magics. These work
1913 system, now there's a @rehash/@rehashx pair of magics. These work
1903 like the csh rehash command, and can be invoked at any time. They
1914 like the csh rehash command, and can be invoked at any time. They
1904 build a table of aliases to everything in the user's $PATH
1915 build a table of aliases to everything in the user's $PATH
1905 (@rehash uses everything, @rehashx is slower but only adds
1916 (@rehash uses everything, @rehashx is slower but only adds
1906 executable files). With this, the pysh.py-based shell profile can
1917 executable files). With this, the pysh.py-based shell profile can
1907 now simply call rehash upon startup, and full access to all
1918 now simply call rehash upon startup, and full access to all
1908 programs in the user's path is obtained.
1919 programs in the user's path is obtained.
1909
1920
1910 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1921 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1911 functionality is now fully in place. I removed the old dynamic
1922 functionality is now fully in place. I removed the old dynamic
1912 code generation based approach, in favor of a much lighter one
1923 code generation based approach, in favor of a much lighter one
1913 based on a simple dict. The advantage is that this allows me to
1924 based on a simple dict. The advantage is that this allows me to
1914 now have thousands of aliases with negligible cost (unthinkable
1925 now have thousands of aliases with negligible cost (unthinkable
1915 with the old system).
1926 with the old system).
1916
1927
1917 2004-06-19 Fernando Perez <fperez@colorado.edu>
1928 2004-06-19 Fernando Perez <fperez@colorado.edu>
1918
1929
1919 * IPython/iplib.py (__init__): extended MagicCompleter class to
1930 * IPython/iplib.py (__init__): extended MagicCompleter class to
1920 also complete (last in priority) on user aliases.
1931 also complete (last in priority) on user aliases.
1921
1932
1922 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1933 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1923 call to eval.
1934 call to eval.
1924 (ItplNS.__init__): Added a new class which functions like Itpl,
1935 (ItplNS.__init__): Added a new class which functions like Itpl,
1925 but allows configuring the namespace for the evaluation to occur
1936 but allows configuring the namespace for the evaluation to occur
1926 in.
1937 in.
1927
1938
1928 2004-06-18 Fernando Perez <fperez@colorado.edu>
1939 2004-06-18 Fernando Perez <fperez@colorado.edu>
1929
1940
1930 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1941 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1931 better message when 'exit' or 'quit' are typed (a common newbie
1942 better message when 'exit' or 'quit' are typed (a common newbie
1932 confusion).
1943 confusion).
1933
1944
1934 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1945 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1935 check for Windows users.
1946 check for Windows users.
1936
1947
1937 * IPython/iplib.py (InteractiveShell.user_setup): removed
1948 * IPython/iplib.py (InteractiveShell.user_setup): removed
1938 disabling of colors for Windows. I'll test at runtime and issue a
1949 disabling of colors for Windows. I'll test at runtime and issue a
1939 warning if Gary's readline isn't found, as to nudge users to
1950 warning if Gary's readline isn't found, as to nudge users to
1940 download it.
1951 download it.
1941
1952
1942 2004-06-16 Fernando Perez <fperez@colorado.edu>
1953 2004-06-16 Fernando Perez <fperez@colorado.edu>
1943
1954
1944 * IPython/genutils.py (Stream.__init__): changed to print errors
1955 * IPython/genutils.py (Stream.__init__): changed to print errors
1945 to sys.stderr. I had a circular dependency here. Now it's
1956 to sys.stderr. I had a circular dependency here. Now it's
1946 possible to run ipython as IDLE's shell (consider this pre-alpha,
1957 possible to run ipython as IDLE's shell (consider this pre-alpha,
1947 since true stdout things end up in the starting terminal instead
1958 since true stdout things end up in the starting terminal instead
1948 of IDLE's out).
1959 of IDLE's out).
1949
1960
1950 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1961 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1951 users who haven't # updated their prompt_in2 definitions. Remove
1962 users who haven't # updated their prompt_in2 definitions. Remove
1952 eventually.
1963 eventually.
1953 (multiple_replace): added credit to original ASPN recipe.
1964 (multiple_replace): added credit to original ASPN recipe.
1954
1965
1955 2004-06-15 Fernando Perez <fperez@colorado.edu>
1966 2004-06-15 Fernando Perez <fperez@colorado.edu>
1956
1967
1957 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1968 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1958 list of auto-defined aliases.
1969 list of auto-defined aliases.
1959
1970
1960 2004-06-13 Fernando Perez <fperez@colorado.edu>
1971 2004-06-13 Fernando Perez <fperez@colorado.edu>
1961
1972
1962 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1973 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1963 install was really requested (so setup.py can be used for other
1974 install was really requested (so setup.py can be used for other
1964 things under Windows).
1975 things under Windows).
1965
1976
1966 2004-06-10 Fernando Perez <fperez@colorado.edu>
1977 2004-06-10 Fernando Perez <fperez@colorado.edu>
1967
1978
1968 * IPython/Logger.py (Logger.create_log): Manually remove any old
1979 * IPython/Logger.py (Logger.create_log): Manually remove any old
1969 backup, since os.remove may fail under Windows. Fixes bug
1980 backup, since os.remove may fail under Windows. Fixes bug
1970 reported by Thorsten.
1981 reported by Thorsten.
1971
1982
1972 2004-06-09 Fernando Perez <fperez@colorado.edu>
1983 2004-06-09 Fernando Perez <fperez@colorado.edu>
1973
1984
1974 * examples/example-embed.py: fixed all references to %n (replaced
1985 * examples/example-embed.py: fixed all references to %n (replaced
1975 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1986 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1976 for all examples and the manual as well.
1987 for all examples and the manual as well.
1977
1988
1978 2004-06-08 Fernando Perez <fperez@colorado.edu>
1989 2004-06-08 Fernando Perez <fperez@colorado.edu>
1979
1990
1980 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1991 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1981 alignment and color management. All 3 prompt subsystems now
1992 alignment and color management. All 3 prompt subsystems now
1982 inherit from BasePrompt.
1993 inherit from BasePrompt.
1983
1994
1984 * tools/release: updates for windows installer build and tag rpms
1995 * tools/release: updates for windows installer build and tag rpms
1985 with python version (since paths are fixed).
1996 with python version (since paths are fixed).
1986
1997
1987 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1998 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1988 which will become eventually obsolete. Also fixed the default
1999 which will become eventually obsolete. Also fixed the default
1989 prompt_in2 to use \D, so at least new users start with the correct
2000 prompt_in2 to use \D, so at least new users start with the correct
1990 defaults.
2001 defaults.
1991 WARNING: Users with existing ipythonrc files will need to apply
2002 WARNING: Users with existing ipythonrc files will need to apply
1992 this fix manually!
2003 this fix manually!
1993
2004
1994 * setup.py: make windows installer (.exe). This is finally the
2005 * setup.py: make windows installer (.exe). This is finally the
1995 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2006 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1996 which I hadn't included because it required Python 2.3 (or recent
2007 which I hadn't included because it required Python 2.3 (or recent
1997 distutils).
2008 distutils).
1998
2009
1999 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2010 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2000 usage of new '\D' escape.
2011 usage of new '\D' escape.
2001
2012
2002 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2013 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2003 lacks os.getuid())
2014 lacks os.getuid())
2004 (CachedOutput.set_colors): Added the ability to turn coloring
2015 (CachedOutput.set_colors): Added the ability to turn coloring
2005 on/off with @colors even for manually defined prompt colors. It
2016 on/off with @colors even for manually defined prompt colors. It
2006 uses a nasty global, but it works safely and via the generic color
2017 uses a nasty global, but it works safely and via the generic color
2007 handling mechanism.
2018 handling mechanism.
2008 (Prompt2.__init__): Introduced new escape '\D' for continuation
2019 (Prompt2.__init__): Introduced new escape '\D' for continuation
2009 prompts. It represents the counter ('\#') as dots.
2020 prompts. It represents the counter ('\#') as dots.
2010 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2021 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2011 need to update their ipythonrc files and replace '%n' with '\D' in
2022 need to update their ipythonrc files and replace '%n' with '\D' in
2012 their prompt_in2 settings everywhere. Sorry, but there's
2023 their prompt_in2 settings everywhere. Sorry, but there's
2013 otherwise no clean way to get all prompts to properly align. The
2024 otherwise no clean way to get all prompts to properly align. The
2014 ipythonrc shipped with IPython has been updated.
2025 ipythonrc shipped with IPython has been updated.
2015
2026
2016 2004-06-07 Fernando Perez <fperez@colorado.edu>
2027 2004-06-07 Fernando Perez <fperez@colorado.edu>
2017
2028
2018 * setup.py (isfile): Pass local_icons option to latex2html, so the
2029 * setup.py (isfile): Pass local_icons option to latex2html, so the
2019 resulting HTML file is self-contained. Thanks to
2030 resulting HTML file is self-contained. Thanks to
2020 dryice-AT-liu.com.cn for the tip.
2031 dryice-AT-liu.com.cn for the tip.
2021
2032
2022 * pysh.py: I created a new profile 'shell', which implements a
2033 * pysh.py: I created a new profile 'shell', which implements a
2023 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2034 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2024 system shell, nor will it become one anytime soon. It's mainly
2035 system shell, nor will it become one anytime soon. It's mainly
2025 meant to illustrate the use of the new flexible bash-like prompts.
2036 meant to illustrate the use of the new flexible bash-like prompts.
2026 I guess it could be used by hardy souls for true shell management,
2037 I guess it could be used by hardy souls for true shell management,
2027 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2038 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2028 profile. This uses the InterpreterExec extension provided by
2039 profile. This uses the InterpreterExec extension provided by
2029 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2040 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2030
2041
2031 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2042 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2032 auto-align itself with the length of the previous input prompt
2043 auto-align itself with the length of the previous input prompt
2033 (taking into account the invisible color escapes).
2044 (taking into account the invisible color escapes).
2034 (CachedOutput.__init__): Large restructuring of this class. Now
2045 (CachedOutput.__init__): Large restructuring of this class. Now
2035 all three prompts (primary1, primary2, output) are proper objects,
2046 all three prompts (primary1, primary2, output) are proper objects,
2036 managed by the 'parent' CachedOutput class. The code is still a
2047 managed by the 'parent' CachedOutput class. The code is still a
2037 bit hackish (all prompts share state via a pointer to the cache),
2048 bit hackish (all prompts share state via a pointer to the cache),
2038 but it's overall far cleaner than before.
2049 but it's overall far cleaner than before.
2039
2050
2040 * IPython/genutils.py (getoutputerror): modified to add verbose,
2051 * IPython/genutils.py (getoutputerror): modified to add verbose,
2041 debug and header options. This makes the interface of all getout*
2052 debug and header options. This makes the interface of all getout*
2042 functions uniform.
2053 functions uniform.
2043 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2054 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2044
2055
2045 * IPython/Magic.py (Magic.default_option): added a function to
2056 * IPython/Magic.py (Magic.default_option): added a function to
2046 allow registering default options for any magic command. This
2057 allow registering default options for any magic command. This
2047 makes it easy to have profiles which customize the magics globally
2058 makes it easy to have profiles which customize the magics globally
2048 for a certain use. The values set through this function are
2059 for a certain use. The values set through this function are
2049 picked up by the parse_options() method, which all magics should
2060 picked up by the parse_options() method, which all magics should
2050 use to parse their options.
2061 use to parse their options.
2051
2062
2052 * IPython/genutils.py (warn): modified the warnings framework to
2063 * IPython/genutils.py (warn): modified the warnings framework to
2053 use the Term I/O class. I'm trying to slowly unify all of
2064 use the Term I/O class. I'm trying to slowly unify all of
2054 IPython's I/O operations to pass through Term.
2065 IPython's I/O operations to pass through Term.
2055
2066
2056 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2067 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2057 the secondary prompt to correctly match the length of the primary
2068 the secondary prompt to correctly match the length of the primary
2058 one for any prompt. Now multi-line code will properly line up
2069 one for any prompt. Now multi-line code will properly line up
2059 even for path dependent prompts, such as the new ones available
2070 even for path dependent prompts, such as the new ones available
2060 via the prompt_specials.
2071 via the prompt_specials.
2061
2072
2062 2004-06-06 Fernando Perez <fperez@colorado.edu>
2073 2004-06-06 Fernando Perez <fperez@colorado.edu>
2063
2074
2064 * IPython/Prompts.py (prompt_specials): Added the ability to have
2075 * IPython/Prompts.py (prompt_specials): Added the ability to have
2065 bash-like special sequences in the prompts, which get
2076 bash-like special sequences in the prompts, which get
2066 automatically expanded. Things like hostname, current working
2077 automatically expanded. Things like hostname, current working
2067 directory and username are implemented already, but it's easy to
2078 directory and username are implemented already, but it's easy to
2068 add more in the future. Thanks to a patch by W.J. van der Laan
2079 add more in the future. Thanks to a patch by W.J. van der Laan
2069 <gnufnork-AT-hetdigitalegat.nl>
2080 <gnufnork-AT-hetdigitalegat.nl>
2070 (prompt_specials): Added color support for prompt strings, so
2081 (prompt_specials): Added color support for prompt strings, so
2071 users can define arbitrary color setups for their prompts.
2082 users can define arbitrary color setups for their prompts.
2072
2083
2073 2004-06-05 Fernando Perez <fperez@colorado.edu>
2084 2004-06-05 Fernando Perez <fperez@colorado.edu>
2074
2085
2075 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2086 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2076 code to load Gary Bishop's readline and configure it
2087 code to load Gary Bishop's readline and configure it
2077 automatically. Thanks to Gary for help on this.
2088 automatically. Thanks to Gary for help on this.
2078
2089
2079 2004-06-01 Fernando Perez <fperez@colorado.edu>
2090 2004-06-01 Fernando Perez <fperez@colorado.edu>
2080
2091
2081 * IPython/Logger.py (Logger.create_log): fix bug for logging
2092 * IPython/Logger.py (Logger.create_log): fix bug for logging
2082 with no filename (previous fix was incomplete).
2093 with no filename (previous fix was incomplete).
2083
2094
2084 2004-05-25 Fernando Perez <fperez@colorado.edu>
2095 2004-05-25 Fernando Perez <fperez@colorado.edu>
2085
2096
2086 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2097 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2087 parens would get passed to the shell.
2098 parens would get passed to the shell.
2088
2099
2089 2004-05-20 Fernando Perez <fperez@colorado.edu>
2100 2004-05-20 Fernando Perez <fperez@colorado.edu>
2090
2101
2091 * IPython/Magic.py (Magic.magic_prun): changed default profile
2102 * IPython/Magic.py (Magic.magic_prun): changed default profile
2092 sort order to 'time' (the more common profiling need).
2103 sort order to 'time' (the more common profiling need).
2093
2104
2094 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2105 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2095 so that source code shown is guaranteed in sync with the file on
2106 so that source code shown is guaranteed in sync with the file on
2096 disk (also changed in psource). Similar fix to the one for
2107 disk (also changed in psource). Similar fix to the one for
2097 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2108 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2098 <yann.ledu-AT-noos.fr>.
2109 <yann.ledu-AT-noos.fr>.
2099
2110
2100 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2111 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2101 with a single option would not be correctly parsed. Closes
2112 with a single option would not be correctly parsed. Closes
2102 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2113 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2103 introduced in 0.6.0 (on 2004-05-06).
2114 introduced in 0.6.0 (on 2004-05-06).
2104
2115
2105 2004-05-13 *** Released version 0.6.0
2116 2004-05-13 *** Released version 0.6.0
2106
2117
2107 2004-05-13 Fernando Perez <fperez@colorado.edu>
2118 2004-05-13 Fernando Perez <fperez@colorado.edu>
2108
2119
2109 * debian/: Added debian/ directory to CVS, so that debian support
2120 * debian/: Added debian/ directory to CVS, so that debian support
2110 is publicly accessible. The debian package is maintained by Jack
2121 is publicly accessible. The debian package is maintained by Jack
2111 Moffit <jack-AT-xiph.org>.
2122 Moffit <jack-AT-xiph.org>.
2112
2123
2113 * Documentation: included the notes about an ipython-based system
2124 * Documentation: included the notes about an ipython-based system
2114 shell (the hypothetical 'pysh') into the new_design.pdf document,
2125 shell (the hypothetical 'pysh') into the new_design.pdf document,
2115 so that these ideas get distributed to users along with the
2126 so that these ideas get distributed to users along with the
2116 official documentation.
2127 official documentation.
2117
2128
2118 2004-05-10 Fernando Perez <fperez@colorado.edu>
2129 2004-05-10 Fernando Perez <fperez@colorado.edu>
2119
2130
2120 * IPython/Logger.py (Logger.create_log): fix recently introduced
2131 * IPython/Logger.py (Logger.create_log): fix recently introduced
2121 bug (misindented line) where logstart would fail when not given an
2132 bug (misindented line) where logstart would fail when not given an
2122 explicit filename.
2133 explicit filename.
2123
2134
2124 2004-05-09 Fernando Perez <fperez@colorado.edu>
2135 2004-05-09 Fernando Perez <fperez@colorado.edu>
2125
2136
2126 * IPython/Magic.py (Magic.parse_options): skip system call when
2137 * IPython/Magic.py (Magic.parse_options): skip system call when
2127 there are no options to look for. Faster, cleaner for the common
2138 there are no options to look for. Faster, cleaner for the common
2128 case.
2139 case.
2129
2140
2130 * Documentation: many updates to the manual: describing Windows
2141 * Documentation: many updates to the manual: describing Windows
2131 support better, Gnuplot updates, credits, misc small stuff. Also
2142 support better, Gnuplot updates, credits, misc small stuff. Also
2132 updated the new_design doc a bit.
2143 updated the new_design doc a bit.
2133
2144
2134 2004-05-06 *** Released version 0.6.0.rc1
2145 2004-05-06 *** Released version 0.6.0.rc1
2135
2146
2136 2004-05-06 Fernando Perez <fperez@colorado.edu>
2147 2004-05-06 Fernando Perez <fperez@colorado.edu>
2137
2148
2138 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2149 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2139 operations to use the vastly more efficient list/''.join() method.
2150 operations to use the vastly more efficient list/''.join() method.
2140 (FormattedTB.text): Fix
2151 (FormattedTB.text): Fix
2141 http://www.scipy.net/roundup/ipython/issue12 - exception source
2152 http://www.scipy.net/roundup/ipython/issue12 - exception source
2142 extract not updated after reload. Thanks to Mike Salib
2153 extract not updated after reload. Thanks to Mike Salib
2143 <msalib-AT-mit.edu> for pinning the source of the problem.
2154 <msalib-AT-mit.edu> for pinning the source of the problem.
2144 Fortunately, the solution works inside ipython and doesn't require
2155 Fortunately, the solution works inside ipython and doesn't require
2145 any changes to python proper.
2156 any changes to python proper.
2146
2157
2147 * IPython/Magic.py (Magic.parse_options): Improved to process the
2158 * IPython/Magic.py (Magic.parse_options): Improved to process the
2148 argument list as a true shell would (by actually using the
2159 argument list as a true shell would (by actually using the
2149 underlying system shell). This way, all @magics automatically get
2160 underlying system shell). This way, all @magics automatically get
2150 shell expansion for variables. Thanks to a comment by Alex
2161 shell expansion for variables. Thanks to a comment by Alex
2151 Schmolck.
2162 Schmolck.
2152
2163
2153 2004-04-04 Fernando Perez <fperez@colorado.edu>
2164 2004-04-04 Fernando Perez <fperez@colorado.edu>
2154
2165
2155 * IPython/iplib.py (InteractiveShell.interact): Added a special
2166 * IPython/iplib.py (InteractiveShell.interact): Added a special
2156 trap for a debugger quit exception, which is basically impossible
2167 trap for a debugger quit exception, which is basically impossible
2157 to handle by normal mechanisms, given what pdb does to the stack.
2168 to handle by normal mechanisms, given what pdb does to the stack.
2158 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2169 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2159
2170
2160 2004-04-03 Fernando Perez <fperez@colorado.edu>
2171 2004-04-03 Fernando Perez <fperez@colorado.edu>
2161
2172
2162 * IPython/genutils.py (Term): Standardized the names of the Term
2173 * IPython/genutils.py (Term): Standardized the names of the Term
2163 class streams to cin/cout/cerr, following C++ naming conventions
2174 class streams to cin/cout/cerr, following C++ naming conventions
2164 (I can't use in/out/err because 'in' is not a valid attribute
2175 (I can't use in/out/err because 'in' is not a valid attribute
2165 name).
2176 name).
2166
2177
2167 * IPython/iplib.py (InteractiveShell.interact): don't increment
2178 * IPython/iplib.py (InteractiveShell.interact): don't increment
2168 the prompt if there's no user input. By Daniel 'Dang' Griffith
2179 the prompt if there's no user input. By Daniel 'Dang' Griffith
2169 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2180 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2170 Francois Pinard.
2181 Francois Pinard.
2171
2182
2172 2004-04-02 Fernando Perez <fperez@colorado.edu>
2183 2004-04-02 Fernando Perez <fperez@colorado.edu>
2173
2184
2174 * IPython/genutils.py (Stream.__init__): Modified to survive at
2185 * IPython/genutils.py (Stream.__init__): Modified to survive at
2175 least importing in contexts where stdin/out/err aren't true file
2186 least importing in contexts where stdin/out/err aren't true file
2176 objects, such as PyCrust (they lack fileno() and mode). However,
2187 objects, such as PyCrust (they lack fileno() and mode). However,
2177 the recovery facilities which rely on these things existing will
2188 the recovery facilities which rely on these things existing will
2178 not work.
2189 not work.
2179
2190
2180 2004-04-01 Fernando Perez <fperez@colorado.edu>
2191 2004-04-01 Fernando Perez <fperez@colorado.edu>
2181
2192
2182 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2193 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2183 use the new getoutputerror() function, so it properly
2194 use the new getoutputerror() function, so it properly
2184 distinguishes stdout/err.
2195 distinguishes stdout/err.
2185
2196
2186 * IPython/genutils.py (getoutputerror): added a function to
2197 * IPython/genutils.py (getoutputerror): added a function to
2187 capture separately the standard output and error of a command.
2198 capture separately the standard output and error of a command.
2188 After a comment from dang on the mailing lists. This code is
2199 After a comment from dang on the mailing lists. This code is
2189 basically a modified version of commands.getstatusoutput(), from
2200 basically a modified version of commands.getstatusoutput(), from
2190 the standard library.
2201 the standard library.
2191
2202
2192 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2203 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2193 '!!' as a special syntax (shorthand) to access @sx.
2204 '!!' as a special syntax (shorthand) to access @sx.
2194
2205
2195 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2206 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2196 command and return its output as a list split on '\n'.
2207 command and return its output as a list split on '\n'.
2197
2208
2198 2004-03-31 Fernando Perez <fperez@colorado.edu>
2209 2004-03-31 Fernando Perez <fperez@colorado.edu>
2199
2210
2200 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2211 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2201 method to dictionaries used as FakeModule instances if they lack
2212 method to dictionaries used as FakeModule instances if they lack
2202 it. At least pydoc in python2.3 breaks for runtime-defined
2213 it. At least pydoc in python2.3 breaks for runtime-defined
2203 functions without this hack. At some point I need to _really_
2214 functions without this hack. At some point I need to _really_
2204 understand what FakeModule is doing, because it's a gross hack.
2215 understand what FakeModule is doing, because it's a gross hack.
2205 But it solves Arnd's problem for now...
2216 But it solves Arnd's problem for now...
2206
2217
2207 2004-02-27 Fernando Perez <fperez@colorado.edu>
2218 2004-02-27 Fernando Perez <fperez@colorado.edu>
2208
2219
2209 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2220 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2210 mode would behave erratically. Also increased the number of
2221 mode would behave erratically. Also increased the number of
2211 possible logs in rotate mod to 999. Thanks to Rod Holland
2222 possible logs in rotate mod to 999. Thanks to Rod Holland
2212 <rhh@StructureLABS.com> for the report and fixes.
2223 <rhh@StructureLABS.com> for the report and fixes.
2213
2224
2214 2004-02-26 Fernando Perez <fperez@colorado.edu>
2225 2004-02-26 Fernando Perez <fperez@colorado.edu>
2215
2226
2216 * IPython/genutils.py (page): Check that the curses module really
2227 * IPython/genutils.py (page): Check that the curses module really
2217 has the initscr attribute before trying to use it. For some
2228 has the initscr attribute before trying to use it. For some
2218 reason, the Solaris curses module is missing this. I think this
2229 reason, the Solaris curses module is missing this. I think this
2219 should be considered a Solaris python bug, but I'm not sure.
2230 should be considered a Solaris python bug, but I'm not sure.
2220
2231
2221 2004-01-17 Fernando Perez <fperez@colorado.edu>
2232 2004-01-17 Fernando Perez <fperez@colorado.edu>
2222
2233
2223 * IPython/genutils.py (Stream.__init__): Changes to try to make
2234 * IPython/genutils.py (Stream.__init__): Changes to try to make
2224 ipython robust against stdin/out/err being closed by the user.
2235 ipython robust against stdin/out/err being closed by the user.
2225 This is 'user error' (and blocks a normal python session, at least
2236 This is 'user error' (and blocks a normal python session, at least
2226 the stdout case). However, Ipython should be able to survive such
2237 the stdout case). However, Ipython should be able to survive such
2227 instances of abuse as gracefully as possible. To simplify the
2238 instances of abuse as gracefully as possible. To simplify the
2228 coding and maintain compatibility with Gary Bishop's Term
2239 coding and maintain compatibility with Gary Bishop's Term
2229 contributions, I've made use of classmethods for this. I think
2240 contributions, I've made use of classmethods for this. I think
2230 this introduces a dependency on python 2.2.
2241 this introduces a dependency on python 2.2.
2231
2242
2232 2004-01-13 Fernando Perez <fperez@colorado.edu>
2243 2004-01-13 Fernando Perez <fperez@colorado.edu>
2233
2244
2234 * IPython/numutils.py (exp_safe): simplified the code a bit and
2245 * IPython/numutils.py (exp_safe): simplified the code a bit and
2235 removed the need for importing the kinds module altogether.
2246 removed the need for importing the kinds module altogether.
2236
2247
2237 2004-01-06 Fernando Perez <fperez@colorado.edu>
2248 2004-01-06 Fernando Perez <fperez@colorado.edu>
2238
2249
2239 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2250 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2240 a magic function instead, after some community feedback. No
2251 a magic function instead, after some community feedback. No
2241 special syntax will exist for it, but its name is deliberately
2252 special syntax will exist for it, but its name is deliberately
2242 very short.
2253 very short.
2243
2254
2244 2003-12-20 Fernando Perez <fperez@colorado.edu>
2255 2003-12-20 Fernando Perez <fperez@colorado.edu>
2245
2256
2246 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2257 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2247 new functionality, to automagically assign the result of a shell
2258 new functionality, to automagically assign the result of a shell
2248 command to a variable. I'll solicit some community feedback on
2259 command to a variable. I'll solicit some community feedback on
2249 this before making it permanent.
2260 this before making it permanent.
2250
2261
2251 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2262 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2252 requested about callables for which inspect couldn't obtain a
2263 requested about callables for which inspect couldn't obtain a
2253 proper argspec. Thanks to a crash report sent by Etienne
2264 proper argspec. Thanks to a crash report sent by Etienne
2254 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2265 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2255
2266
2256 2003-12-09 Fernando Perez <fperez@colorado.edu>
2267 2003-12-09 Fernando Perez <fperez@colorado.edu>
2257
2268
2258 * IPython/genutils.py (page): patch for the pager to work across
2269 * IPython/genutils.py (page): patch for the pager to work across
2259 various versions of Windows. By Gary Bishop.
2270 various versions of Windows. By Gary Bishop.
2260
2271
2261 2003-12-04 Fernando Perez <fperez@colorado.edu>
2272 2003-12-04 Fernando Perez <fperez@colorado.edu>
2262
2273
2263 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2274 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2264 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2275 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2265 While I tested this and it looks ok, there may still be corner
2276 While I tested this and it looks ok, there may still be corner
2266 cases I've missed.
2277 cases I've missed.
2267
2278
2268 2003-12-01 Fernando Perez <fperez@colorado.edu>
2279 2003-12-01 Fernando Perez <fperez@colorado.edu>
2269
2280
2270 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2281 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2271 where a line like 'p,q=1,2' would fail because the automagic
2282 where a line like 'p,q=1,2' would fail because the automagic
2272 system would be triggered for @p.
2283 system would be triggered for @p.
2273
2284
2274 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2285 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2275 cleanups, code unmodified.
2286 cleanups, code unmodified.
2276
2287
2277 * IPython/genutils.py (Term): added a class for IPython to handle
2288 * IPython/genutils.py (Term): added a class for IPython to handle
2278 output. In most cases it will just be a proxy for stdout/err, but
2289 output. In most cases it will just be a proxy for stdout/err, but
2279 having this allows modifications to be made for some platforms,
2290 having this allows modifications to be made for some platforms,
2280 such as handling color escapes under Windows. All of this code
2291 such as handling color escapes under Windows. All of this code
2281 was contributed by Gary Bishop, with minor modifications by me.
2292 was contributed by Gary Bishop, with minor modifications by me.
2282 The actual changes affect many files.
2293 The actual changes affect many files.
2283
2294
2284 2003-11-30 Fernando Perez <fperez@colorado.edu>
2295 2003-11-30 Fernando Perez <fperez@colorado.edu>
2285
2296
2286 * IPython/iplib.py (file_matches): new completion code, courtesy
2297 * IPython/iplib.py (file_matches): new completion code, courtesy
2287 of Jeff Collins. This enables filename completion again under
2298 of Jeff Collins. This enables filename completion again under
2288 python 2.3, which disabled it at the C level.
2299 python 2.3, which disabled it at the C level.
2289
2300
2290 2003-11-11 Fernando Perez <fperez@colorado.edu>
2301 2003-11-11 Fernando Perez <fperez@colorado.edu>
2291
2302
2292 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2303 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2293 for Numeric.array(map(...)), but often convenient.
2304 for Numeric.array(map(...)), but often convenient.
2294
2305
2295 2003-11-05 Fernando Perez <fperez@colorado.edu>
2306 2003-11-05 Fernando Perez <fperez@colorado.edu>
2296
2307
2297 * IPython/numutils.py (frange): Changed a call from int() to
2308 * IPython/numutils.py (frange): Changed a call from int() to
2298 int(round()) to prevent a problem reported with arange() in the
2309 int(round()) to prevent a problem reported with arange() in the
2299 numpy list.
2310 numpy list.
2300
2311
2301 2003-10-06 Fernando Perez <fperez@colorado.edu>
2312 2003-10-06 Fernando Perez <fperez@colorado.edu>
2302
2313
2303 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2314 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2304 prevent crashes if sys lacks an argv attribute (it happens with
2315 prevent crashes if sys lacks an argv attribute (it happens with
2305 embedded interpreters which build a bare-bones sys module).
2316 embedded interpreters which build a bare-bones sys module).
2306 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2317 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2307
2318
2308 2003-09-24 Fernando Perez <fperez@colorado.edu>
2319 2003-09-24 Fernando Perez <fperez@colorado.edu>
2309
2320
2310 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2321 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2311 to protect against poorly written user objects where __getattr__
2322 to protect against poorly written user objects where __getattr__
2312 raises exceptions other than AttributeError. Thanks to a bug
2323 raises exceptions other than AttributeError. Thanks to a bug
2313 report by Oliver Sander <osander-AT-gmx.de>.
2324 report by Oliver Sander <osander-AT-gmx.de>.
2314
2325
2315 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2326 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2316 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2327 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2317
2328
2318 2003-09-09 Fernando Perez <fperez@colorado.edu>
2329 2003-09-09 Fernando Perez <fperez@colorado.edu>
2319
2330
2320 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2331 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2321 unpacking a list whith a callable as first element would
2332 unpacking a list whith a callable as first element would
2322 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2333 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2323 Collins.
2334 Collins.
2324
2335
2325 2003-08-25 *** Released version 0.5.0
2336 2003-08-25 *** Released version 0.5.0
2326
2337
2327 2003-08-22 Fernando Perez <fperez@colorado.edu>
2338 2003-08-22 Fernando Perez <fperez@colorado.edu>
2328
2339
2329 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2340 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2330 improperly defined user exceptions. Thanks to feedback from Mark
2341 improperly defined user exceptions. Thanks to feedback from Mark
2331 Russell <mrussell-AT-verio.net>.
2342 Russell <mrussell-AT-verio.net>.
2332
2343
2333 2003-08-20 Fernando Perez <fperez@colorado.edu>
2344 2003-08-20 Fernando Perez <fperez@colorado.edu>
2334
2345
2335 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2346 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2336 printing so that it would print multi-line string forms starting
2347 printing so that it would print multi-line string forms starting
2337 with a new line. This way the formatting is better respected for
2348 with a new line. This way the formatting is better respected for
2338 objects which work hard to make nice string forms.
2349 objects which work hard to make nice string forms.
2339
2350
2340 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2351 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2341 autocall would overtake data access for objects with both
2352 autocall would overtake data access for objects with both
2342 __getitem__ and __call__.
2353 __getitem__ and __call__.
2343
2354
2344 2003-08-19 *** Released version 0.5.0-rc1
2355 2003-08-19 *** Released version 0.5.0-rc1
2345
2356
2346 2003-08-19 Fernando Perez <fperez@colorado.edu>
2357 2003-08-19 Fernando Perez <fperez@colorado.edu>
2347
2358
2348 * IPython/deep_reload.py (load_tail): single tiny change here
2359 * IPython/deep_reload.py (load_tail): single tiny change here
2349 seems to fix the long-standing bug of dreload() failing to work
2360 seems to fix the long-standing bug of dreload() failing to work
2350 for dotted names. But this module is pretty tricky, so I may have
2361 for dotted names. But this module is pretty tricky, so I may have
2351 missed some subtlety. Needs more testing!.
2362 missed some subtlety. Needs more testing!.
2352
2363
2353 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2364 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2354 exceptions which have badly implemented __str__ methods.
2365 exceptions which have badly implemented __str__ methods.
2355 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2366 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2356 which I've been getting reports about from Python 2.3 users. I
2367 which I've been getting reports about from Python 2.3 users. I
2357 wish I had a simple test case to reproduce the problem, so I could
2368 wish I had a simple test case to reproduce the problem, so I could
2358 either write a cleaner workaround or file a bug report if
2369 either write a cleaner workaround or file a bug report if
2359 necessary.
2370 necessary.
2360
2371
2361 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2372 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2362 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2373 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2363 a bug report by Tjabo Kloppenburg.
2374 a bug report by Tjabo Kloppenburg.
2364
2375
2365 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2376 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2366 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2377 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2367 seems rather unstable. Thanks to a bug report by Tjabo
2378 seems rather unstable. Thanks to a bug report by Tjabo
2368 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2379 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2369
2380
2370 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2381 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2371 this out soon because of the critical fixes in the inner loop for
2382 this out soon because of the critical fixes in the inner loop for
2372 generators.
2383 generators.
2373
2384
2374 * IPython/Magic.py (Magic.getargspec): removed. This (and
2385 * IPython/Magic.py (Magic.getargspec): removed. This (and
2375 _get_def) have been obsoleted by OInspect for a long time, I
2386 _get_def) have been obsoleted by OInspect for a long time, I
2376 hadn't noticed that they were dead code.
2387 hadn't noticed that they were dead code.
2377 (Magic._ofind): restored _ofind functionality for a few literals
2388 (Magic._ofind): restored _ofind functionality for a few literals
2378 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2389 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2379 for things like "hello".capitalize?, since that would require a
2390 for things like "hello".capitalize?, since that would require a
2380 potentially dangerous eval() again.
2391 potentially dangerous eval() again.
2381
2392
2382 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2393 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2383 logic a bit more to clean up the escapes handling and minimize the
2394 logic a bit more to clean up the escapes handling and minimize the
2384 use of _ofind to only necessary cases. The interactive 'feel' of
2395 use of _ofind to only necessary cases. The interactive 'feel' of
2385 IPython should have improved quite a bit with the changes in
2396 IPython should have improved quite a bit with the changes in
2386 _prefilter and _ofind (besides being far safer than before).
2397 _prefilter and _ofind (besides being far safer than before).
2387
2398
2388 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2399 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2389 obscure, never reported). Edit would fail to find the object to
2400 obscure, never reported). Edit would fail to find the object to
2390 edit under some circumstances.
2401 edit under some circumstances.
2391 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2402 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2392 which were causing double-calling of generators. Those eval calls
2403 which were causing double-calling of generators. Those eval calls
2393 were _very_ dangerous, since code with side effects could be
2404 were _very_ dangerous, since code with side effects could be
2394 triggered. As they say, 'eval is evil'... These were the
2405 triggered. As they say, 'eval is evil'... These were the
2395 nastiest evals in IPython. Besides, _ofind is now far simpler,
2406 nastiest evals in IPython. Besides, _ofind is now far simpler,
2396 and it should also be quite a bit faster. Its use of inspect is
2407 and it should also be quite a bit faster. Its use of inspect is
2397 also safer, so perhaps some of the inspect-related crashes I've
2408 also safer, so perhaps some of the inspect-related crashes I've
2398 seen lately with Python 2.3 might be taken care of. That will
2409 seen lately with Python 2.3 might be taken care of. That will
2399 need more testing.
2410 need more testing.
2400
2411
2401 2003-08-17 Fernando Perez <fperez@colorado.edu>
2412 2003-08-17 Fernando Perez <fperez@colorado.edu>
2402
2413
2403 * IPython/iplib.py (InteractiveShell._prefilter): significant
2414 * IPython/iplib.py (InteractiveShell._prefilter): significant
2404 simplifications to the logic for handling user escapes. Faster
2415 simplifications to the logic for handling user escapes. Faster
2405 and simpler code.
2416 and simpler code.
2406
2417
2407 2003-08-14 Fernando Perez <fperez@colorado.edu>
2418 2003-08-14 Fernando Perez <fperez@colorado.edu>
2408
2419
2409 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2420 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2410 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2421 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2411 but it should be quite a bit faster. And the recursive version
2422 but it should be quite a bit faster. And the recursive version
2412 generated O(log N) intermediate storage for all rank>1 arrays,
2423 generated O(log N) intermediate storage for all rank>1 arrays,
2413 even if they were contiguous.
2424 even if they were contiguous.
2414 (l1norm): Added this function.
2425 (l1norm): Added this function.
2415 (norm): Added this function for arbitrary norms (including
2426 (norm): Added this function for arbitrary norms (including
2416 l-infinity). l1 and l2 are still special cases for convenience
2427 l-infinity). l1 and l2 are still special cases for convenience
2417 and speed.
2428 and speed.
2418
2429
2419 2003-08-03 Fernando Perez <fperez@colorado.edu>
2430 2003-08-03 Fernando Perez <fperez@colorado.edu>
2420
2431
2421 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2432 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2422 exceptions, which now raise PendingDeprecationWarnings in Python
2433 exceptions, which now raise PendingDeprecationWarnings in Python
2423 2.3. There were some in Magic and some in Gnuplot2.
2434 2.3. There were some in Magic and some in Gnuplot2.
2424
2435
2425 2003-06-30 Fernando Perez <fperez@colorado.edu>
2436 2003-06-30 Fernando Perez <fperez@colorado.edu>
2426
2437
2427 * IPython/genutils.py (page): modified to call curses only for
2438 * IPython/genutils.py (page): modified to call curses only for
2428 terminals where TERM=='xterm'. After problems under many other
2439 terminals where TERM=='xterm'. After problems under many other
2429 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2440 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2430
2441
2431 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2442 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2432 would be triggered when readline was absent. This was just an old
2443 would be triggered when readline was absent. This was just an old
2433 debugging statement I'd forgotten to take out.
2444 debugging statement I'd forgotten to take out.
2434
2445
2435 2003-06-20 Fernando Perez <fperez@colorado.edu>
2446 2003-06-20 Fernando Perez <fperez@colorado.edu>
2436
2447
2437 * IPython/genutils.py (clock): modified to return only user time
2448 * IPython/genutils.py (clock): modified to return only user time
2438 (not counting system time), after a discussion on scipy. While
2449 (not counting system time), after a discussion on scipy. While
2439 system time may be a useful quantity occasionally, it may much
2450 system time may be a useful quantity occasionally, it may much
2440 more easily be skewed by occasional swapping or other similar
2451 more easily be skewed by occasional swapping or other similar
2441 activity.
2452 activity.
2442
2453
2443 2003-06-05 Fernando Perez <fperez@colorado.edu>
2454 2003-06-05 Fernando Perez <fperez@colorado.edu>
2444
2455
2445 * IPython/numutils.py (identity): new function, for building
2456 * IPython/numutils.py (identity): new function, for building
2446 arbitrary rank Kronecker deltas (mostly backwards compatible with
2457 arbitrary rank Kronecker deltas (mostly backwards compatible with
2447 Numeric.identity)
2458 Numeric.identity)
2448
2459
2449 2003-06-03 Fernando Perez <fperez@colorado.edu>
2460 2003-06-03 Fernando Perez <fperez@colorado.edu>
2450
2461
2451 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2462 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2452 arguments passed to magics with spaces, to allow trailing '\' to
2463 arguments passed to magics with spaces, to allow trailing '\' to
2453 work normally (mainly for Windows users).
2464 work normally (mainly for Windows users).
2454
2465
2455 2003-05-29 Fernando Perez <fperez@colorado.edu>
2466 2003-05-29 Fernando Perez <fperez@colorado.edu>
2456
2467
2457 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2468 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2458 instead of pydoc.help. This fixes a bizarre behavior where
2469 instead of pydoc.help. This fixes a bizarre behavior where
2459 printing '%s' % locals() would trigger the help system. Now
2470 printing '%s' % locals() would trigger the help system. Now
2460 ipython behaves like normal python does.
2471 ipython behaves like normal python does.
2461
2472
2462 Note that if one does 'from pydoc import help', the bizarre
2473 Note that if one does 'from pydoc import help', the bizarre
2463 behavior returns, but this will also happen in normal python, so
2474 behavior returns, but this will also happen in normal python, so
2464 it's not an ipython bug anymore (it has to do with how pydoc.help
2475 it's not an ipython bug anymore (it has to do with how pydoc.help
2465 is implemented).
2476 is implemented).
2466
2477
2467 2003-05-22 Fernando Perez <fperez@colorado.edu>
2478 2003-05-22 Fernando Perez <fperez@colorado.edu>
2468
2479
2469 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2480 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2470 return [] instead of None when nothing matches, also match to end
2481 return [] instead of None when nothing matches, also match to end
2471 of line. Patch by Gary Bishop.
2482 of line. Patch by Gary Bishop.
2472
2483
2473 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2484 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2474 protection as before, for files passed on the command line. This
2485 protection as before, for files passed on the command line. This
2475 prevents the CrashHandler from kicking in if user files call into
2486 prevents the CrashHandler from kicking in if user files call into
2476 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2487 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2477 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2488 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2478
2489
2479 2003-05-20 *** Released version 0.4.0
2490 2003-05-20 *** Released version 0.4.0
2480
2491
2481 2003-05-20 Fernando Perez <fperez@colorado.edu>
2492 2003-05-20 Fernando Perez <fperez@colorado.edu>
2482
2493
2483 * setup.py: added support for manpages. It's a bit hackish b/c of
2494 * setup.py: added support for manpages. It's a bit hackish b/c of
2484 a bug in the way the bdist_rpm distutils target handles gzipped
2495 a bug in the way the bdist_rpm distutils target handles gzipped
2485 manpages, but it works. After a patch by Jack.
2496 manpages, but it works. After a patch by Jack.
2486
2497
2487 2003-05-19 Fernando Perez <fperez@colorado.edu>
2498 2003-05-19 Fernando Perez <fperez@colorado.edu>
2488
2499
2489 * IPython/numutils.py: added a mockup of the kinds module, since
2500 * IPython/numutils.py: added a mockup of the kinds module, since
2490 it was recently removed from Numeric. This way, numutils will
2501 it was recently removed from Numeric. This way, numutils will
2491 work for all users even if they are missing kinds.
2502 work for all users even if they are missing kinds.
2492
2503
2493 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2504 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2494 failure, which can occur with SWIG-wrapped extensions. After a
2505 failure, which can occur with SWIG-wrapped extensions. After a
2495 crash report from Prabhu.
2506 crash report from Prabhu.
2496
2507
2497 2003-05-16 Fernando Perez <fperez@colorado.edu>
2508 2003-05-16 Fernando Perez <fperez@colorado.edu>
2498
2509
2499 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2510 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2500 protect ipython from user code which may call directly
2511 protect ipython from user code which may call directly
2501 sys.excepthook (this looks like an ipython crash to the user, even
2512 sys.excepthook (this looks like an ipython crash to the user, even
2502 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2513 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2503 This is especially important to help users of WxWindows, but may
2514 This is especially important to help users of WxWindows, but may
2504 also be useful in other cases.
2515 also be useful in other cases.
2505
2516
2506 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2517 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2507 an optional tb_offset to be specified, and to preserve exception
2518 an optional tb_offset to be specified, and to preserve exception
2508 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2519 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2509
2520
2510 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2521 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2511
2522
2512 2003-05-15 Fernando Perez <fperez@colorado.edu>
2523 2003-05-15 Fernando Perez <fperez@colorado.edu>
2513
2524
2514 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2525 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2515 installing for a new user under Windows.
2526 installing for a new user under Windows.
2516
2527
2517 2003-05-12 Fernando Perez <fperez@colorado.edu>
2528 2003-05-12 Fernando Perez <fperez@colorado.edu>
2518
2529
2519 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2530 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2520 handler for Emacs comint-based lines. Currently it doesn't do
2531 handler for Emacs comint-based lines. Currently it doesn't do
2521 much (but importantly, it doesn't update the history cache). In
2532 much (but importantly, it doesn't update the history cache). In
2522 the future it may be expanded if Alex needs more functionality
2533 the future it may be expanded if Alex needs more functionality
2523 there.
2534 there.
2524
2535
2525 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2536 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2526 info to crash reports.
2537 info to crash reports.
2527
2538
2528 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2539 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2529 just like Python's -c. Also fixed crash with invalid -color
2540 just like Python's -c. Also fixed crash with invalid -color
2530 option value at startup. Thanks to Will French
2541 option value at startup. Thanks to Will French
2531 <wfrench-AT-bestweb.net> for the bug report.
2542 <wfrench-AT-bestweb.net> for the bug report.
2532
2543
2533 2003-05-09 Fernando Perez <fperez@colorado.edu>
2544 2003-05-09 Fernando Perez <fperez@colorado.edu>
2534
2545
2535 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2546 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2536 to EvalDict (it's a mapping, after all) and simplified its code
2547 to EvalDict (it's a mapping, after all) and simplified its code
2537 quite a bit, after a nice discussion on c.l.py where Gustavo
2548 quite a bit, after a nice discussion on c.l.py where Gustavo
2538 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2549 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2539
2550
2540 2003-04-30 Fernando Perez <fperez@colorado.edu>
2551 2003-04-30 Fernando Perez <fperez@colorado.edu>
2541
2552
2542 * IPython/genutils.py (timings_out): modified it to reduce its
2553 * IPython/genutils.py (timings_out): modified it to reduce its
2543 overhead in the common reps==1 case.
2554 overhead in the common reps==1 case.
2544
2555
2545 2003-04-29 Fernando Perez <fperez@colorado.edu>
2556 2003-04-29 Fernando Perez <fperez@colorado.edu>
2546
2557
2547 * IPython/genutils.py (timings_out): Modified to use the resource
2558 * IPython/genutils.py (timings_out): Modified to use the resource
2548 module, which avoids the wraparound problems of time.clock().
2559 module, which avoids the wraparound problems of time.clock().
2549
2560
2550 2003-04-17 *** Released version 0.2.15pre4
2561 2003-04-17 *** Released version 0.2.15pre4
2551
2562
2552 2003-04-17 Fernando Perez <fperez@colorado.edu>
2563 2003-04-17 Fernando Perez <fperez@colorado.edu>
2553
2564
2554 * setup.py (scriptfiles): Split windows-specific stuff over to a
2565 * setup.py (scriptfiles): Split windows-specific stuff over to a
2555 separate file, in an attempt to have a Windows GUI installer.
2566 separate file, in an attempt to have a Windows GUI installer.
2556 That didn't work, but part of the groundwork is done.
2567 That didn't work, but part of the groundwork is done.
2557
2568
2558 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2569 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2559 indent/unindent with 4 spaces. Particularly useful in combination
2570 indent/unindent with 4 spaces. Particularly useful in combination
2560 with the new auto-indent option.
2571 with the new auto-indent option.
2561
2572
2562 2003-04-16 Fernando Perez <fperez@colorado.edu>
2573 2003-04-16 Fernando Perez <fperez@colorado.edu>
2563
2574
2564 * IPython/Magic.py: various replacements of self.rc for
2575 * IPython/Magic.py: various replacements of self.rc for
2565 self.shell.rc. A lot more remains to be done to fully disentangle
2576 self.shell.rc. A lot more remains to be done to fully disentangle
2566 this class from the main Shell class.
2577 this class from the main Shell class.
2567
2578
2568 * IPython/GnuplotRuntime.py: added checks for mouse support so
2579 * IPython/GnuplotRuntime.py: added checks for mouse support so
2569 that we don't try to enable it if the current gnuplot doesn't
2580 that we don't try to enable it if the current gnuplot doesn't
2570 really support it. Also added checks so that we don't try to
2581 really support it. Also added checks so that we don't try to
2571 enable persist under Windows (where Gnuplot doesn't recognize the
2582 enable persist under Windows (where Gnuplot doesn't recognize the
2572 option).
2583 option).
2573
2584
2574 * IPython/iplib.py (InteractiveShell.interact): Added optional
2585 * IPython/iplib.py (InteractiveShell.interact): Added optional
2575 auto-indenting code, after a patch by King C. Shu
2586 auto-indenting code, after a patch by King C. Shu
2576 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2587 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2577 get along well with pasting indented code. If I ever figure out
2588 get along well with pasting indented code. If I ever figure out
2578 how to make that part go well, it will become on by default.
2589 how to make that part go well, it will become on by default.
2579
2590
2580 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2591 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2581 crash ipython if there was an unmatched '%' in the user's prompt
2592 crash ipython if there was an unmatched '%' in the user's prompt
2582 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2593 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2583
2594
2584 * IPython/iplib.py (InteractiveShell.interact): removed the
2595 * IPython/iplib.py (InteractiveShell.interact): removed the
2585 ability to ask the user whether he wants to crash or not at the
2596 ability to ask the user whether he wants to crash or not at the
2586 'last line' exception handler. Calling functions at that point
2597 'last line' exception handler. Calling functions at that point
2587 changes the stack, and the error reports would have incorrect
2598 changes the stack, and the error reports would have incorrect
2588 tracebacks.
2599 tracebacks.
2589
2600
2590 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2601 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2591 pass through a peger a pretty-printed form of any object. After a
2602 pass through a peger a pretty-printed form of any object. After a
2592 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2603 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2593
2604
2594 2003-04-14 Fernando Perez <fperez@colorado.edu>
2605 2003-04-14 Fernando Perez <fperez@colorado.edu>
2595
2606
2596 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2607 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2597 all files in ~ would be modified at first install (instead of
2608 all files in ~ would be modified at first install (instead of
2598 ~/.ipython). This could be potentially disastrous, as the
2609 ~/.ipython). This could be potentially disastrous, as the
2599 modification (make line-endings native) could damage binary files.
2610 modification (make line-endings native) could damage binary files.
2600
2611
2601 2003-04-10 Fernando Perez <fperez@colorado.edu>
2612 2003-04-10 Fernando Perez <fperez@colorado.edu>
2602
2613
2603 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2614 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2604 handle only lines which are invalid python. This now means that
2615 handle only lines which are invalid python. This now means that
2605 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2616 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2606 for the bug report.
2617 for the bug report.
2607
2618
2608 2003-04-01 Fernando Perez <fperez@colorado.edu>
2619 2003-04-01 Fernando Perez <fperez@colorado.edu>
2609
2620
2610 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2621 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2611 where failing to set sys.last_traceback would crash pdb.pm().
2622 where failing to set sys.last_traceback would crash pdb.pm().
2612 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2623 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2613 report.
2624 report.
2614
2625
2615 2003-03-25 Fernando Perez <fperez@colorado.edu>
2626 2003-03-25 Fernando Perez <fperez@colorado.edu>
2616
2627
2617 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2628 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2618 before printing it (it had a lot of spurious blank lines at the
2629 before printing it (it had a lot of spurious blank lines at the
2619 end).
2630 end).
2620
2631
2621 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2632 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2622 output would be sent 21 times! Obviously people don't use this
2633 output would be sent 21 times! Obviously people don't use this
2623 too often, or I would have heard about it.
2634 too often, or I would have heard about it.
2624
2635
2625 2003-03-24 Fernando Perez <fperez@colorado.edu>
2636 2003-03-24 Fernando Perez <fperez@colorado.edu>
2626
2637
2627 * setup.py (scriptfiles): renamed the data_files parameter from
2638 * setup.py (scriptfiles): renamed the data_files parameter from
2628 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2639 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2629 for the patch.
2640 for the patch.
2630
2641
2631 2003-03-20 Fernando Perez <fperez@colorado.edu>
2642 2003-03-20 Fernando Perez <fperez@colorado.edu>
2632
2643
2633 * IPython/genutils.py (error): added error() and fatal()
2644 * IPython/genutils.py (error): added error() and fatal()
2634 functions.
2645 functions.
2635
2646
2636 2003-03-18 *** Released version 0.2.15pre3
2647 2003-03-18 *** Released version 0.2.15pre3
2637
2648
2638 2003-03-18 Fernando Perez <fperez@colorado.edu>
2649 2003-03-18 Fernando Perez <fperez@colorado.edu>
2639
2650
2640 * setupext/install_data_ext.py
2651 * setupext/install_data_ext.py
2641 (install_data_ext.initialize_options): Class contributed by Jack
2652 (install_data_ext.initialize_options): Class contributed by Jack
2642 Moffit for fixing the old distutils hack. He is sending this to
2653 Moffit for fixing the old distutils hack. He is sending this to
2643 the distutils folks so in the future we may not need it as a
2654 the distutils folks so in the future we may not need it as a
2644 private fix.
2655 private fix.
2645
2656
2646 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2657 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2647 changes for Debian packaging. See his patch for full details.
2658 changes for Debian packaging. See his patch for full details.
2648 The old distutils hack of making the ipythonrc* files carry a
2659 The old distutils hack of making the ipythonrc* files carry a
2649 bogus .py extension is gone, at last. Examples were moved to a
2660 bogus .py extension is gone, at last. Examples were moved to a
2650 separate subdir under doc/, and the separate executable scripts
2661 separate subdir under doc/, and the separate executable scripts
2651 now live in their own directory. Overall a great cleanup. The
2662 now live in their own directory. Overall a great cleanup. The
2652 manual was updated to use the new files, and setup.py has been
2663 manual was updated to use the new files, and setup.py has been
2653 fixed for this setup.
2664 fixed for this setup.
2654
2665
2655 * IPython/PyColorize.py (Parser.usage): made non-executable and
2666 * IPython/PyColorize.py (Parser.usage): made non-executable and
2656 created a pycolor wrapper around it to be included as a script.
2667 created a pycolor wrapper around it to be included as a script.
2657
2668
2658 2003-03-12 *** Released version 0.2.15pre2
2669 2003-03-12 *** Released version 0.2.15pre2
2659
2670
2660 2003-03-12 Fernando Perez <fperez@colorado.edu>
2671 2003-03-12 Fernando Perez <fperez@colorado.edu>
2661
2672
2662 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2673 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2663 long-standing problem with garbage characters in some terminals.
2674 long-standing problem with garbage characters in some terminals.
2664 The issue was really that the \001 and \002 escapes must _only_ be
2675 The issue was really that the \001 and \002 escapes must _only_ be
2665 passed to input prompts (which call readline), but _never_ to
2676 passed to input prompts (which call readline), but _never_ to
2666 normal text to be printed on screen. I changed ColorANSI to have
2677 normal text to be printed on screen. I changed ColorANSI to have
2667 two classes: TermColors and InputTermColors, each with the
2678 two classes: TermColors and InputTermColors, each with the
2668 appropriate escapes for input prompts or normal text. The code in
2679 appropriate escapes for input prompts or normal text. The code in
2669 Prompts.py got slightly more complicated, but this very old and
2680 Prompts.py got slightly more complicated, but this very old and
2670 annoying bug is finally fixed.
2681 annoying bug is finally fixed.
2671
2682
2672 All the credit for nailing down the real origin of this problem
2683 All the credit for nailing down the real origin of this problem
2673 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2684 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2674 *Many* thanks to him for spending quite a bit of effort on this.
2685 *Many* thanks to him for spending quite a bit of effort on this.
2675
2686
2676 2003-03-05 *** Released version 0.2.15pre1
2687 2003-03-05 *** Released version 0.2.15pre1
2677
2688
2678 2003-03-03 Fernando Perez <fperez@colorado.edu>
2689 2003-03-03 Fernando Perez <fperez@colorado.edu>
2679
2690
2680 * IPython/FakeModule.py: Moved the former _FakeModule to a
2691 * IPython/FakeModule.py: Moved the former _FakeModule to a
2681 separate file, because it's also needed by Magic (to fix a similar
2692 separate file, because it's also needed by Magic (to fix a similar
2682 pickle-related issue in @run).
2693 pickle-related issue in @run).
2683
2694
2684 2003-03-02 Fernando Perez <fperez@colorado.edu>
2695 2003-03-02 Fernando Perez <fperez@colorado.edu>
2685
2696
2686 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2697 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2687 the autocall option at runtime.
2698 the autocall option at runtime.
2688 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2699 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2689 across Magic.py to start separating Magic from InteractiveShell.
2700 across Magic.py to start separating Magic from InteractiveShell.
2690 (Magic._ofind): Fixed to return proper namespace for dotted
2701 (Magic._ofind): Fixed to return proper namespace for dotted
2691 names. Before, a dotted name would always return 'not currently
2702 names. Before, a dotted name would always return 'not currently
2692 defined', because it would find the 'parent'. s.x would be found,
2703 defined', because it would find the 'parent'. s.x would be found,
2693 but since 'x' isn't defined by itself, it would get confused.
2704 but since 'x' isn't defined by itself, it would get confused.
2694 (Magic.magic_run): Fixed pickling problems reported by Ralf
2705 (Magic.magic_run): Fixed pickling problems reported by Ralf
2695 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2706 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2696 that I'd used when Mike Heeter reported similar issues at the
2707 that I'd used when Mike Heeter reported similar issues at the
2697 top-level, but now for @run. It boils down to injecting the
2708 top-level, but now for @run. It boils down to injecting the
2698 namespace where code is being executed with something that looks
2709 namespace where code is being executed with something that looks
2699 enough like a module to fool pickle.dump(). Since a pickle stores
2710 enough like a module to fool pickle.dump(). Since a pickle stores
2700 a named reference to the importing module, we need this for
2711 a named reference to the importing module, we need this for
2701 pickles to save something sensible.
2712 pickles to save something sensible.
2702
2713
2703 * IPython/ipmaker.py (make_IPython): added an autocall option.
2714 * IPython/ipmaker.py (make_IPython): added an autocall option.
2704
2715
2705 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2716 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2706 the auto-eval code. Now autocalling is an option, and the code is
2717 the auto-eval code. Now autocalling is an option, and the code is
2707 also vastly safer. There is no more eval() involved at all.
2718 also vastly safer. There is no more eval() involved at all.
2708
2719
2709 2003-03-01 Fernando Perez <fperez@colorado.edu>
2720 2003-03-01 Fernando Perez <fperez@colorado.edu>
2710
2721
2711 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2722 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2712 dict with named keys instead of a tuple.
2723 dict with named keys instead of a tuple.
2713
2724
2714 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2725 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2715
2726
2716 * setup.py (make_shortcut): Fixed message about directories
2727 * setup.py (make_shortcut): Fixed message about directories
2717 created during Windows installation (the directories were ok, just
2728 created during Windows installation (the directories were ok, just
2718 the printed message was misleading). Thanks to Chris Liechti
2729 the printed message was misleading). Thanks to Chris Liechti
2719 <cliechti-AT-gmx.net> for the heads up.
2730 <cliechti-AT-gmx.net> for the heads up.
2720
2731
2721 2003-02-21 Fernando Perez <fperez@colorado.edu>
2732 2003-02-21 Fernando Perez <fperez@colorado.edu>
2722
2733
2723 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2734 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2724 of ValueError exception when checking for auto-execution. This
2735 of ValueError exception when checking for auto-execution. This
2725 one is raised by things like Numeric arrays arr.flat when the
2736 one is raised by things like Numeric arrays arr.flat when the
2726 array is non-contiguous.
2737 array is non-contiguous.
2727
2738
2728 2003-01-31 Fernando Perez <fperez@colorado.edu>
2739 2003-01-31 Fernando Perez <fperez@colorado.edu>
2729
2740
2730 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2741 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2731 not return any value at all (even though the command would get
2742 not return any value at all (even though the command would get
2732 executed).
2743 executed).
2733 (xsys): Flush stdout right after printing the command to ensure
2744 (xsys): Flush stdout right after printing the command to ensure
2734 proper ordering of commands and command output in the total
2745 proper ordering of commands and command output in the total
2735 output.
2746 output.
2736 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2747 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2737 system/getoutput as defaults. The old ones are kept for
2748 system/getoutput as defaults. The old ones are kept for
2738 compatibility reasons, so no code which uses this library needs
2749 compatibility reasons, so no code which uses this library needs
2739 changing.
2750 changing.
2740
2751
2741 2003-01-27 *** Released version 0.2.14
2752 2003-01-27 *** Released version 0.2.14
2742
2753
2743 2003-01-25 Fernando Perez <fperez@colorado.edu>
2754 2003-01-25 Fernando Perez <fperez@colorado.edu>
2744
2755
2745 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2756 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2746 functions defined in previous edit sessions could not be re-edited
2757 functions defined in previous edit sessions could not be re-edited
2747 (because the temp files were immediately removed). Now temp files
2758 (because the temp files were immediately removed). Now temp files
2748 are removed only at IPython's exit.
2759 are removed only at IPython's exit.
2749 (Magic.magic_run): Improved @run to perform shell-like expansions
2760 (Magic.magic_run): Improved @run to perform shell-like expansions
2750 on its arguments (~users and $VARS). With this, @run becomes more
2761 on its arguments (~users and $VARS). With this, @run becomes more
2751 like a normal command-line.
2762 like a normal command-line.
2752
2763
2753 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2764 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2754 bugs related to embedding and cleaned up that code. A fairly
2765 bugs related to embedding and cleaned up that code. A fairly
2755 important one was the impossibility to access the global namespace
2766 important one was the impossibility to access the global namespace
2756 through the embedded IPython (only local variables were visible).
2767 through the embedded IPython (only local variables were visible).
2757
2768
2758 2003-01-14 Fernando Perez <fperez@colorado.edu>
2769 2003-01-14 Fernando Perez <fperez@colorado.edu>
2759
2770
2760 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2771 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2761 auto-calling to be a bit more conservative. Now it doesn't get
2772 auto-calling to be a bit more conservative. Now it doesn't get
2762 triggered if any of '!=()<>' are in the rest of the input line, to
2773 triggered if any of '!=()<>' are in the rest of the input line, to
2763 allow comparing callables. Thanks to Alex for the heads up.
2774 allow comparing callables. Thanks to Alex for the heads up.
2764
2775
2765 2003-01-07 Fernando Perez <fperez@colorado.edu>
2776 2003-01-07 Fernando Perez <fperez@colorado.edu>
2766
2777
2767 * IPython/genutils.py (page): fixed estimation of the number of
2778 * IPython/genutils.py (page): fixed estimation of the number of
2768 lines in a string to be paged to simply count newlines. This
2779 lines in a string to be paged to simply count newlines. This
2769 prevents over-guessing due to embedded escape sequences. A better
2780 prevents over-guessing due to embedded escape sequences. A better
2770 long-term solution would involve stripping out the control chars
2781 long-term solution would involve stripping out the control chars
2771 for the count, but it's potentially so expensive I just don't
2782 for the count, but it's potentially so expensive I just don't
2772 think it's worth doing.
2783 think it's worth doing.
2773
2784
2774 2002-12-19 *** Released version 0.2.14pre50
2785 2002-12-19 *** Released version 0.2.14pre50
2775
2786
2776 2002-12-19 Fernando Perez <fperez@colorado.edu>
2787 2002-12-19 Fernando Perez <fperez@colorado.edu>
2777
2788
2778 * tools/release (version): Changed release scripts to inform
2789 * tools/release (version): Changed release scripts to inform
2779 Andrea and build a NEWS file with a list of recent changes.
2790 Andrea and build a NEWS file with a list of recent changes.
2780
2791
2781 * IPython/ColorANSI.py (__all__): changed terminal detection
2792 * IPython/ColorANSI.py (__all__): changed terminal detection
2782 code. Seems to work better for xterms without breaking
2793 code. Seems to work better for xterms without breaking
2783 konsole. Will need more testing to determine if WinXP and Mac OSX
2794 konsole. Will need more testing to determine if WinXP and Mac OSX
2784 also work ok.
2795 also work ok.
2785
2796
2786 2002-12-18 *** Released version 0.2.14pre49
2797 2002-12-18 *** Released version 0.2.14pre49
2787
2798
2788 2002-12-18 Fernando Perez <fperez@colorado.edu>
2799 2002-12-18 Fernando Perez <fperez@colorado.edu>
2789
2800
2790 * Docs: added new info about Mac OSX, from Andrea.
2801 * Docs: added new info about Mac OSX, from Andrea.
2791
2802
2792 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2803 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2793 allow direct plotting of python strings whose format is the same
2804 allow direct plotting of python strings whose format is the same
2794 of gnuplot data files.
2805 of gnuplot data files.
2795
2806
2796 2002-12-16 Fernando Perez <fperez@colorado.edu>
2807 2002-12-16 Fernando Perez <fperez@colorado.edu>
2797
2808
2798 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2809 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2799 value of exit question to be acknowledged.
2810 value of exit question to be acknowledged.
2800
2811
2801 2002-12-03 Fernando Perez <fperez@colorado.edu>
2812 2002-12-03 Fernando Perez <fperez@colorado.edu>
2802
2813
2803 * IPython/ipmaker.py: removed generators, which had been added
2814 * IPython/ipmaker.py: removed generators, which had been added
2804 by mistake in an earlier debugging run. This was causing trouble
2815 by mistake in an earlier debugging run. This was causing trouble
2805 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2816 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2806 for pointing this out.
2817 for pointing this out.
2807
2818
2808 2002-11-17 Fernando Perez <fperez@colorado.edu>
2819 2002-11-17 Fernando Perez <fperez@colorado.edu>
2809
2820
2810 * Manual: updated the Gnuplot section.
2821 * Manual: updated the Gnuplot section.
2811
2822
2812 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2823 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2813 a much better split of what goes in Runtime and what goes in
2824 a much better split of what goes in Runtime and what goes in
2814 Interactive.
2825 Interactive.
2815
2826
2816 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2827 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2817 being imported from iplib.
2828 being imported from iplib.
2818
2829
2819 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2830 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2820 for command-passing. Now the global Gnuplot instance is called
2831 for command-passing. Now the global Gnuplot instance is called
2821 'gp' instead of 'g', which was really a far too fragile and
2832 'gp' instead of 'g', which was really a far too fragile and
2822 common name.
2833 common name.
2823
2834
2824 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2835 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2825 bounding boxes generated by Gnuplot for square plots.
2836 bounding boxes generated by Gnuplot for square plots.
2826
2837
2827 * IPython/genutils.py (popkey): new function added. I should
2838 * IPython/genutils.py (popkey): new function added. I should
2828 suggest this on c.l.py as a dict method, it seems useful.
2839 suggest this on c.l.py as a dict method, it seems useful.
2829
2840
2830 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2841 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2831 to transparently handle PostScript generation. MUCH better than
2842 to transparently handle PostScript generation. MUCH better than
2832 the previous plot_eps/replot_eps (which I removed now). The code
2843 the previous plot_eps/replot_eps (which I removed now). The code
2833 is also fairly clean and well documented now (including
2844 is also fairly clean and well documented now (including
2834 docstrings).
2845 docstrings).
2835
2846
2836 2002-11-13 Fernando Perez <fperez@colorado.edu>
2847 2002-11-13 Fernando Perez <fperez@colorado.edu>
2837
2848
2838 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2849 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2839 (inconsistent with options).
2850 (inconsistent with options).
2840
2851
2841 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2852 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2842 manually disabled, I don't know why. Fixed it.
2853 manually disabled, I don't know why. Fixed it.
2843 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2854 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2844 eps output.
2855 eps output.
2845
2856
2846 2002-11-12 Fernando Perez <fperez@colorado.edu>
2857 2002-11-12 Fernando Perez <fperez@colorado.edu>
2847
2858
2848 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2859 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2849 don't propagate up to caller. Fixes crash reported by François
2860 don't propagate up to caller. Fixes crash reported by François
2850 Pinard.
2861 Pinard.
2851
2862
2852 2002-11-09 Fernando Perez <fperez@colorado.edu>
2863 2002-11-09 Fernando Perez <fperez@colorado.edu>
2853
2864
2854 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2865 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2855 history file for new users.
2866 history file for new users.
2856 (make_IPython): fixed bug where initial install would leave the
2867 (make_IPython): fixed bug where initial install would leave the
2857 user running in the .ipython dir.
2868 user running in the .ipython dir.
2858 (make_IPython): fixed bug where config dir .ipython would be
2869 (make_IPython): fixed bug where config dir .ipython would be
2859 created regardless of the given -ipythondir option. Thanks to Cory
2870 created regardless of the given -ipythondir option. Thanks to Cory
2860 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2871 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2861
2872
2862 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2873 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2863 type confirmations. Will need to use it in all of IPython's code
2874 type confirmations. Will need to use it in all of IPython's code
2864 consistently.
2875 consistently.
2865
2876
2866 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2877 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2867 context to print 31 lines instead of the default 5. This will make
2878 context to print 31 lines instead of the default 5. This will make
2868 the crash reports extremely detailed in case the problem is in
2879 the crash reports extremely detailed in case the problem is in
2869 libraries I don't have access to.
2880 libraries I don't have access to.
2870
2881
2871 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2882 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2872 line of defense' code to still crash, but giving users fair
2883 line of defense' code to still crash, but giving users fair
2873 warning. I don't want internal errors to go unreported: if there's
2884 warning. I don't want internal errors to go unreported: if there's
2874 an internal problem, IPython should crash and generate a full
2885 an internal problem, IPython should crash and generate a full
2875 report.
2886 report.
2876
2887
2877 2002-11-08 Fernando Perez <fperez@colorado.edu>
2888 2002-11-08 Fernando Perez <fperez@colorado.edu>
2878
2889
2879 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2890 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2880 otherwise uncaught exceptions which can appear if people set
2891 otherwise uncaught exceptions which can appear if people set
2881 sys.stdout to something badly broken. Thanks to a crash report
2892 sys.stdout to something badly broken. Thanks to a crash report
2882 from henni-AT-mail.brainbot.com.
2893 from henni-AT-mail.brainbot.com.
2883
2894
2884 2002-11-04 Fernando Perez <fperez@colorado.edu>
2895 2002-11-04 Fernando Perez <fperez@colorado.edu>
2885
2896
2886 * IPython/iplib.py (InteractiveShell.interact): added
2897 * IPython/iplib.py (InteractiveShell.interact): added
2887 __IPYTHON__active to the builtins. It's a flag which goes on when
2898 __IPYTHON__active to the builtins. It's a flag which goes on when
2888 the interaction starts and goes off again when it stops. This
2899 the interaction starts and goes off again when it stops. This
2889 allows embedding code to detect being inside IPython. Before this
2900 allows embedding code to detect being inside IPython. Before this
2890 was done via __IPYTHON__, but that only shows that an IPython
2901 was done via __IPYTHON__, but that only shows that an IPython
2891 instance has been created.
2902 instance has been created.
2892
2903
2893 * IPython/Magic.py (Magic.magic_env): I realized that in a
2904 * IPython/Magic.py (Magic.magic_env): I realized that in a
2894 UserDict, instance.data holds the data as a normal dict. So I
2905 UserDict, instance.data holds the data as a normal dict. So I
2895 modified @env to return os.environ.data instead of rebuilding a
2906 modified @env to return os.environ.data instead of rebuilding a
2896 dict by hand.
2907 dict by hand.
2897
2908
2898 2002-11-02 Fernando Perez <fperez@colorado.edu>
2909 2002-11-02 Fernando Perez <fperez@colorado.edu>
2899
2910
2900 * IPython/genutils.py (warn): changed so that level 1 prints no
2911 * IPython/genutils.py (warn): changed so that level 1 prints no
2901 header. Level 2 is now the default (with 'WARNING' header, as
2912 header. Level 2 is now the default (with 'WARNING' header, as
2902 before). I think I tracked all places where changes were needed in
2913 before). I think I tracked all places where changes were needed in
2903 IPython, but outside code using the old level numbering may have
2914 IPython, but outside code using the old level numbering may have
2904 broken.
2915 broken.
2905
2916
2906 * IPython/iplib.py (InteractiveShell.runcode): added this to
2917 * IPython/iplib.py (InteractiveShell.runcode): added this to
2907 handle the tracebacks in SystemExit traps correctly. The previous
2918 handle the tracebacks in SystemExit traps correctly. The previous
2908 code (through interact) was printing more of the stack than
2919 code (through interact) was printing more of the stack than
2909 necessary, showing IPython internal code to the user.
2920 necessary, showing IPython internal code to the user.
2910
2921
2911 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2922 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2912 default. Now that the default at the confirmation prompt is yes,
2923 default. Now that the default at the confirmation prompt is yes,
2913 it's not so intrusive. François' argument that ipython sessions
2924 it's not so intrusive. François' argument that ipython sessions
2914 tend to be complex enough not to lose them from an accidental C-d,
2925 tend to be complex enough not to lose them from an accidental C-d,
2915 is a valid one.
2926 is a valid one.
2916
2927
2917 * IPython/iplib.py (InteractiveShell.interact): added a
2928 * IPython/iplib.py (InteractiveShell.interact): added a
2918 showtraceback() call to the SystemExit trap, and modified the exit
2929 showtraceback() call to the SystemExit trap, and modified the exit
2919 confirmation to have yes as the default.
2930 confirmation to have yes as the default.
2920
2931
2921 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2932 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2922 this file. It's been gone from the code for a long time, this was
2933 this file. It's been gone from the code for a long time, this was
2923 simply leftover junk.
2934 simply leftover junk.
2924
2935
2925 2002-11-01 Fernando Perez <fperez@colorado.edu>
2936 2002-11-01 Fernando Perez <fperez@colorado.edu>
2926
2937
2927 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2938 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2928 added. If set, IPython now traps EOF and asks for
2939 added. If set, IPython now traps EOF and asks for
2929 confirmation. After a request by François Pinard.
2940 confirmation. After a request by François Pinard.
2930
2941
2931 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2942 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2932 of @abort, and with a new (better) mechanism for handling the
2943 of @abort, and with a new (better) mechanism for handling the
2933 exceptions.
2944 exceptions.
2934
2945
2935 2002-10-27 Fernando Perez <fperez@colorado.edu>
2946 2002-10-27 Fernando Perez <fperez@colorado.edu>
2936
2947
2937 * IPython/usage.py (__doc__): updated the --help information and
2948 * IPython/usage.py (__doc__): updated the --help information and
2938 the ipythonrc file to indicate that -log generates
2949 the ipythonrc file to indicate that -log generates
2939 ./ipython.log. Also fixed the corresponding info in @logstart.
2950 ./ipython.log. Also fixed the corresponding info in @logstart.
2940 This and several other fixes in the manuals thanks to reports by
2951 This and several other fixes in the manuals thanks to reports by
2941 François Pinard <pinard-AT-iro.umontreal.ca>.
2952 François Pinard <pinard-AT-iro.umontreal.ca>.
2942
2953
2943 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2954 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2944 refer to @logstart (instead of @log, which doesn't exist).
2955 refer to @logstart (instead of @log, which doesn't exist).
2945
2956
2946 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2957 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2947 AttributeError crash. Thanks to Christopher Armstrong
2958 AttributeError crash. Thanks to Christopher Armstrong
2948 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2959 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2949 introduced recently (in 0.2.14pre37) with the fix to the eval
2960 introduced recently (in 0.2.14pre37) with the fix to the eval
2950 problem mentioned below.
2961 problem mentioned below.
2951
2962
2952 2002-10-17 Fernando Perez <fperez@colorado.edu>
2963 2002-10-17 Fernando Perez <fperez@colorado.edu>
2953
2964
2954 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2965 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2955 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2966 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2956
2967
2957 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2968 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2958 this function to fix a problem reported by Alex Schmolck. He saw
2969 this function to fix a problem reported by Alex Schmolck. He saw
2959 it with list comprehensions and generators, which were getting
2970 it with list comprehensions and generators, which were getting
2960 called twice. The real problem was an 'eval' call in testing for
2971 called twice. The real problem was an 'eval' call in testing for
2961 automagic which was evaluating the input line silently.
2972 automagic which was evaluating the input line silently.
2962
2973
2963 This is a potentially very nasty bug, if the input has side
2974 This is a potentially very nasty bug, if the input has side
2964 effects which must not be repeated. The code is much cleaner now,
2975 effects which must not be repeated. The code is much cleaner now,
2965 without any blanket 'except' left and with a regexp test for
2976 without any blanket 'except' left and with a regexp test for
2966 actual function names.
2977 actual function names.
2967
2978
2968 But an eval remains, which I'm not fully comfortable with. I just
2979 But an eval remains, which I'm not fully comfortable with. I just
2969 don't know how to find out if an expression could be a callable in
2980 don't know how to find out if an expression could be a callable in
2970 the user's namespace without doing an eval on the string. However
2981 the user's namespace without doing an eval on the string. However
2971 that string is now much more strictly checked so that no code
2982 that string is now much more strictly checked so that no code
2972 slips by, so the eval should only happen for things that can
2983 slips by, so the eval should only happen for things that can
2973 really be only function/method names.
2984 really be only function/method names.
2974
2985
2975 2002-10-15 Fernando Perez <fperez@colorado.edu>
2986 2002-10-15 Fernando Perez <fperez@colorado.edu>
2976
2987
2977 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2988 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2978 OSX information to main manual, removed README_Mac_OSX file from
2989 OSX information to main manual, removed README_Mac_OSX file from
2979 distribution. Also updated credits for recent additions.
2990 distribution. Also updated credits for recent additions.
2980
2991
2981 2002-10-10 Fernando Perez <fperez@colorado.edu>
2992 2002-10-10 Fernando Perez <fperez@colorado.edu>
2982
2993
2983 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2994 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2984 terminal-related issues. Many thanks to Andrea Riciputi
2995 terminal-related issues. Many thanks to Andrea Riciputi
2985 <andrea.riciputi-AT-libero.it> for writing it.
2996 <andrea.riciputi-AT-libero.it> for writing it.
2986
2997
2987 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2998 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2988 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2999 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2989
3000
2990 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3001 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2991 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3002 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2992 <syver-en-AT-online.no> who both submitted patches for this problem.
3003 <syver-en-AT-online.no> who both submitted patches for this problem.
2993
3004
2994 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3005 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2995 global embedding to make sure that things don't overwrite user
3006 global embedding to make sure that things don't overwrite user
2996 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3007 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2997
3008
2998 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3009 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2999 compatibility. Thanks to Hayden Callow
3010 compatibility. Thanks to Hayden Callow
3000 <h.callow-AT-elec.canterbury.ac.nz>
3011 <h.callow-AT-elec.canterbury.ac.nz>
3001
3012
3002 2002-10-04 Fernando Perez <fperez@colorado.edu>
3013 2002-10-04 Fernando Perez <fperez@colorado.edu>
3003
3014
3004 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3015 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3005 Gnuplot.File objects.
3016 Gnuplot.File objects.
3006
3017
3007 2002-07-23 Fernando Perez <fperez@colorado.edu>
3018 2002-07-23 Fernando Perez <fperez@colorado.edu>
3008
3019
3009 * IPython/genutils.py (timing): Added timings() and timing() for
3020 * IPython/genutils.py (timing): Added timings() and timing() for
3010 quick access to the most commonly needed data, the execution
3021 quick access to the most commonly needed data, the execution
3011 times. Old timing() renamed to timings_out().
3022 times. Old timing() renamed to timings_out().
3012
3023
3013 2002-07-18 Fernando Perez <fperez@colorado.edu>
3024 2002-07-18 Fernando Perez <fperez@colorado.edu>
3014
3025
3015 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3026 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3016 bug with nested instances disrupting the parent's tab completion.
3027 bug with nested instances disrupting the parent's tab completion.
3017
3028
3018 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3029 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3019 all_completions code to begin the emacs integration.
3030 all_completions code to begin the emacs integration.
3020
3031
3021 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3032 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3022 argument to allow titling individual arrays when plotting.
3033 argument to allow titling individual arrays when plotting.
3023
3034
3024 2002-07-15 Fernando Perez <fperez@colorado.edu>
3035 2002-07-15 Fernando Perez <fperez@colorado.edu>
3025
3036
3026 * setup.py (make_shortcut): changed to retrieve the value of
3037 * setup.py (make_shortcut): changed to retrieve the value of
3027 'Program Files' directory from the registry (this value changes in
3038 'Program Files' directory from the registry (this value changes in
3028 non-english versions of Windows). Thanks to Thomas Fanslau
3039 non-english versions of Windows). Thanks to Thomas Fanslau
3029 <tfanslau-AT-gmx.de> for the report.
3040 <tfanslau-AT-gmx.de> for the report.
3030
3041
3031 2002-07-10 Fernando Perez <fperez@colorado.edu>
3042 2002-07-10 Fernando Perez <fperez@colorado.edu>
3032
3043
3033 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3044 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3034 a bug in pdb, which crashes if a line with only whitespace is
3045 a bug in pdb, which crashes if a line with only whitespace is
3035 entered. Bug report submitted to sourceforge.
3046 entered. Bug report submitted to sourceforge.
3036
3047
3037 2002-07-09 Fernando Perez <fperez@colorado.edu>
3048 2002-07-09 Fernando Perez <fperez@colorado.edu>
3038
3049
3039 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3050 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3040 reporting exceptions (it's a bug in inspect.py, I just set a
3051 reporting exceptions (it's a bug in inspect.py, I just set a
3041 workaround).
3052 workaround).
3042
3053
3043 2002-07-08 Fernando Perez <fperez@colorado.edu>
3054 2002-07-08 Fernando Perez <fperez@colorado.edu>
3044
3055
3045 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3056 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3046 __IPYTHON__ in __builtins__ to show up in user_ns.
3057 __IPYTHON__ in __builtins__ to show up in user_ns.
3047
3058
3048 2002-07-03 Fernando Perez <fperez@colorado.edu>
3059 2002-07-03 Fernando Perez <fperez@colorado.edu>
3049
3060
3050 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3061 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3051 name from @gp_set_instance to @gp_set_default.
3062 name from @gp_set_instance to @gp_set_default.
3052
3063
3053 * IPython/ipmaker.py (make_IPython): default editor value set to
3064 * IPython/ipmaker.py (make_IPython): default editor value set to
3054 '0' (a string), to match the rc file. Otherwise will crash when
3065 '0' (a string), to match the rc file. Otherwise will crash when
3055 .strip() is called on it.
3066 .strip() is called on it.
3056
3067
3057
3068
3058 2002-06-28 Fernando Perez <fperez@colorado.edu>
3069 2002-06-28 Fernando Perez <fperez@colorado.edu>
3059
3070
3060 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3071 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3061 of files in current directory when a file is executed via
3072 of files in current directory when a file is executed via
3062 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3073 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3063
3074
3064 * setup.py (manfiles): fix for rpm builds, submitted by RA
3075 * setup.py (manfiles): fix for rpm builds, submitted by RA
3065 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3076 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3066
3077
3067 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3078 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3068 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3079 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3069 string!). A. Schmolck caught this one.
3080 string!). A. Schmolck caught this one.
3070
3081
3071 2002-06-27 Fernando Perez <fperez@colorado.edu>
3082 2002-06-27 Fernando Perez <fperez@colorado.edu>
3072
3083
3073 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3084 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3074 defined files at the cmd line. __name__ wasn't being set to
3085 defined files at the cmd line. __name__ wasn't being set to
3075 __main__.
3086 __main__.
3076
3087
3077 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3088 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3078 regular lists and tuples besides Numeric arrays.
3089 regular lists and tuples besides Numeric arrays.
3079
3090
3080 * IPython/Prompts.py (CachedOutput.__call__): Added output
3091 * IPython/Prompts.py (CachedOutput.__call__): Added output
3081 supression for input ending with ';'. Similar to Mathematica and
3092 supression for input ending with ';'. Similar to Mathematica and
3082 Matlab. The _* vars and Out[] list are still updated, just like
3093 Matlab. The _* vars and Out[] list are still updated, just like
3083 Mathematica behaves.
3094 Mathematica behaves.
3084
3095
3085 2002-06-25 Fernando Perez <fperez@colorado.edu>
3096 2002-06-25 Fernando Perez <fperez@colorado.edu>
3086
3097
3087 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3098 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3088 .ini extensions for profiels under Windows.
3099 .ini extensions for profiels under Windows.
3089
3100
3090 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3101 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3091 string form. Fix contributed by Alexander Schmolck
3102 string form. Fix contributed by Alexander Schmolck
3092 <a.schmolck-AT-gmx.net>
3103 <a.schmolck-AT-gmx.net>
3093
3104
3094 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3105 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3095 pre-configured Gnuplot instance.
3106 pre-configured Gnuplot instance.
3096
3107
3097 2002-06-21 Fernando Perez <fperez@colorado.edu>
3108 2002-06-21 Fernando Perez <fperez@colorado.edu>
3098
3109
3099 * IPython/numutils.py (exp_safe): new function, works around the
3110 * IPython/numutils.py (exp_safe): new function, works around the
3100 underflow problems in Numeric.
3111 underflow problems in Numeric.
3101 (log2): New fn. Safe log in base 2: returns exact integer answer
3112 (log2): New fn. Safe log in base 2: returns exact integer answer
3102 for exact integer powers of 2.
3113 for exact integer powers of 2.
3103
3114
3104 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3115 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3105 properly.
3116 properly.
3106
3117
3107 2002-06-20 Fernando Perez <fperez@colorado.edu>
3118 2002-06-20 Fernando Perez <fperez@colorado.edu>
3108
3119
3109 * IPython/genutils.py (timing): new function like
3120 * IPython/genutils.py (timing): new function like
3110 Mathematica's. Similar to time_test, but returns more info.
3121 Mathematica's. Similar to time_test, but returns more info.
3111
3122
3112 2002-06-18 Fernando Perez <fperez@colorado.edu>
3123 2002-06-18 Fernando Perez <fperez@colorado.edu>
3113
3124
3114 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3125 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3115 according to Mike Heeter's suggestions.
3126 according to Mike Heeter's suggestions.
3116
3127
3117 2002-06-16 Fernando Perez <fperez@colorado.edu>
3128 2002-06-16 Fernando Perez <fperez@colorado.edu>
3118
3129
3119 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3130 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3120 system. GnuplotMagic is gone as a user-directory option. New files
3131 system. GnuplotMagic is gone as a user-directory option. New files
3121 make it easier to use all the gnuplot stuff both from external
3132 make it easier to use all the gnuplot stuff both from external
3122 programs as well as from IPython. Had to rewrite part of
3133 programs as well as from IPython. Had to rewrite part of
3123 hardcopy() b/c of a strange bug: often the ps files simply don't
3134 hardcopy() b/c of a strange bug: often the ps files simply don't
3124 get created, and require a repeat of the command (often several
3135 get created, and require a repeat of the command (often several
3125 times).
3136 times).
3126
3137
3127 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3138 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3128 resolve output channel at call time, so that if sys.stderr has
3139 resolve output channel at call time, so that if sys.stderr has
3129 been redirected by user this gets honored.
3140 been redirected by user this gets honored.
3130
3141
3131 2002-06-13 Fernando Perez <fperez@colorado.edu>
3142 2002-06-13 Fernando Perez <fperez@colorado.edu>
3132
3143
3133 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3144 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3134 IPShell. Kept a copy with the old names to avoid breaking people's
3145 IPShell. Kept a copy with the old names to avoid breaking people's
3135 embedded code.
3146 embedded code.
3136
3147
3137 * IPython/ipython: simplified it to the bare minimum after
3148 * IPython/ipython: simplified it to the bare minimum after
3138 Holger's suggestions. Added info about how to use it in
3149 Holger's suggestions. Added info about how to use it in
3139 PYTHONSTARTUP.
3150 PYTHONSTARTUP.
3140
3151
3141 * IPython/Shell.py (IPythonShell): changed the options passing
3152 * IPython/Shell.py (IPythonShell): changed the options passing
3142 from a string with funky %s replacements to a straight list. Maybe
3153 from a string with funky %s replacements to a straight list. Maybe
3143 a bit more typing, but it follows sys.argv conventions, so there's
3154 a bit more typing, but it follows sys.argv conventions, so there's
3144 less special-casing to remember.
3155 less special-casing to remember.
3145
3156
3146 2002-06-12 Fernando Perez <fperez@colorado.edu>
3157 2002-06-12 Fernando Perez <fperez@colorado.edu>
3147
3158
3148 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3159 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3149 command. Thanks to a suggestion by Mike Heeter.
3160 command. Thanks to a suggestion by Mike Heeter.
3150 (Magic.magic_pfile): added behavior to look at filenames if given
3161 (Magic.magic_pfile): added behavior to look at filenames if given
3151 arg is not a defined object.
3162 arg is not a defined object.
3152 (Magic.magic_save): New @save function to save code snippets. Also
3163 (Magic.magic_save): New @save function to save code snippets. Also
3153 a Mike Heeter idea.
3164 a Mike Heeter idea.
3154
3165
3155 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3166 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3156 plot() and replot(). Much more convenient now, especially for
3167 plot() and replot(). Much more convenient now, especially for
3157 interactive use.
3168 interactive use.
3158
3169
3159 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3170 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3160 filenames.
3171 filenames.
3161
3172
3162 2002-06-02 Fernando Perez <fperez@colorado.edu>
3173 2002-06-02 Fernando Perez <fperez@colorado.edu>
3163
3174
3164 * IPython/Struct.py (Struct.__init__): modified to admit
3175 * IPython/Struct.py (Struct.__init__): modified to admit
3165 initialization via another struct.
3176 initialization via another struct.
3166
3177
3167 * IPython/genutils.py (SystemExec.__init__): New stateful
3178 * IPython/genutils.py (SystemExec.__init__): New stateful
3168 interface to xsys and bq. Useful for writing system scripts.
3179 interface to xsys and bq. Useful for writing system scripts.
3169
3180
3170 2002-05-30 Fernando Perez <fperez@colorado.edu>
3181 2002-05-30 Fernando Perez <fperez@colorado.edu>
3171
3182
3172 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3183 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3173 documents. This will make the user download smaller (it's getting
3184 documents. This will make the user download smaller (it's getting
3174 too big).
3185 too big).
3175
3186
3176 2002-05-29 Fernando Perez <fperez@colorado.edu>
3187 2002-05-29 Fernando Perez <fperez@colorado.edu>
3177
3188
3178 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3189 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3179 fix problems with shelve and pickle. Seems to work, but I don't
3190 fix problems with shelve and pickle. Seems to work, but I don't
3180 know if corner cases break it. Thanks to Mike Heeter
3191 know if corner cases break it. Thanks to Mike Heeter
3181 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3192 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3182
3193
3183 2002-05-24 Fernando Perez <fperez@colorado.edu>
3194 2002-05-24 Fernando Perez <fperez@colorado.edu>
3184
3195
3185 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3196 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3186 macros having broken.
3197 macros having broken.
3187
3198
3188 2002-05-21 Fernando Perez <fperez@colorado.edu>
3199 2002-05-21 Fernando Perez <fperez@colorado.edu>
3189
3200
3190 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3201 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3191 introduced logging bug: all history before logging started was
3202 introduced logging bug: all history before logging started was
3192 being written one character per line! This came from the redesign
3203 being written one character per line! This came from the redesign
3193 of the input history as a special list which slices to strings,
3204 of the input history as a special list which slices to strings,
3194 not to lists.
3205 not to lists.
3195
3206
3196 2002-05-20 Fernando Perez <fperez@colorado.edu>
3207 2002-05-20 Fernando Perez <fperez@colorado.edu>
3197
3208
3198 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3209 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3199 be an attribute of all classes in this module. The design of these
3210 be an attribute of all classes in this module. The design of these
3200 classes needs some serious overhauling.
3211 classes needs some serious overhauling.
3201
3212
3202 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3213 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3203 which was ignoring '_' in option names.
3214 which was ignoring '_' in option names.
3204
3215
3205 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3216 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3206 'Verbose_novars' to 'Context' and made it the new default. It's a
3217 'Verbose_novars' to 'Context' and made it the new default. It's a
3207 bit more readable and also safer than verbose.
3218 bit more readable and also safer than verbose.
3208
3219
3209 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3220 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3210 triple-quoted strings.
3221 triple-quoted strings.
3211
3222
3212 * IPython/OInspect.py (__all__): new module exposing the object
3223 * IPython/OInspect.py (__all__): new module exposing the object
3213 introspection facilities. Now the corresponding magics are dummy
3224 introspection facilities. Now the corresponding magics are dummy
3214 wrappers around this. Having this module will make it much easier
3225 wrappers around this. Having this module will make it much easier
3215 to put these functions into our modified pdb.
3226 to put these functions into our modified pdb.
3216 This new object inspector system uses the new colorizing module,
3227 This new object inspector system uses the new colorizing module,
3217 so source code and other things are nicely syntax highlighted.
3228 so source code and other things are nicely syntax highlighted.
3218
3229
3219 2002-05-18 Fernando Perez <fperez@colorado.edu>
3230 2002-05-18 Fernando Perez <fperez@colorado.edu>
3220
3231
3221 * IPython/ColorANSI.py: Split the coloring tools into a separate
3232 * IPython/ColorANSI.py: Split the coloring tools into a separate
3222 module so I can use them in other code easier (they were part of
3233 module so I can use them in other code easier (they were part of
3223 ultraTB).
3234 ultraTB).
3224
3235
3225 2002-05-17 Fernando Perez <fperez@colorado.edu>
3236 2002-05-17 Fernando Perez <fperez@colorado.edu>
3226
3237
3227 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3238 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3228 fixed it to set the global 'g' also to the called instance, as
3239 fixed it to set the global 'g' also to the called instance, as
3229 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3240 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3230 user's 'g' variables).
3241 user's 'g' variables).
3231
3242
3232 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3243 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3233 global variables (aliases to _ih,_oh) so that users which expect
3244 global variables (aliases to _ih,_oh) so that users which expect
3234 In[5] or Out[7] to work aren't unpleasantly surprised.
3245 In[5] or Out[7] to work aren't unpleasantly surprised.
3235 (InputList.__getslice__): new class to allow executing slices of
3246 (InputList.__getslice__): new class to allow executing slices of
3236 input history directly. Very simple class, complements the use of
3247 input history directly. Very simple class, complements the use of
3237 macros.
3248 macros.
3238
3249
3239 2002-05-16 Fernando Perez <fperez@colorado.edu>
3250 2002-05-16 Fernando Perez <fperez@colorado.edu>
3240
3251
3241 * setup.py (docdirbase): make doc directory be just doc/IPython
3252 * setup.py (docdirbase): make doc directory be just doc/IPython
3242 without version numbers, it will reduce clutter for users.
3253 without version numbers, it will reduce clutter for users.
3243
3254
3244 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3255 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3245 execfile call to prevent possible memory leak. See for details:
3256 execfile call to prevent possible memory leak. See for details:
3246 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3257 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3247
3258
3248 2002-05-15 Fernando Perez <fperez@colorado.edu>
3259 2002-05-15 Fernando Perez <fperez@colorado.edu>
3249
3260
3250 * IPython/Magic.py (Magic.magic_psource): made the object
3261 * IPython/Magic.py (Magic.magic_psource): made the object
3251 introspection names be more standard: pdoc, pdef, pfile and
3262 introspection names be more standard: pdoc, pdef, pfile and
3252 psource. They all print/page their output, and it makes
3263 psource. They all print/page their output, and it makes
3253 remembering them easier. Kept old names for compatibility as
3264 remembering them easier. Kept old names for compatibility as
3254 aliases.
3265 aliases.
3255
3266
3256 2002-05-14 Fernando Perez <fperez@colorado.edu>
3267 2002-05-14 Fernando Perez <fperez@colorado.edu>
3257
3268
3258 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3269 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3259 what the mouse problem was. The trick is to use gnuplot with temp
3270 what the mouse problem was. The trick is to use gnuplot with temp
3260 files and NOT with pipes (for data communication), because having
3271 files and NOT with pipes (for data communication), because having
3261 both pipes and the mouse on is bad news.
3272 both pipes and the mouse on is bad news.
3262
3273
3263 2002-05-13 Fernando Perez <fperez@colorado.edu>
3274 2002-05-13 Fernando Perez <fperez@colorado.edu>
3264
3275
3265 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3276 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3266 bug. Information would be reported about builtins even when
3277 bug. Information would be reported about builtins even when
3267 user-defined functions overrode them.
3278 user-defined functions overrode them.
3268
3279
3269 2002-05-11 Fernando Perez <fperez@colorado.edu>
3280 2002-05-11 Fernando Perez <fperez@colorado.edu>
3270
3281
3271 * IPython/__init__.py (__all__): removed FlexCompleter from
3282 * IPython/__init__.py (__all__): removed FlexCompleter from
3272 __all__ so that things don't fail in platforms without readline.
3283 __all__ so that things don't fail in platforms without readline.
3273
3284
3274 2002-05-10 Fernando Perez <fperez@colorado.edu>
3285 2002-05-10 Fernando Perez <fperez@colorado.edu>
3275
3286
3276 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3287 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3277 it requires Numeric, effectively making Numeric a dependency for
3288 it requires Numeric, effectively making Numeric a dependency for
3278 IPython.
3289 IPython.
3279
3290
3280 * Released 0.2.13
3291 * Released 0.2.13
3281
3292
3282 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3293 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3283 profiler interface. Now all the major options from the profiler
3294 profiler interface. Now all the major options from the profiler
3284 module are directly supported in IPython, both for single
3295 module are directly supported in IPython, both for single
3285 expressions (@prun) and for full programs (@run -p).
3296 expressions (@prun) and for full programs (@run -p).
3286
3297
3287 2002-05-09 Fernando Perez <fperez@colorado.edu>
3298 2002-05-09 Fernando Perez <fperez@colorado.edu>
3288
3299
3289 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3300 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3290 magic properly formatted for screen.
3301 magic properly formatted for screen.
3291
3302
3292 * setup.py (make_shortcut): Changed things to put pdf version in
3303 * setup.py (make_shortcut): Changed things to put pdf version in
3293 doc/ instead of doc/manual (had to change lyxport a bit).
3304 doc/ instead of doc/manual (had to change lyxport a bit).
3294
3305
3295 * IPython/Magic.py (Profile.string_stats): made profile runs go
3306 * IPython/Magic.py (Profile.string_stats): made profile runs go
3296 through pager (they are long and a pager allows searching, saving,
3307 through pager (they are long and a pager allows searching, saving,
3297 etc.)
3308 etc.)
3298
3309
3299 2002-05-08 Fernando Perez <fperez@colorado.edu>
3310 2002-05-08 Fernando Perez <fperez@colorado.edu>
3300
3311
3301 * Released 0.2.12
3312 * Released 0.2.12
3302
3313
3303 2002-05-06 Fernando Perez <fperez@colorado.edu>
3314 2002-05-06 Fernando Perez <fperez@colorado.edu>
3304
3315
3305 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3316 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3306 introduced); 'hist n1 n2' was broken.
3317 introduced); 'hist n1 n2' was broken.
3307 (Magic.magic_pdb): added optional on/off arguments to @pdb
3318 (Magic.magic_pdb): added optional on/off arguments to @pdb
3308 (Magic.magic_run): added option -i to @run, which executes code in
3319 (Magic.magic_run): added option -i to @run, which executes code in
3309 the IPython namespace instead of a clean one. Also added @irun as
3320 the IPython namespace instead of a clean one. Also added @irun as
3310 an alias to @run -i.
3321 an alias to @run -i.
3311
3322
3312 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3323 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3313 fixed (it didn't really do anything, the namespaces were wrong).
3324 fixed (it didn't really do anything, the namespaces were wrong).
3314
3325
3315 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3326 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3316
3327
3317 * IPython/__init__.py (__all__): Fixed package namespace, now
3328 * IPython/__init__.py (__all__): Fixed package namespace, now
3318 'import IPython' does give access to IPython.<all> as
3329 'import IPython' does give access to IPython.<all> as
3319 expected. Also renamed __release__ to Release.
3330 expected. Also renamed __release__ to Release.
3320
3331
3321 * IPython/Debugger.py (__license__): created new Pdb class which
3332 * IPython/Debugger.py (__license__): created new Pdb class which
3322 functions like a drop-in for the normal pdb.Pdb but does NOT
3333 functions like a drop-in for the normal pdb.Pdb but does NOT
3323 import readline by default. This way it doesn't muck up IPython's
3334 import readline by default. This way it doesn't muck up IPython's
3324 readline handling, and now tab-completion finally works in the
3335 readline handling, and now tab-completion finally works in the
3325 debugger -- sort of. It completes things globally visible, but the
3336 debugger -- sort of. It completes things globally visible, but the
3326 completer doesn't track the stack as pdb walks it. That's a bit
3337 completer doesn't track the stack as pdb walks it. That's a bit
3327 tricky, and I'll have to implement it later.
3338 tricky, and I'll have to implement it later.
3328
3339
3329 2002-05-05 Fernando Perez <fperez@colorado.edu>
3340 2002-05-05 Fernando Perez <fperez@colorado.edu>
3330
3341
3331 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3342 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3332 magic docstrings when printed via ? (explicit \'s were being
3343 magic docstrings when printed via ? (explicit \'s were being
3333 printed).
3344 printed).
3334
3345
3335 * IPython/ipmaker.py (make_IPython): fixed namespace
3346 * IPython/ipmaker.py (make_IPython): fixed namespace
3336 identification bug. Now variables loaded via logs or command-line
3347 identification bug. Now variables loaded via logs or command-line
3337 files are recognized in the interactive namespace by @who.
3348 files are recognized in the interactive namespace by @who.
3338
3349
3339 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3350 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3340 log replay system stemming from the string form of Structs.
3351 log replay system stemming from the string form of Structs.
3341
3352
3342 * IPython/Magic.py (Macro.__init__): improved macros to properly
3353 * IPython/Magic.py (Macro.__init__): improved macros to properly
3343 handle magic commands in them.
3354 handle magic commands in them.
3344 (Magic.magic_logstart): usernames are now expanded so 'logstart
3355 (Magic.magic_logstart): usernames are now expanded so 'logstart
3345 ~/mylog' now works.
3356 ~/mylog' now works.
3346
3357
3347 * IPython/iplib.py (complete): fixed bug where paths starting with
3358 * IPython/iplib.py (complete): fixed bug where paths starting with
3348 '/' would be completed as magic names.
3359 '/' would be completed as magic names.
3349
3360
3350 2002-05-04 Fernando Perez <fperez@colorado.edu>
3361 2002-05-04 Fernando Perez <fperez@colorado.edu>
3351
3362
3352 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3363 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3353 allow running full programs under the profiler's control.
3364 allow running full programs under the profiler's control.
3354
3365
3355 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3366 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3356 mode to report exceptions verbosely but without formatting
3367 mode to report exceptions verbosely but without formatting
3357 variables. This addresses the issue of ipython 'freezing' (it's
3368 variables. This addresses the issue of ipython 'freezing' (it's
3358 not frozen, but caught in an expensive formatting loop) when huge
3369 not frozen, but caught in an expensive formatting loop) when huge
3359 variables are in the context of an exception.
3370 variables are in the context of an exception.
3360 (VerboseTB.text): Added '--->' markers at line where exception was
3371 (VerboseTB.text): Added '--->' markers at line where exception was
3361 triggered. Much clearer to read, especially in NoColor modes.
3372 triggered. Much clearer to read, especially in NoColor modes.
3362
3373
3363 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3374 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3364 implemented in reverse when changing to the new parse_options().
3375 implemented in reverse when changing to the new parse_options().
3365
3376
3366 2002-05-03 Fernando Perez <fperez@colorado.edu>
3377 2002-05-03 Fernando Perez <fperez@colorado.edu>
3367
3378
3368 * IPython/Magic.py (Magic.parse_options): new function so that
3379 * IPython/Magic.py (Magic.parse_options): new function so that
3369 magics can parse options easier.
3380 magics can parse options easier.
3370 (Magic.magic_prun): new function similar to profile.run(),
3381 (Magic.magic_prun): new function similar to profile.run(),
3371 suggested by Chris Hart.
3382 suggested by Chris Hart.
3372 (Magic.magic_cd): fixed behavior so that it only changes if
3383 (Magic.magic_cd): fixed behavior so that it only changes if
3373 directory actually is in history.
3384 directory actually is in history.
3374
3385
3375 * IPython/usage.py (__doc__): added information about potential
3386 * IPython/usage.py (__doc__): added information about potential
3376 slowness of Verbose exception mode when there are huge data
3387 slowness of Verbose exception mode when there are huge data
3377 structures to be formatted (thanks to Archie Paulson).
3388 structures to be formatted (thanks to Archie Paulson).
3378
3389
3379 * IPython/ipmaker.py (make_IPython): Changed default logging
3390 * IPython/ipmaker.py (make_IPython): Changed default logging
3380 (when simply called with -log) to use curr_dir/ipython.log in
3391 (when simply called with -log) to use curr_dir/ipython.log in
3381 rotate mode. Fixed crash which was occuring with -log before
3392 rotate mode. Fixed crash which was occuring with -log before
3382 (thanks to Jim Boyle).
3393 (thanks to Jim Boyle).
3383
3394
3384 2002-05-01 Fernando Perez <fperez@colorado.edu>
3395 2002-05-01 Fernando Perez <fperez@colorado.edu>
3385
3396
3386 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3397 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3387 was nasty -- though somewhat of a corner case).
3398 was nasty -- though somewhat of a corner case).
3388
3399
3389 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3400 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3390 text (was a bug).
3401 text (was a bug).
3391
3402
3392 2002-04-30 Fernando Perez <fperez@colorado.edu>
3403 2002-04-30 Fernando Perez <fperez@colorado.edu>
3393
3404
3394 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3405 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3395 a print after ^D or ^C from the user so that the In[] prompt
3406 a print after ^D or ^C from the user so that the In[] prompt
3396 doesn't over-run the gnuplot one.
3407 doesn't over-run the gnuplot one.
3397
3408
3398 2002-04-29 Fernando Perez <fperez@colorado.edu>
3409 2002-04-29 Fernando Perez <fperez@colorado.edu>
3399
3410
3400 * Released 0.2.10
3411 * Released 0.2.10
3401
3412
3402 * IPython/__release__.py (version): get date dynamically.
3413 * IPython/__release__.py (version): get date dynamically.
3403
3414
3404 * Misc. documentation updates thanks to Arnd's comments. Also ran
3415 * Misc. documentation updates thanks to Arnd's comments. Also ran
3405 a full spellcheck on the manual (hadn't been done in a while).
3416 a full spellcheck on the manual (hadn't been done in a while).
3406
3417
3407 2002-04-27 Fernando Perez <fperez@colorado.edu>
3418 2002-04-27 Fernando Perez <fperez@colorado.edu>
3408
3419
3409 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3420 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3410 starting a log in mid-session would reset the input history list.
3421 starting a log in mid-session would reset the input history list.
3411
3422
3412 2002-04-26 Fernando Perez <fperez@colorado.edu>
3423 2002-04-26 Fernando Perez <fperez@colorado.edu>
3413
3424
3414 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3425 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3415 all files were being included in an update. Now anything in
3426 all files were being included in an update. Now anything in
3416 UserConfig that matches [A-Za-z]*.py will go (this excludes
3427 UserConfig that matches [A-Za-z]*.py will go (this excludes
3417 __init__.py)
3428 __init__.py)
3418
3429
3419 2002-04-25 Fernando Perez <fperez@colorado.edu>
3430 2002-04-25 Fernando Perez <fperez@colorado.edu>
3420
3431
3421 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3432 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3422 to __builtins__ so that any form of embedded or imported code can
3433 to __builtins__ so that any form of embedded or imported code can
3423 test for being inside IPython.
3434 test for being inside IPython.
3424
3435
3425 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3436 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3426 changed to GnuplotMagic because it's now an importable module,
3437 changed to GnuplotMagic because it's now an importable module,
3427 this makes the name follow that of the standard Gnuplot module.
3438 this makes the name follow that of the standard Gnuplot module.
3428 GnuplotMagic can now be loaded at any time in mid-session.
3439 GnuplotMagic can now be loaded at any time in mid-session.
3429
3440
3430 2002-04-24 Fernando Perez <fperez@colorado.edu>
3441 2002-04-24 Fernando Perez <fperez@colorado.edu>
3431
3442
3432 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3443 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3433 the globals (IPython has its own namespace) and the
3444 the globals (IPython has its own namespace) and the
3434 PhysicalQuantity stuff is much better anyway.
3445 PhysicalQuantity stuff is much better anyway.
3435
3446
3436 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3447 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3437 embedding example to standard user directory for
3448 embedding example to standard user directory for
3438 distribution. Also put it in the manual.
3449 distribution. Also put it in the manual.
3439
3450
3440 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3451 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3441 instance as first argument (so it doesn't rely on some obscure
3452 instance as first argument (so it doesn't rely on some obscure
3442 hidden global).
3453 hidden global).
3443
3454
3444 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3455 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3445 delimiters. While it prevents ().TAB from working, it allows
3456 delimiters. While it prevents ().TAB from working, it allows
3446 completions in open (... expressions. This is by far a more common
3457 completions in open (... expressions. This is by far a more common
3447 case.
3458 case.
3448
3459
3449 2002-04-23 Fernando Perez <fperez@colorado.edu>
3460 2002-04-23 Fernando Perez <fperez@colorado.edu>
3450
3461
3451 * IPython/Extensions/InterpreterPasteInput.py: new
3462 * IPython/Extensions/InterpreterPasteInput.py: new
3452 syntax-processing module for pasting lines with >>> or ... at the
3463 syntax-processing module for pasting lines with >>> or ... at the
3453 start.
3464 start.
3454
3465
3455 * IPython/Extensions/PhysicalQ_Interactive.py
3466 * IPython/Extensions/PhysicalQ_Interactive.py
3456 (PhysicalQuantityInteractive.__int__): fixed to work with either
3467 (PhysicalQuantityInteractive.__int__): fixed to work with either
3457 Numeric or math.
3468 Numeric or math.
3458
3469
3459 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3470 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3460 provided profiles. Now we have:
3471 provided profiles. Now we have:
3461 -math -> math module as * and cmath with its own namespace.
3472 -math -> math module as * and cmath with its own namespace.
3462 -numeric -> Numeric as *, plus gnuplot & grace
3473 -numeric -> Numeric as *, plus gnuplot & grace
3463 -physics -> same as before
3474 -physics -> same as before
3464
3475
3465 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3476 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3466 user-defined magics wouldn't be found by @magic if they were
3477 user-defined magics wouldn't be found by @magic if they were
3467 defined as class methods. Also cleaned up the namespace search
3478 defined as class methods. Also cleaned up the namespace search
3468 logic and the string building (to use %s instead of many repeated
3479 logic and the string building (to use %s instead of many repeated
3469 string adds).
3480 string adds).
3470
3481
3471 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3482 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3472 of user-defined magics to operate with class methods (cleaner, in
3483 of user-defined magics to operate with class methods (cleaner, in
3473 line with the gnuplot code).
3484 line with the gnuplot code).
3474
3485
3475 2002-04-22 Fernando Perez <fperez@colorado.edu>
3486 2002-04-22 Fernando Perez <fperez@colorado.edu>
3476
3487
3477 * setup.py: updated dependency list so that manual is updated when
3488 * setup.py: updated dependency list so that manual is updated when
3478 all included files change.
3489 all included files change.
3479
3490
3480 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3491 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3481 the delimiter removal option (the fix is ugly right now).
3492 the delimiter removal option (the fix is ugly right now).
3482
3493
3483 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3494 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3484 all of the math profile (quicker loading, no conflict between
3495 all of the math profile (quicker loading, no conflict between
3485 g-9.8 and g-gnuplot).
3496 g-9.8 and g-gnuplot).
3486
3497
3487 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3498 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3488 name of post-mortem files to IPython_crash_report.txt.
3499 name of post-mortem files to IPython_crash_report.txt.
3489
3500
3490 * Cleanup/update of the docs. Added all the new readline info and
3501 * Cleanup/update of the docs. Added all the new readline info and
3491 formatted all lists as 'real lists'.
3502 formatted all lists as 'real lists'.
3492
3503
3493 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3504 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3494 tab-completion options, since the full readline parse_and_bind is
3505 tab-completion options, since the full readline parse_and_bind is
3495 now accessible.
3506 now accessible.
3496
3507
3497 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3508 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3498 handling of readline options. Now users can specify any string to
3509 handling of readline options. Now users can specify any string to
3499 be passed to parse_and_bind(), as well as the delimiters to be
3510 be passed to parse_and_bind(), as well as the delimiters to be
3500 removed.
3511 removed.
3501 (InteractiveShell.__init__): Added __name__ to the global
3512 (InteractiveShell.__init__): Added __name__ to the global
3502 namespace so that things like Itpl which rely on its existence
3513 namespace so that things like Itpl which rely on its existence
3503 don't crash.
3514 don't crash.
3504 (InteractiveShell._prefilter): Defined the default with a _ so
3515 (InteractiveShell._prefilter): Defined the default with a _ so
3505 that prefilter() is easier to override, while the default one
3516 that prefilter() is easier to override, while the default one
3506 remains available.
3517 remains available.
3507
3518
3508 2002-04-18 Fernando Perez <fperez@colorado.edu>
3519 2002-04-18 Fernando Perez <fperez@colorado.edu>
3509
3520
3510 * Added information about pdb in the docs.
3521 * Added information about pdb in the docs.
3511
3522
3512 2002-04-17 Fernando Perez <fperez@colorado.edu>
3523 2002-04-17 Fernando Perez <fperez@colorado.edu>
3513
3524
3514 * IPython/ipmaker.py (make_IPython): added rc_override option to
3525 * IPython/ipmaker.py (make_IPython): added rc_override option to
3515 allow passing config options at creation time which may override
3526 allow passing config options at creation time which may override
3516 anything set in the config files or command line. This is
3527 anything set in the config files or command line. This is
3517 particularly useful for configuring embedded instances.
3528 particularly useful for configuring embedded instances.
3518
3529
3519 2002-04-15 Fernando Perez <fperez@colorado.edu>
3530 2002-04-15 Fernando Perez <fperez@colorado.edu>
3520
3531
3521 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3532 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3522 crash embedded instances because of the input cache falling out of
3533 crash embedded instances because of the input cache falling out of
3523 sync with the output counter.
3534 sync with the output counter.
3524
3535
3525 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3536 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3526 mode which calls pdb after an uncaught exception in IPython itself.
3537 mode which calls pdb after an uncaught exception in IPython itself.
3527
3538
3528 2002-04-14 Fernando Perez <fperez@colorado.edu>
3539 2002-04-14 Fernando Perez <fperez@colorado.edu>
3529
3540
3530 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3541 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3531 readline, fix it back after each call.
3542 readline, fix it back after each call.
3532
3543
3533 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3544 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3534 method to force all access via __call__(), which guarantees that
3545 method to force all access via __call__(), which guarantees that
3535 traceback references are properly deleted.
3546 traceback references are properly deleted.
3536
3547
3537 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3548 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3538 improve printing when pprint is in use.
3549 improve printing when pprint is in use.
3539
3550
3540 2002-04-13 Fernando Perez <fperez@colorado.edu>
3551 2002-04-13 Fernando Perez <fperez@colorado.edu>
3541
3552
3542 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3553 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3543 exceptions aren't caught anymore. If the user triggers one, he
3554 exceptions aren't caught anymore. If the user triggers one, he
3544 should know why he's doing it and it should go all the way up,
3555 should know why he's doing it and it should go all the way up,
3545 just like any other exception. So now @abort will fully kill the
3556 just like any other exception. So now @abort will fully kill the
3546 embedded interpreter and the embedding code (unless that happens
3557 embedded interpreter and the embedding code (unless that happens
3547 to catch SystemExit).
3558 to catch SystemExit).
3548
3559
3549 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3560 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3550 and a debugger() method to invoke the interactive pdb debugger
3561 and a debugger() method to invoke the interactive pdb debugger
3551 after printing exception information. Also added the corresponding
3562 after printing exception information. Also added the corresponding
3552 -pdb option and @pdb magic to control this feature, and updated
3563 -pdb option and @pdb magic to control this feature, and updated
3553 the docs. After a suggestion from Christopher Hart
3564 the docs. After a suggestion from Christopher Hart
3554 (hart-AT-caltech.edu).
3565 (hart-AT-caltech.edu).
3555
3566
3556 2002-04-12 Fernando Perez <fperez@colorado.edu>
3567 2002-04-12 Fernando Perez <fperez@colorado.edu>
3557
3568
3558 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3569 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3559 the exception handlers defined by the user (not the CrashHandler)
3570 the exception handlers defined by the user (not the CrashHandler)
3560 so that user exceptions don't trigger an ipython bug report.
3571 so that user exceptions don't trigger an ipython bug report.
3561
3572
3562 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3573 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3563 configurable (it should have always been so).
3574 configurable (it should have always been so).
3564
3575
3565 2002-03-26 Fernando Perez <fperez@colorado.edu>
3576 2002-03-26 Fernando Perez <fperez@colorado.edu>
3566
3577
3567 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3578 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3568 and there to fix embedding namespace issues. This should all be
3579 and there to fix embedding namespace issues. This should all be
3569 done in a more elegant way.
3580 done in a more elegant way.
3570
3581
3571 2002-03-25 Fernando Perez <fperez@colorado.edu>
3582 2002-03-25 Fernando Perez <fperez@colorado.edu>
3572
3583
3573 * IPython/genutils.py (get_home_dir): Try to make it work under
3584 * IPython/genutils.py (get_home_dir): Try to make it work under
3574 win9x also.
3585 win9x also.
3575
3586
3576 2002-03-20 Fernando Perez <fperez@colorado.edu>
3587 2002-03-20 Fernando Perez <fperez@colorado.edu>
3577
3588
3578 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3589 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3579 sys.displayhook untouched upon __init__.
3590 sys.displayhook untouched upon __init__.
3580
3591
3581 2002-03-19 Fernando Perez <fperez@colorado.edu>
3592 2002-03-19 Fernando Perez <fperez@colorado.edu>
3582
3593
3583 * Released 0.2.9 (for embedding bug, basically).
3594 * Released 0.2.9 (for embedding bug, basically).
3584
3595
3585 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3596 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3586 exceptions so that enclosing shell's state can be restored.
3597 exceptions so that enclosing shell's state can be restored.
3587
3598
3588 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3599 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3589 naming conventions in the .ipython/ dir.
3600 naming conventions in the .ipython/ dir.
3590
3601
3591 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3602 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3592 from delimiters list so filenames with - in them get expanded.
3603 from delimiters list so filenames with - in them get expanded.
3593
3604
3594 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3605 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3595 sys.displayhook not being properly restored after an embedded call.
3606 sys.displayhook not being properly restored after an embedded call.
3596
3607
3597 2002-03-18 Fernando Perez <fperez@colorado.edu>
3608 2002-03-18 Fernando Perez <fperez@colorado.edu>
3598
3609
3599 * Released 0.2.8
3610 * Released 0.2.8
3600
3611
3601 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3612 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3602 some files weren't being included in a -upgrade.
3613 some files weren't being included in a -upgrade.
3603 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3614 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3604 on' so that the first tab completes.
3615 on' so that the first tab completes.
3605 (InteractiveShell.handle_magic): fixed bug with spaces around
3616 (InteractiveShell.handle_magic): fixed bug with spaces around
3606 quotes breaking many magic commands.
3617 quotes breaking many magic commands.
3607
3618
3608 * setup.py: added note about ignoring the syntax error messages at
3619 * setup.py: added note about ignoring the syntax error messages at
3609 installation.
3620 installation.
3610
3621
3611 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3622 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3612 streamlining the gnuplot interface, now there's only one magic @gp.
3623 streamlining the gnuplot interface, now there's only one magic @gp.
3613
3624
3614 2002-03-17 Fernando Perez <fperez@colorado.edu>
3625 2002-03-17 Fernando Perez <fperez@colorado.edu>
3615
3626
3616 * IPython/UserConfig/magic_gnuplot.py: new name for the
3627 * IPython/UserConfig/magic_gnuplot.py: new name for the
3617 example-magic_pm.py file. Much enhanced system, now with a shell
3628 example-magic_pm.py file. Much enhanced system, now with a shell
3618 for communicating directly with gnuplot, one command at a time.
3629 for communicating directly with gnuplot, one command at a time.
3619
3630
3620 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3631 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3621 setting __name__=='__main__'.
3632 setting __name__=='__main__'.
3622
3633
3623 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3634 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3624 mini-shell for accessing gnuplot from inside ipython. Should
3635 mini-shell for accessing gnuplot from inside ipython. Should
3625 extend it later for grace access too. Inspired by Arnd's
3636 extend it later for grace access too. Inspired by Arnd's
3626 suggestion.
3637 suggestion.
3627
3638
3628 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3639 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3629 calling magic functions with () in their arguments. Thanks to Arnd
3640 calling magic functions with () in their arguments. Thanks to Arnd
3630 Baecker for pointing this to me.
3641 Baecker for pointing this to me.
3631
3642
3632 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3643 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3633 infinitely for integer or complex arrays (only worked with floats).
3644 infinitely for integer or complex arrays (only worked with floats).
3634
3645
3635 2002-03-16 Fernando Perez <fperez@colorado.edu>
3646 2002-03-16 Fernando Perez <fperez@colorado.edu>
3636
3647
3637 * setup.py: Merged setup and setup_windows into a single script
3648 * setup.py: Merged setup and setup_windows into a single script
3638 which properly handles things for windows users.
3649 which properly handles things for windows users.
3639
3650
3640 2002-03-15 Fernando Perez <fperez@colorado.edu>
3651 2002-03-15 Fernando Perez <fperez@colorado.edu>
3641
3652
3642 * Big change to the manual: now the magics are all automatically
3653 * Big change to the manual: now the magics are all automatically
3643 documented. This information is generated from their docstrings
3654 documented. This information is generated from their docstrings
3644 and put in a latex file included by the manual lyx file. This way
3655 and put in a latex file included by the manual lyx file. This way
3645 we get always up to date information for the magics. The manual
3656 we get always up to date information for the magics. The manual
3646 now also has proper version information, also auto-synced.
3657 now also has proper version information, also auto-synced.
3647
3658
3648 For this to work, an undocumented --magic_docstrings option was added.
3659 For this to work, an undocumented --magic_docstrings option was added.
3649
3660
3650 2002-03-13 Fernando Perez <fperez@colorado.edu>
3661 2002-03-13 Fernando Perez <fperez@colorado.edu>
3651
3662
3652 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3663 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3653 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3664 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3654
3665
3655 2002-03-12 Fernando Perez <fperez@colorado.edu>
3666 2002-03-12 Fernando Perez <fperez@colorado.edu>
3656
3667
3657 * IPython/ultraTB.py (TermColors): changed color escapes again to
3668 * IPython/ultraTB.py (TermColors): changed color escapes again to
3658 fix the (old, reintroduced) line-wrapping bug. Basically, if
3669 fix the (old, reintroduced) line-wrapping bug. Basically, if
3659 \001..\002 aren't given in the color escapes, lines get wrapped
3670 \001..\002 aren't given in the color escapes, lines get wrapped
3660 weirdly. But giving those screws up old xterms and emacs terms. So
3671 weirdly. But giving those screws up old xterms and emacs terms. So
3661 I added some logic for emacs terms to be ok, but I can't identify old
3672 I added some logic for emacs terms to be ok, but I can't identify old
3662 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3673 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3663
3674
3664 2002-03-10 Fernando Perez <fperez@colorado.edu>
3675 2002-03-10 Fernando Perez <fperez@colorado.edu>
3665
3676
3666 * IPython/usage.py (__doc__): Various documentation cleanups and
3677 * IPython/usage.py (__doc__): Various documentation cleanups and
3667 updates, both in usage docstrings and in the manual.
3678 updates, both in usage docstrings and in the manual.
3668
3679
3669 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3680 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3670 handling of caching. Set minimum acceptabe value for having a
3681 handling of caching. Set minimum acceptabe value for having a
3671 cache at 20 values.
3682 cache at 20 values.
3672
3683
3673 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3684 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3674 install_first_time function to a method, renamed it and added an
3685 install_first_time function to a method, renamed it and added an
3675 'upgrade' mode. Now people can update their config directory with
3686 'upgrade' mode. Now people can update their config directory with
3676 a simple command line switch (-upgrade, also new).
3687 a simple command line switch (-upgrade, also new).
3677
3688
3678 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3689 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3679 @file (convenient for automagic users under Python >= 2.2).
3690 @file (convenient for automagic users under Python >= 2.2).
3680 Removed @files (it seemed more like a plural than an abbrev. of
3691 Removed @files (it seemed more like a plural than an abbrev. of
3681 'file show').
3692 'file show').
3682
3693
3683 * IPython/iplib.py (install_first_time): Fixed crash if there were
3694 * IPython/iplib.py (install_first_time): Fixed crash if there were
3684 backup files ('~') in .ipython/ install directory.
3695 backup files ('~') in .ipython/ install directory.
3685
3696
3686 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3697 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3687 system. Things look fine, but these changes are fairly
3698 system. Things look fine, but these changes are fairly
3688 intrusive. Test them for a few days.
3699 intrusive. Test them for a few days.
3689
3700
3690 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3701 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3691 the prompts system. Now all in/out prompt strings are user
3702 the prompts system. Now all in/out prompt strings are user
3692 controllable. This is particularly useful for embedding, as one
3703 controllable. This is particularly useful for embedding, as one
3693 can tag embedded instances with particular prompts.
3704 can tag embedded instances with particular prompts.
3694
3705
3695 Also removed global use of sys.ps1/2, which now allows nested
3706 Also removed global use of sys.ps1/2, which now allows nested
3696 embeddings without any problems. Added command-line options for
3707 embeddings without any problems. Added command-line options for
3697 the prompt strings.
3708 the prompt strings.
3698
3709
3699 2002-03-08 Fernando Perez <fperez@colorado.edu>
3710 2002-03-08 Fernando Perez <fperez@colorado.edu>
3700
3711
3701 * IPython/UserConfig/example-embed-short.py (ipshell): added
3712 * IPython/UserConfig/example-embed-short.py (ipshell): added
3702 example file with the bare minimum code for embedding.
3713 example file with the bare minimum code for embedding.
3703
3714
3704 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3715 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3705 functionality for the embeddable shell to be activated/deactivated
3716 functionality for the embeddable shell to be activated/deactivated
3706 either globally or at each call.
3717 either globally or at each call.
3707
3718
3708 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3719 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3709 rewriting the prompt with '--->' for auto-inputs with proper
3720 rewriting the prompt with '--->' for auto-inputs with proper
3710 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3721 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3711 this is handled by the prompts class itself, as it should.
3722 this is handled by the prompts class itself, as it should.
3712
3723
3713 2002-03-05 Fernando Perez <fperez@colorado.edu>
3724 2002-03-05 Fernando Perez <fperez@colorado.edu>
3714
3725
3715 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3726 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3716 @logstart to avoid name clashes with the math log function.
3727 @logstart to avoid name clashes with the math log function.
3717
3728
3718 * Big updates to X/Emacs section of the manual.
3729 * Big updates to X/Emacs section of the manual.
3719
3730
3720 * Removed ipython_emacs. Milan explained to me how to pass
3731 * Removed ipython_emacs. Milan explained to me how to pass
3721 arguments to ipython through Emacs. Some day I'm going to end up
3732 arguments to ipython through Emacs. Some day I'm going to end up
3722 learning some lisp...
3733 learning some lisp...
3723
3734
3724 2002-03-04 Fernando Perez <fperez@colorado.edu>
3735 2002-03-04 Fernando Perez <fperez@colorado.edu>
3725
3736
3726 * IPython/ipython_emacs: Created script to be used as the
3737 * IPython/ipython_emacs: Created script to be used as the
3727 py-python-command Emacs variable so we can pass IPython
3738 py-python-command Emacs variable so we can pass IPython
3728 parameters. I can't figure out how to tell Emacs directly to pass
3739 parameters. I can't figure out how to tell Emacs directly to pass
3729 parameters to IPython, so a dummy shell script will do it.
3740 parameters to IPython, so a dummy shell script will do it.
3730
3741
3731 Other enhancements made for things to work better under Emacs'
3742 Other enhancements made for things to work better under Emacs'
3732 various types of terminals. Many thanks to Milan Zamazal
3743 various types of terminals. Many thanks to Milan Zamazal
3733 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3744 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3734
3745
3735 2002-03-01 Fernando Perez <fperez@colorado.edu>
3746 2002-03-01 Fernando Perez <fperez@colorado.edu>
3736
3747
3737 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3748 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3738 that loading of readline is now optional. This gives better
3749 that loading of readline is now optional. This gives better
3739 control to emacs users.
3750 control to emacs users.
3740
3751
3741 * IPython/ultraTB.py (__date__): Modified color escape sequences
3752 * IPython/ultraTB.py (__date__): Modified color escape sequences
3742 and now things work fine under xterm and in Emacs' term buffers
3753 and now things work fine under xterm and in Emacs' term buffers
3743 (though not shell ones). Well, in emacs you get colors, but all
3754 (though not shell ones). Well, in emacs you get colors, but all
3744 seem to be 'light' colors (no difference between dark and light
3755 seem to be 'light' colors (no difference between dark and light
3745 ones). But the garbage chars are gone, and also in xterms. It
3756 ones). But the garbage chars are gone, and also in xterms. It
3746 seems that now I'm using 'cleaner' ansi sequences.
3757 seems that now I'm using 'cleaner' ansi sequences.
3747
3758
3748 2002-02-21 Fernando Perez <fperez@colorado.edu>
3759 2002-02-21 Fernando Perez <fperez@colorado.edu>
3749
3760
3750 * Released 0.2.7 (mainly to publish the scoping fix).
3761 * Released 0.2.7 (mainly to publish the scoping fix).
3751
3762
3752 * IPython/Logger.py (Logger.logstate): added. A corresponding
3763 * IPython/Logger.py (Logger.logstate): added. A corresponding
3753 @logstate magic was created.
3764 @logstate magic was created.
3754
3765
3755 * IPython/Magic.py: fixed nested scoping problem under Python
3766 * IPython/Magic.py: fixed nested scoping problem under Python
3756 2.1.x (automagic wasn't working).
3767 2.1.x (automagic wasn't working).
3757
3768
3758 2002-02-20 Fernando Perez <fperez@colorado.edu>
3769 2002-02-20 Fernando Perez <fperez@colorado.edu>
3759
3770
3760 * Released 0.2.6.
3771 * Released 0.2.6.
3761
3772
3762 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3773 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3763 option so that logs can come out without any headers at all.
3774 option so that logs can come out without any headers at all.
3764
3775
3765 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3776 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3766 SciPy.
3777 SciPy.
3767
3778
3768 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3779 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3769 that embedded IPython calls don't require vars() to be explicitly
3780 that embedded IPython calls don't require vars() to be explicitly
3770 passed. Now they are extracted from the caller's frame (code
3781 passed. Now they are extracted from the caller's frame (code
3771 snatched from Eric Jones' weave). Added better documentation to
3782 snatched from Eric Jones' weave). Added better documentation to
3772 the section on embedding and the example file.
3783 the section on embedding and the example file.
3773
3784
3774 * IPython/genutils.py (page): Changed so that under emacs, it just
3785 * IPython/genutils.py (page): Changed so that under emacs, it just
3775 prints the string. You can then page up and down in the emacs
3786 prints the string. You can then page up and down in the emacs
3776 buffer itself. This is how the builtin help() works.
3787 buffer itself. This is how the builtin help() works.
3777
3788
3778 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3789 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3779 macro scoping: macros need to be executed in the user's namespace
3790 macro scoping: macros need to be executed in the user's namespace
3780 to work as if they had been typed by the user.
3791 to work as if they had been typed by the user.
3781
3792
3782 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3793 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3783 execute automatically (no need to type 'exec...'). They then
3794 execute automatically (no need to type 'exec...'). They then
3784 behave like 'true macros'. The printing system was also modified
3795 behave like 'true macros'. The printing system was also modified
3785 for this to work.
3796 for this to work.
3786
3797
3787 2002-02-19 Fernando Perez <fperez@colorado.edu>
3798 2002-02-19 Fernando Perez <fperez@colorado.edu>
3788
3799
3789 * IPython/genutils.py (page_file): new function for paging files
3800 * IPython/genutils.py (page_file): new function for paging files
3790 in an OS-independent way. Also necessary for file viewing to work
3801 in an OS-independent way. Also necessary for file viewing to work
3791 well inside Emacs buffers.
3802 well inside Emacs buffers.
3792 (page): Added checks for being in an emacs buffer.
3803 (page): Added checks for being in an emacs buffer.
3793 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3804 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3794 same bug in iplib.
3805 same bug in iplib.
3795
3806
3796 2002-02-18 Fernando Perez <fperez@colorado.edu>
3807 2002-02-18 Fernando Perez <fperez@colorado.edu>
3797
3808
3798 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3809 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3799 of readline so that IPython can work inside an Emacs buffer.
3810 of readline so that IPython can work inside an Emacs buffer.
3800
3811
3801 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3812 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3802 method signatures (they weren't really bugs, but it looks cleaner
3813 method signatures (they weren't really bugs, but it looks cleaner
3803 and keeps PyChecker happy).
3814 and keeps PyChecker happy).
3804
3815
3805 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3816 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3806 for implementing various user-defined hooks. Currently only
3817 for implementing various user-defined hooks. Currently only
3807 display is done.
3818 display is done.
3808
3819
3809 * IPython/Prompts.py (CachedOutput._display): changed display
3820 * IPython/Prompts.py (CachedOutput._display): changed display
3810 functions so that they can be dynamically changed by users easily.
3821 functions so that they can be dynamically changed by users easily.
3811
3822
3812 * IPython/Extensions/numeric_formats.py (num_display): added an
3823 * IPython/Extensions/numeric_formats.py (num_display): added an
3813 extension for printing NumPy arrays in flexible manners. It
3824 extension for printing NumPy arrays in flexible manners. It
3814 doesn't do anything yet, but all the structure is in
3825 doesn't do anything yet, but all the structure is in
3815 place. Ultimately the plan is to implement output format control
3826 place. Ultimately the plan is to implement output format control
3816 like in Octave.
3827 like in Octave.
3817
3828
3818 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3829 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3819 methods are found at run-time by all the automatic machinery.
3830 methods are found at run-time by all the automatic machinery.
3820
3831
3821 2002-02-17 Fernando Perez <fperez@colorado.edu>
3832 2002-02-17 Fernando Perez <fperez@colorado.edu>
3822
3833
3823 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3834 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3824 whole file a little.
3835 whole file a little.
3825
3836
3826 * ToDo: closed this document. Now there's a new_design.lyx
3837 * ToDo: closed this document. Now there's a new_design.lyx
3827 document for all new ideas. Added making a pdf of it for the
3838 document for all new ideas. Added making a pdf of it for the
3828 end-user distro.
3839 end-user distro.
3829
3840
3830 * IPython/Logger.py (Logger.switch_log): Created this to replace
3841 * IPython/Logger.py (Logger.switch_log): Created this to replace
3831 logon() and logoff(). It also fixes a nasty crash reported by
3842 logon() and logoff(). It also fixes a nasty crash reported by
3832 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3843 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3833
3844
3834 * IPython/iplib.py (complete): got auto-completion to work with
3845 * IPython/iplib.py (complete): got auto-completion to work with
3835 automagic (I had wanted this for a long time).
3846 automagic (I had wanted this for a long time).
3836
3847
3837 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3848 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3838 to @file, since file() is now a builtin and clashes with automagic
3849 to @file, since file() is now a builtin and clashes with automagic
3839 for @file.
3850 for @file.
3840
3851
3841 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3852 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3842 of this was previously in iplib, which had grown to more than 2000
3853 of this was previously in iplib, which had grown to more than 2000
3843 lines, way too long. No new functionality, but it makes managing
3854 lines, way too long. No new functionality, but it makes managing
3844 the code a bit easier.
3855 the code a bit easier.
3845
3856
3846 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3857 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3847 information to crash reports.
3858 information to crash reports.
3848
3859
3849 2002-02-12 Fernando Perez <fperez@colorado.edu>
3860 2002-02-12 Fernando Perez <fperez@colorado.edu>
3850
3861
3851 * Released 0.2.5.
3862 * Released 0.2.5.
3852
3863
3853 2002-02-11 Fernando Perez <fperez@colorado.edu>
3864 2002-02-11 Fernando Perez <fperez@colorado.edu>
3854
3865
3855 * Wrote a relatively complete Windows installer. It puts
3866 * Wrote a relatively complete Windows installer. It puts
3856 everything in place, creates Start Menu entries and fixes the
3867 everything in place, creates Start Menu entries and fixes the
3857 color issues. Nothing fancy, but it works.
3868 color issues. Nothing fancy, but it works.
3858
3869
3859 2002-02-10 Fernando Perez <fperez@colorado.edu>
3870 2002-02-10 Fernando Perez <fperez@colorado.edu>
3860
3871
3861 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3872 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3862 os.path.expanduser() call so that we can type @run ~/myfile.py and
3873 os.path.expanduser() call so that we can type @run ~/myfile.py and
3863 have thigs work as expected.
3874 have thigs work as expected.
3864
3875
3865 * IPython/genutils.py (page): fixed exception handling so things
3876 * IPython/genutils.py (page): fixed exception handling so things
3866 work both in Unix and Windows correctly. Quitting a pager triggers
3877 work both in Unix and Windows correctly. Quitting a pager triggers
3867 an IOError/broken pipe in Unix, and in windows not finding a pager
3878 an IOError/broken pipe in Unix, and in windows not finding a pager
3868 is also an IOError, so I had to actually look at the return value
3879 is also an IOError, so I had to actually look at the return value
3869 of the exception, not just the exception itself. Should be ok now.
3880 of the exception, not just the exception itself. Should be ok now.
3870
3881
3871 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3882 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3872 modified to allow case-insensitive color scheme changes.
3883 modified to allow case-insensitive color scheme changes.
3873
3884
3874 2002-02-09 Fernando Perez <fperez@colorado.edu>
3885 2002-02-09 Fernando Perez <fperez@colorado.edu>
3875
3886
3876 * IPython/genutils.py (native_line_ends): new function to leave
3887 * IPython/genutils.py (native_line_ends): new function to leave
3877 user config files with os-native line-endings.
3888 user config files with os-native line-endings.
3878
3889
3879 * README and manual updates.
3890 * README and manual updates.
3880
3891
3881 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3892 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3882 instead of StringType to catch Unicode strings.
3893 instead of StringType to catch Unicode strings.
3883
3894
3884 * IPython/genutils.py (filefind): fixed bug for paths with
3895 * IPython/genutils.py (filefind): fixed bug for paths with
3885 embedded spaces (very common in Windows).
3896 embedded spaces (very common in Windows).
3886
3897
3887 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3898 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3888 files under Windows, so that they get automatically associated
3899 files under Windows, so that they get automatically associated
3889 with a text editor. Windows makes it a pain to handle
3900 with a text editor. Windows makes it a pain to handle
3890 extension-less files.
3901 extension-less files.
3891
3902
3892 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3903 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3893 warning about readline only occur for Posix. In Windows there's no
3904 warning about readline only occur for Posix. In Windows there's no
3894 way to get readline, so why bother with the warning.
3905 way to get readline, so why bother with the warning.
3895
3906
3896 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3907 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3897 for __str__ instead of dir(self), since dir() changed in 2.2.
3908 for __str__ instead of dir(self), since dir() changed in 2.2.
3898
3909
3899 * Ported to Windows! Tested on XP, I suspect it should work fine
3910 * Ported to Windows! Tested on XP, I suspect it should work fine
3900 on NT/2000, but I don't think it will work on 98 et al. That
3911 on NT/2000, but I don't think it will work on 98 et al. That
3901 series of Windows is such a piece of junk anyway that I won't try
3912 series of Windows is such a piece of junk anyway that I won't try
3902 porting it there. The XP port was straightforward, showed a few
3913 porting it there. The XP port was straightforward, showed a few
3903 bugs here and there (fixed all), in particular some string
3914 bugs here and there (fixed all), in particular some string
3904 handling stuff which required considering Unicode strings (which
3915 handling stuff which required considering Unicode strings (which
3905 Windows uses). This is good, but hasn't been too tested :) No
3916 Windows uses). This is good, but hasn't been too tested :) No
3906 fancy installer yet, I'll put a note in the manual so people at
3917 fancy installer yet, I'll put a note in the manual so people at
3907 least make manually a shortcut.
3918 least make manually a shortcut.
3908
3919
3909 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3920 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3910 into a single one, "colors". This now controls both prompt and
3921 into a single one, "colors". This now controls both prompt and
3911 exception color schemes, and can be changed both at startup
3922 exception color schemes, and can be changed both at startup
3912 (either via command-line switches or via ipythonrc files) and at
3923 (either via command-line switches or via ipythonrc files) and at
3913 runtime, with @colors.
3924 runtime, with @colors.
3914 (Magic.magic_run): renamed @prun to @run and removed the old
3925 (Magic.magic_run): renamed @prun to @run and removed the old
3915 @run. The two were too similar to warrant keeping both.
3926 @run. The two were too similar to warrant keeping both.
3916
3927
3917 2002-02-03 Fernando Perez <fperez@colorado.edu>
3928 2002-02-03 Fernando Perez <fperez@colorado.edu>
3918
3929
3919 * IPython/iplib.py (install_first_time): Added comment on how to
3930 * IPython/iplib.py (install_first_time): Added comment on how to
3920 configure the color options for first-time users. Put a <return>
3931 configure the color options for first-time users. Put a <return>
3921 request at the end so that small-terminal users get a chance to
3932 request at the end so that small-terminal users get a chance to
3922 read the startup info.
3933 read the startup info.
3923
3934
3924 2002-01-23 Fernando Perez <fperez@colorado.edu>
3935 2002-01-23 Fernando Perez <fperez@colorado.edu>
3925
3936
3926 * IPython/iplib.py (CachedOutput.update): Changed output memory
3937 * IPython/iplib.py (CachedOutput.update): Changed output memory
3927 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3938 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3928 input history we still use _i. Did this b/c these variable are
3939 input history we still use _i. Did this b/c these variable are
3929 very commonly used in interactive work, so the less we need to
3940 very commonly used in interactive work, so the less we need to
3930 type the better off we are.
3941 type the better off we are.
3931 (Magic.magic_prun): updated @prun to better handle the namespaces
3942 (Magic.magic_prun): updated @prun to better handle the namespaces
3932 the file will run in, including a fix for __name__ not being set
3943 the file will run in, including a fix for __name__ not being set
3933 before.
3944 before.
3934
3945
3935 2002-01-20 Fernando Perez <fperez@colorado.edu>
3946 2002-01-20 Fernando Perez <fperez@colorado.edu>
3936
3947
3937 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3948 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3938 extra garbage for Python 2.2. Need to look more carefully into
3949 extra garbage for Python 2.2. Need to look more carefully into
3939 this later.
3950 this later.
3940
3951
3941 2002-01-19 Fernando Perez <fperez@colorado.edu>
3952 2002-01-19 Fernando Perez <fperez@colorado.edu>
3942
3953
3943 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3954 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3944 display SyntaxError exceptions properly formatted when they occur
3955 display SyntaxError exceptions properly formatted when they occur
3945 (they can be triggered by imported code).
3956 (they can be triggered by imported code).
3946
3957
3947 2002-01-18 Fernando Perez <fperez@colorado.edu>
3958 2002-01-18 Fernando Perez <fperez@colorado.edu>
3948
3959
3949 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3960 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3950 SyntaxError exceptions are reported nicely formatted, instead of
3961 SyntaxError exceptions are reported nicely formatted, instead of
3951 spitting out only offset information as before.
3962 spitting out only offset information as before.
3952 (Magic.magic_prun): Added the @prun function for executing
3963 (Magic.magic_prun): Added the @prun function for executing
3953 programs with command line args inside IPython.
3964 programs with command line args inside IPython.
3954
3965
3955 2002-01-16 Fernando Perez <fperez@colorado.edu>
3966 2002-01-16 Fernando Perez <fperez@colorado.edu>
3956
3967
3957 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3968 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3958 to *not* include the last item given in a range. This brings their
3969 to *not* include the last item given in a range. This brings their
3959 behavior in line with Python's slicing:
3970 behavior in line with Python's slicing:
3960 a[n1:n2] -> a[n1]...a[n2-1]
3971 a[n1:n2] -> a[n1]...a[n2-1]
3961 It may be a bit less convenient, but I prefer to stick to Python's
3972 It may be a bit less convenient, but I prefer to stick to Python's
3962 conventions *everywhere*, so users never have to wonder.
3973 conventions *everywhere*, so users never have to wonder.
3963 (Magic.magic_macro): Added @macro function to ease the creation of
3974 (Magic.magic_macro): Added @macro function to ease the creation of
3964 macros.
3975 macros.
3965
3976
3966 2002-01-05 Fernando Perez <fperez@colorado.edu>
3977 2002-01-05 Fernando Perez <fperez@colorado.edu>
3967
3978
3968 * Released 0.2.4.
3979 * Released 0.2.4.
3969
3980
3970 * IPython/iplib.py (Magic.magic_pdef):
3981 * IPython/iplib.py (Magic.magic_pdef):
3971 (InteractiveShell.safe_execfile): report magic lines and error
3982 (InteractiveShell.safe_execfile): report magic lines and error
3972 lines without line numbers so one can easily copy/paste them for
3983 lines without line numbers so one can easily copy/paste them for
3973 re-execution.
3984 re-execution.
3974
3985
3975 * Updated manual with recent changes.
3986 * Updated manual with recent changes.
3976
3987
3977 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3988 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3978 docstring printing when class? is called. Very handy for knowing
3989 docstring printing when class? is called. Very handy for knowing
3979 how to create class instances (as long as __init__ is well
3990 how to create class instances (as long as __init__ is well
3980 documented, of course :)
3991 documented, of course :)
3981 (Magic.magic_doc): print both class and constructor docstrings.
3992 (Magic.magic_doc): print both class and constructor docstrings.
3982 (Magic.magic_pdef): give constructor info if passed a class and
3993 (Magic.magic_pdef): give constructor info if passed a class and
3983 __call__ info for callable object instances.
3994 __call__ info for callable object instances.
3984
3995
3985 2002-01-04 Fernando Perez <fperez@colorado.edu>
3996 2002-01-04 Fernando Perez <fperez@colorado.edu>
3986
3997
3987 * Made deep_reload() off by default. It doesn't always work
3998 * Made deep_reload() off by default. It doesn't always work
3988 exactly as intended, so it's probably safer to have it off. It's
3999 exactly as intended, so it's probably safer to have it off. It's
3989 still available as dreload() anyway, so nothing is lost.
4000 still available as dreload() anyway, so nothing is lost.
3990
4001
3991 2002-01-02 Fernando Perez <fperez@colorado.edu>
4002 2002-01-02 Fernando Perez <fperez@colorado.edu>
3992
4003
3993 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4004 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3994 so I wanted an updated release).
4005 so I wanted an updated release).
3995
4006
3996 2001-12-27 Fernando Perez <fperez@colorado.edu>
4007 2001-12-27 Fernando Perez <fperez@colorado.edu>
3997
4008
3998 * IPython/iplib.py (InteractiveShell.interact): Added the original
4009 * IPython/iplib.py (InteractiveShell.interact): Added the original
3999 code from 'code.py' for this module in order to change the
4010 code from 'code.py' for this module in order to change the
4000 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4011 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4001 the history cache would break when the user hit Ctrl-C, and
4012 the history cache would break when the user hit Ctrl-C, and
4002 interact() offers no way to add any hooks to it.
4013 interact() offers no way to add any hooks to it.
4003
4014
4004 2001-12-23 Fernando Perez <fperez@colorado.edu>
4015 2001-12-23 Fernando Perez <fperez@colorado.edu>
4005
4016
4006 * setup.py: added check for 'MANIFEST' before trying to remove
4017 * setup.py: added check for 'MANIFEST' before trying to remove
4007 it. Thanks to Sean Reifschneider.
4018 it. Thanks to Sean Reifschneider.
4008
4019
4009 2001-12-22 Fernando Perez <fperez@colorado.edu>
4020 2001-12-22 Fernando Perez <fperez@colorado.edu>
4010
4021
4011 * Released 0.2.2.
4022 * Released 0.2.2.
4012
4023
4013 * Finished (reasonably) writing the manual. Later will add the
4024 * Finished (reasonably) writing the manual. Later will add the
4014 python-standard navigation stylesheets, but for the time being
4025 python-standard navigation stylesheets, but for the time being
4015 it's fairly complete. Distribution will include html and pdf
4026 it's fairly complete. Distribution will include html and pdf
4016 versions.
4027 versions.
4017
4028
4018 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4029 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4019 (MayaVi author).
4030 (MayaVi author).
4020
4031
4021 2001-12-21 Fernando Perez <fperez@colorado.edu>
4032 2001-12-21 Fernando Perez <fperez@colorado.edu>
4022
4033
4023 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4034 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4024 good public release, I think (with the manual and the distutils
4035 good public release, I think (with the manual and the distutils
4025 installer). The manual can use some work, but that can go
4036 installer). The manual can use some work, but that can go
4026 slowly. Otherwise I think it's quite nice for end users. Next
4037 slowly. Otherwise I think it's quite nice for end users. Next
4027 summer, rewrite the guts of it...
4038 summer, rewrite the guts of it...
4028
4039
4029 * Changed format of ipythonrc files to use whitespace as the
4040 * Changed format of ipythonrc files to use whitespace as the
4030 separator instead of an explicit '='. Cleaner.
4041 separator instead of an explicit '='. Cleaner.
4031
4042
4032 2001-12-20 Fernando Perez <fperez@colorado.edu>
4043 2001-12-20 Fernando Perez <fperez@colorado.edu>
4033
4044
4034 * Started a manual in LyX. For now it's just a quick merge of the
4045 * Started a manual in LyX. For now it's just a quick merge of the
4035 various internal docstrings and READMEs. Later it may grow into a
4046 various internal docstrings and READMEs. Later it may grow into a
4036 nice, full-blown manual.
4047 nice, full-blown manual.
4037
4048
4038 * Set up a distutils based installer. Installation should now be
4049 * Set up a distutils based installer. Installation should now be
4039 trivially simple for end-users.
4050 trivially simple for end-users.
4040
4051
4041 2001-12-11 Fernando Perez <fperez@colorado.edu>
4052 2001-12-11 Fernando Perez <fperez@colorado.edu>
4042
4053
4043 * Released 0.2.0. First public release, announced it at
4054 * Released 0.2.0. First public release, announced it at
4044 comp.lang.python. From now on, just bugfixes...
4055 comp.lang.python. From now on, just bugfixes...
4045
4056
4046 * Went through all the files, set copyright/license notices and
4057 * Went through all the files, set copyright/license notices and
4047 cleaned up things. Ready for release.
4058 cleaned up things. Ready for release.
4048
4059
4049 2001-12-10 Fernando Perez <fperez@colorado.edu>
4060 2001-12-10 Fernando Perez <fperez@colorado.edu>
4050
4061
4051 * Changed the first-time installer not to use tarfiles. It's more
4062 * Changed the first-time installer not to use tarfiles. It's more
4052 robust now and less unix-dependent. Also makes it easier for
4063 robust now and less unix-dependent. Also makes it easier for
4053 people to later upgrade versions.
4064 people to later upgrade versions.
4054
4065
4055 * Changed @exit to @abort to reflect the fact that it's pretty
4066 * Changed @exit to @abort to reflect the fact that it's pretty
4056 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4067 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4057 becomes significant only when IPyhton is embedded: in that case,
4068 becomes significant only when IPyhton is embedded: in that case,
4058 C-D closes IPython only, but @abort kills the enclosing program
4069 C-D closes IPython only, but @abort kills the enclosing program
4059 too (unless it had called IPython inside a try catching
4070 too (unless it had called IPython inside a try catching
4060 SystemExit).
4071 SystemExit).
4061
4072
4062 * Created Shell module which exposes the actuall IPython Shell
4073 * Created Shell module which exposes the actuall IPython Shell
4063 classes, currently the normal and the embeddable one. This at
4074 classes, currently the normal and the embeddable one. This at
4064 least offers a stable interface we won't need to change when
4075 least offers a stable interface we won't need to change when
4065 (later) the internals are rewritten. That rewrite will be confined
4076 (later) the internals are rewritten. That rewrite will be confined
4066 to iplib and ipmaker, but the Shell interface should remain as is.
4077 to iplib and ipmaker, but the Shell interface should remain as is.
4067
4078
4068 * Added embed module which offers an embeddable IPShell object,
4079 * Added embed module which offers an embeddable IPShell object,
4069 useful to fire up IPython *inside* a running program. Great for
4080 useful to fire up IPython *inside* a running program. Great for
4070 debugging or dynamical data analysis.
4081 debugging or dynamical data analysis.
4071
4082
4072 2001-12-08 Fernando Perez <fperez@colorado.edu>
4083 2001-12-08 Fernando Perez <fperez@colorado.edu>
4073
4084
4074 * Fixed small bug preventing seeing info from methods of defined
4085 * Fixed small bug preventing seeing info from methods of defined
4075 objects (incorrect namespace in _ofind()).
4086 objects (incorrect namespace in _ofind()).
4076
4087
4077 * Documentation cleanup. Moved the main usage docstrings to a
4088 * Documentation cleanup. Moved the main usage docstrings to a
4078 separate file, usage.py (cleaner to maintain, and hopefully in the
4089 separate file, usage.py (cleaner to maintain, and hopefully in the
4079 future some perlpod-like way of producing interactive, man and
4090 future some perlpod-like way of producing interactive, man and
4080 html docs out of it will be found).
4091 html docs out of it will be found).
4081
4092
4082 * Added @profile to see your profile at any time.
4093 * Added @profile to see your profile at any time.
4083
4094
4084 * Added @p as an alias for 'print'. It's especially convenient if
4095 * Added @p as an alias for 'print'. It's especially convenient if
4085 using automagic ('p x' prints x).
4096 using automagic ('p x' prints x).
4086
4097
4087 * Small cleanups and fixes after a pychecker run.
4098 * Small cleanups and fixes after a pychecker run.
4088
4099
4089 * Changed the @cd command to handle @cd - and @cd -<n> for
4100 * Changed the @cd command to handle @cd - and @cd -<n> for
4090 visiting any directory in _dh.
4101 visiting any directory in _dh.
4091
4102
4092 * Introduced _dh, a history of visited directories. @dhist prints
4103 * Introduced _dh, a history of visited directories. @dhist prints
4093 it out with numbers.
4104 it out with numbers.
4094
4105
4095 2001-12-07 Fernando Perez <fperez@colorado.edu>
4106 2001-12-07 Fernando Perez <fperez@colorado.edu>
4096
4107
4097 * Released 0.1.22
4108 * Released 0.1.22
4098
4109
4099 * Made initialization a bit more robust against invalid color
4110 * Made initialization a bit more robust against invalid color
4100 options in user input (exit, not traceback-crash).
4111 options in user input (exit, not traceback-crash).
4101
4112
4102 * Changed the bug crash reporter to write the report only in the
4113 * Changed the bug crash reporter to write the report only in the
4103 user's .ipython directory. That way IPython won't litter people's
4114 user's .ipython directory. That way IPython won't litter people's
4104 hard disks with crash files all over the place. Also print on
4115 hard disks with crash files all over the place. Also print on
4105 screen the necessary mail command.
4116 screen the necessary mail command.
4106
4117
4107 * With the new ultraTB, implemented LightBG color scheme for light
4118 * With the new ultraTB, implemented LightBG color scheme for light
4108 background terminals. A lot of people like white backgrounds, so I
4119 background terminals. A lot of people like white backgrounds, so I
4109 guess we should at least give them something readable.
4120 guess we should at least give them something readable.
4110
4121
4111 2001-12-06 Fernando Perez <fperez@colorado.edu>
4122 2001-12-06 Fernando Perez <fperez@colorado.edu>
4112
4123
4113 * Modified the structure of ultraTB. Now there's a proper class
4124 * Modified the structure of ultraTB. Now there's a proper class
4114 for tables of color schemes which allow adding schemes easily and
4125 for tables of color schemes which allow adding schemes easily and
4115 switching the active scheme without creating a new instance every
4126 switching the active scheme without creating a new instance every
4116 time (which was ridiculous). The syntax for creating new schemes
4127 time (which was ridiculous). The syntax for creating new schemes
4117 is also cleaner. I think ultraTB is finally done, with a clean
4128 is also cleaner. I think ultraTB is finally done, with a clean
4118 class structure. Names are also much cleaner (now there's proper
4129 class structure. Names are also much cleaner (now there's proper
4119 color tables, no need for every variable to also have 'color' in
4130 color tables, no need for every variable to also have 'color' in
4120 its name).
4131 its name).
4121
4132
4122 * Broke down genutils into separate files. Now genutils only
4133 * Broke down genutils into separate files. Now genutils only
4123 contains utility functions, and classes have been moved to their
4134 contains utility functions, and classes have been moved to their
4124 own files (they had enough independent functionality to warrant
4135 own files (they had enough independent functionality to warrant
4125 it): ConfigLoader, OutputTrap, Struct.
4136 it): ConfigLoader, OutputTrap, Struct.
4126
4137
4127 2001-12-05 Fernando Perez <fperez@colorado.edu>
4138 2001-12-05 Fernando Perez <fperez@colorado.edu>
4128
4139
4129 * IPython turns 21! Released version 0.1.21, as a candidate for
4140 * IPython turns 21! Released version 0.1.21, as a candidate for
4130 public consumption. If all goes well, release in a few days.
4141 public consumption. If all goes well, release in a few days.
4131
4142
4132 * Fixed path bug (files in Extensions/ directory wouldn't be found
4143 * Fixed path bug (files in Extensions/ directory wouldn't be found
4133 unless IPython/ was explicitly in sys.path).
4144 unless IPython/ was explicitly in sys.path).
4134
4145
4135 * Extended the FlexCompleter class as MagicCompleter to allow
4146 * Extended the FlexCompleter class as MagicCompleter to allow
4136 completion of @-starting lines.
4147 completion of @-starting lines.
4137
4148
4138 * Created __release__.py file as a central repository for release
4149 * Created __release__.py file as a central repository for release
4139 info that other files can read from.
4150 info that other files can read from.
4140
4151
4141 * Fixed small bug in logging: when logging was turned on in
4152 * Fixed small bug in logging: when logging was turned on in
4142 mid-session, old lines with special meanings (!@?) were being
4153 mid-session, old lines with special meanings (!@?) were being
4143 logged without the prepended comment, which is necessary since
4154 logged without the prepended comment, which is necessary since
4144 they are not truly valid python syntax. This should make session
4155 they are not truly valid python syntax. This should make session
4145 restores produce less errors.
4156 restores produce less errors.
4146
4157
4147 * The namespace cleanup forced me to make a FlexCompleter class
4158 * The namespace cleanup forced me to make a FlexCompleter class
4148 which is nothing but a ripoff of rlcompleter, but with selectable
4159 which is nothing but a ripoff of rlcompleter, but with selectable
4149 namespace (rlcompleter only works in __main__.__dict__). I'll try
4160 namespace (rlcompleter only works in __main__.__dict__). I'll try
4150 to submit a note to the authors to see if this change can be
4161 to submit a note to the authors to see if this change can be
4151 incorporated in future rlcompleter releases (Dec.6: done)
4162 incorporated in future rlcompleter releases (Dec.6: done)
4152
4163
4153 * More fixes to namespace handling. It was a mess! Now all
4164 * More fixes to namespace handling. It was a mess! Now all
4154 explicit references to __main__.__dict__ are gone (except when
4165 explicit references to __main__.__dict__ are gone (except when
4155 really needed) and everything is handled through the namespace
4166 really needed) and everything is handled through the namespace
4156 dicts in the IPython instance. We seem to be getting somewhere
4167 dicts in the IPython instance. We seem to be getting somewhere
4157 with this, finally...
4168 with this, finally...
4158
4169
4159 * Small documentation updates.
4170 * Small documentation updates.
4160
4171
4161 * Created the Extensions directory under IPython (with an
4172 * Created the Extensions directory under IPython (with an
4162 __init__.py). Put the PhysicalQ stuff there. This directory should
4173 __init__.py). Put the PhysicalQ stuff there. This directory should
4163 be used for all special-purpose extensions.
4174 be used for all special-purpose extensions.
4164
4175
4165 * File renaming:
4176 * File renaming:
4166 ipythonlib --> ipmaker
4177 ipythonlib --> ipmaker
4167 ipplib --> iplib
4178 ipplib --> iplib
4168 This makes a bit more sense in terms of what these files actually do.
4179 This makes a bit more sense in terms of what these files actually do.
4169
4180
4170 * Moved all the classes and functions in ipythonlib to ipplib, so
4181 * Moved all the classes and functions in ipythonlib to ipplib, so
4171 now ipythonlib only has make_IPython(). This will ease up its
4182 now ipythonlib only has make_IPython(). This will ease up its
4172 splitting in smaller functional chunks later.
4183 splitting in smaller functional chunks later.
4173
4184
4174 * Cleaned up (done, I think) output of @whos. Better column
4185 * Cleaned up (done, I think) output of @whos. Better column
4175 formatting, and now shows str(var) for as much as it can, which is
4186 formatting, and now shows str(var) for as much as it can, which is
4176 typically what one gets with a 'print var'.
4187 typically what one gets with a 'print var'.
4177
4188
4178 2001-12-04 Fernando Perez <fperez@colorado.edu>
4189 2001-12-04 Fernando Perez <fperez@colorado.edu>
4179
4190
4180 * Fixed namespace problems. Now builtin/IPyhton/user names get
4191 * Fixed namespace problems. Now builtin/IPyhton/user names get
4181 properly reported in their namespace. Internal namespace handling
4192 properly reported in their namespace. Internal namespace handling
4182 is finally getting decent (not perfect yet, but much better than
4193 is finally getting decent (not perfect yet, but much better than
4183 the ad-hoc mess we had).
4194 the ad-hoc mess we had).
4184
4195
4185 * Removed -exit option. If people just want to run a python
4196 * Removed -exit option. If people just want to run a python
4186 script, that's what the normal interpreter is for. Less
4197 script, that's what the normal interpreter is for. Less
4187 unnecessary options, less chances for bugs.
4198 unnecessary options, less chances for bugs.
4188
4199
4189 * Added a crash handler which generates a complete post-mortem if
4200 * Added a crash handler which generates a complete post-mortem if
4190 IPython crashes. This will help a lot in tracking bugs down the
4201 IPython crashes. This will help a lot in tracking bugs down the
4191 road.
4202 road.
4192
4203
4193 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4204 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4194 which were boud to functions being reassigned would bypass the
4205 which were boud to functions being reassigned would bypass the
4195 logger, breaking the sync of _il with the prompt counter. This
4206 logger, breaking the sync of _il with the prompt counter. This
4196 would then crash IPython later when a new line was logged.
4207 would then crash IPython later when a new line was logged.
4197
4208
4198 2001-12-02 Fernando Perez <fperez@colorado.edu>
4209 2001-12-02 Fernando Perez <fperez@colorado.edu>
4199
4210
4200 * Made IPython a package. This means people don't have to clutter
4211 * Made IPython a package. This means people don't have to clutter
4201 their sys.path with yet another directory. Changed the INSTALL
4212 their sys.path with yet another directory. Changed the INSTALL
4202 file accordingly.
4213 file accordingly.
4203
4214
4204 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4215 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4205 sorts its output (so @who shows it sorted) and @whos formats the
4216 sorts its output (so @who shows it sorted) and @whos formats the
4206 table according to the width of the first column. Nicer, easier to
4217 table according to the width of the first column. Nicer, easier to
4207 read. Todo: write a generic table_format() which takes a list of
4218 read. Todo: write a generic table_format() which takes a list of
4208 lists and prints it nicely formatted, with optional row/column
4219 lists and prints it nicely formatted, with optional row/column
4209 separators and proper padding and justification.
4220 separators and proper padding and justification.
4210
4221
4211 * Released 0.1.20
4222 * Released 0.1.20
4212
4223
4213 * Fixed bug in @log which would reverse the inputcache list (a
4224 * Fixed bug in @log which would reverse the inputcache list (a
4214 copy operation was missing).
4225 copy operation was missing).
4215
4226
4216 * Code cleanup. @config was changed to use page(). Better, since
4227 * Code cleanup. @config was changed to use page(). Better, since
4217 its output is always quite long.
4228 its output is always quite long.
4218
4229
4219 * Itpl is back as a dependency. I was having too many problems
4230 * Itpl is back as a dependency. I was having too many problems
4220 getting the parametric aliases to work reliably, and it's just
4231 getting the parametric aliases to work reliably, and it's just
4221 easier to code weird string operations with it than playing %()s
4232 easier to code weird string operations with it than playing %()s
4222 games. It's only ~6k, so I don't think it's too big a deal.
4233 games. It's only ~6k, so I don't think it's too big a deal.
4223
4234
4224 * Found (and fixed) a very nasty bug with history. !lines weren't
4235 * Found (and fixed) a very nasty bug with history. !lines weren't
4225 getting cached, and the out of sync caches would crash
4236 getting cached, and the out of sync caches would crash
4226 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4237 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4227 division of labor a bit better. Bug fixed, cleaner structure.
4238 division of labor a bit better. Bug fixed, cleaner structure.
4228
4239
4229 2001-12-01 Fernando Perez <fperez@colorado.edu>
4240 2001-12-01 Fernando Perez <fperez@colorado.edu>
4230
4241
4231 * Released 0.1.19
4242 * Released 0.1.19
4232
4243
4233 * Added option -n to @hist to prevent line number printing. Much
4244 * Added option -n to @hist to prevent line number printing. Much
4234 easier to copy/paste code this way.
4245 easier to copy/paste code this way.
4235
4246
4236 * Created global _il to hold the input list. Allows easy
4247 * Created global _il to hold the input list. Allows easy
4237 re-execution of blocks of code by slicing it (inspired by Janko's
4248 re-execution of blocks of code by slicing it (inspired by Janko's
4238 comment on 'macros').
4249 comment on 'macros').
4239
4250
4240 * Small fixes and doc updates.
4251 * Small fixes and doc updates.
4241
4252
4242 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4253 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4243 much too fragile with automagic. Handles properly multi-line
4254 much too fragile with automagic. Handles properly multi-line
4244 statements and takes parameters.
4255 statements and takes parameters.
4245
4256
4246 2001-11-30 Fernando Perez <fperez@colorado.edu>
4257 2001-11-30 Fernando Perez <fperez@colorado.edu>
4247
4258
4248 * Version 0.1.18 released.
4259 * Version 0.1.18 released.
4249
4260
4250 * Fixed nasty namespace bug in initial module imports.
4261 * Fixed nasty namespace bug in initial module imports.
4251
4262
4252 * Added copyright/license notes to all code files (except
4263 * Added copyright/license notes to all code files (except
4253 DPyGetOpt). For the time being, LGPL. That could change.
4264 DPyGetOpt). For the time being, LGPL. That could change.
4254
4265
4255 * Rewrote a much nicer README, updated INSTALL, cleaned up
4266 * Rewrote a much nicer README, updated INSTALL, cleaned up
4256 ipythonrc-* samples.
4267 ipythonrc-* samples.
4257
4268
4258 * Overall code/documentation cleanup. Basically ready for
4269 * Overall code/documentation cleanup. Basically ready for
4259 release. Only remaining thing: licence decision (LGPL?).
4270 release. Only remaining thing: licence decision (LGPL?).
4260
4271
4261 * Converted load_config to a class, ConfigLoader. Now recursion
4272 * Converted load_config to a class, ConfigLoader. Now recursion
4262 control is better organized. Doesn't include the same file twice.
4273 control is better organized. Doesn't include the same file twice.
4263
4274
4264 2001-11-29 Fernando Perez <fperez@colorado.edu>
4275 2001-11-29 Fernando Perez <fperez@colorado.edu>
4265
4276
4266 * Got input history working. Changed output history variables from
4277 * Got input history working. Changed output history variables from
4267 _p to _o so that _i is for input and _o for output. Just cleaner
4278 _p to _o so that _i is for input and _o for output. Just cleaner
4268 convention.
4279 convention.
4269
4280
4270 * Implemented parametric aliases. This pretty much allows the
4281 * Implemented parametric aliases. This pretty much allows the
4271 alias system to offer full-blown shell convenience, I think.
4282 alias system to offer full-blown shell convenience, I think.
4272
4283
4273 * Version 0.1.17 released, 0.1.18 opened.
4284 * Version 0.1.17 released, 0.1.18 opened.
4274
4285
4275 * dot_ipython/ipythonrc (alias): added documentation.
4286 * dot_ipython/ipythonrc (alias): added documentation.
4276 (xcolor): Fixed small bug (xcolors -> xcolor)
4287 (xcolor): Fixed small bug (xcolors -> xcolor)
4277
4288
4278 * Changed the alias system. Now alias is a magic command to define
4289 * Changed the alias system. Now alias is a magic command to define
4279 aliases just like the shell. Rationale: the builtin magics should
4290 aliases just like the shell. Rationale: the builtin magics should
4280 be there for things deeply connected to IPython's
4291 be there for things deeply connected to IPython's
4281 architecture. And this is a much lighter system for what I think
4292 architecture. And this is a much lighter system for what I think
4282 is the really important feature: allowing users to define quickly
4293 is the really important feature: allowing users to define quickly
4283 magics that will do shell things for them, so they can customize
4294 magics that will do shell things for them, so they can customize
4284 IPython easily to match their work habits. If someone is really
4295 IPython easily to match their work habits. If someone is really
4285 desperate to have another name for a builtin alias, they can
4296 desperate to have another name for a builtin alias, they can
4286 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4297 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4287 works.
4298 works.
4288
4299
4289 2001-11-28 Fernando Perez <fperez@colorado.edu>
4300 2001-11-28 Fernando Perez <fperez@colorado.edu>
4290
4301
4291 * Changed @file so that it opens the source file at the proper
4302 * Changed @file so that it opens the source file at the proper
4292 line. Since it uses less, if your EDITOR environment is
4303 line. Since it uses less, if your EDITOR environment is
4293 configured, typing v will immediately open your editor of choice
4304 configured, typing v will immediately open your editor of choice
4294 right at the line where the object is defined. Not as quick as
4305 right at the line where the object is defined. Not as quick as
4295 having a direct @edit command, but for all intents and purposes it
4306 having a direct @edit command, but for all intents and purposes it
4296 works. And I don't have to worry about writing @edit to deal with
4307 works. And I don't have to worry about writing @edit to deal with
4297 all the editors, less does that.
4308 all the editors, less does that.
4298
4309
4299 * Version 0.1.16 released, 0.1.17 opened.
4310 * Version 0.1.16 released, 0.1.17 opened.
4300
4311
4301 * Fixed some nasty bugs in the page/page_dumb combo that could
4312 * Fixed some nasty bugs in the page/page_dumb combo that could
4302 crash IPython.
4313 crash IPython.
4303
4314
4304 2001-11-27 Fernando Perez <fperez@colorado.edu>
4315 2001-11-27 Fernando Perez <fperez@colorado.edu>
4305
4316
4306 * Version 0.1.15 released, 0.1.16 opened.
4317 * Version 0.1.15 released, 0.1.16 opened.
4307
4318
4308 * Finally got ? and ?? to work for undefined things: now it's
4319 * Finally got ? and ?? to work for undefined things: now it's
4309 possible to type {}.get? and get information about the get method
4320 possible to type {}.get? and get information about the get method
4310 of dicts, or os.path? even if only os is defined (so technically
4321 of dicts, or os.path? even if only os is defined (so technically
4311 os.path isn't). Works at any level. For example, after import os,
4322 os.path isn't). Works at any level. For example, after import os,
4312 os?, os.path?, os.path.abspath? all work. This is great, took some
4323 os?, os.path?, os.path.abspath? all work. This is great, took some
4313 work in _ofind.
4324 work in _ofind.
4314
4325
4315 * Fixed more bugs with logging. The sanest way to do it was to add
4326 * Fixed more bugs with logging. The sanest way to do it was to add
4316 to @log a 'mode' parameter. Killed two in one shot (this mode
4327 to @log a 'mode' parameter. Killed two in one shot (this mode
4317 option was a request of Janko's). I think it's finally clean
4328 option was a request of Janko's). I think it's finally clean
4318 (famous last words).
4329 (famous last words).
4319
4330
4320 * Added a page_dumb() pager which does a decent job of paging on
4331 * Added a page_dumb() pager which does a decent job of paging on
4321 screen, if better things (like less) aren't available. One less
4332 screen, if better things (like less) aren't available. One less
4322 unix dependency (someday maybe somebody will port this to
4333 unix dependency (someday maybe somebody will port this to
4323 windows).
4334 windows).
4324
4335
4325 * Fixed problem in magic_log: would lock of logging out if log
4336 * Fixed problem in magic_log: would lock of logging out if log
4326 creation failed (because it would still think it had succeeded).
4337 creation failed (because it would still think it had succeeded).
4327
4338
4328 * Improved the page() function using curses to auto-detect screen
4339 * Improved the page() function using curses to auto-detect screen
4329 size. Now it can make a much better decision on whether to print
4340 size. Now it can make a much better decision on whether to print
4330 or page a string. Option screen_length was modified: a value 0
4341 or page a string. Option screen_length was modified: a value 0
4331 means auto-detect, and that's the default now.
4342 means auto-detect, and that's the default now.
4332
4343
4333 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4344 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4334 go out. I'll test it for a few days, then talk to Janko about
4345 go out. I'll test it for a few days, then talk to Janko about
4335 licences and announce it.
4346 licences and announce it.
4336
4347
4337 * Fixed the length of the auto-generated ---> prompt which appears
4348 * Fixed the length of the auto-generated ---> prompt which appears
4338 for auto-parens and auto-quotes. Getting this right isn't trivial,
4349 for auto-parens and auto-quotes. Getting this right isn't trivial,
4339 with all the color escapes, different prompt types and optional
4350 with all the color escapes, different prompt types and optional
4340 separators. But it seems to be working in all the combinations.
4351 separators. But it seems to be working in all the combinations.
4341
4352
4342 2001-11-26 Fernando Perez <fperez@colorado.edu>
4353 2001-11-26 Fernando Perez <fperez@colorado.edu>
4343
4354
4344 * Wrote a regexp filter to get option types from the option names
4355 * Wrote a regexp filter to get option types from the option names
4345 string. This eliminates the need to manually keep two duplicate
4356 string. This eliminates the need to manually keep two duplicate
4346 lists.
4357 lists.
4347
4358
4348 * Removed the unneeded check_option_names. Now options are handled
4359 * Removed the unneeded check_option_names. Now options are handled
4349 in a much saner manner and it's easy to visually check that things
4360 in a much saner manner and it's easy to visually check that things
4350 are ok.
4361 are ok.
4351
4362
4352 * Updated version numbers on all files I modified to carry a
4363 * Updated version numbers on all files I modified to carry a
4353 notice so Janko and Nathan have clear version markers.
4364 notice so Janko and Nathan have clear version markers.
4354
4365
4355 * Updated docstring for ultraTB with my changes. I should send
4366 * Updated docstring for ultraTB with my changes. I should send
4356 this to Nathan.
4367 this to Nathan.
4357
4368
4358 * Lots of small fixes. Ran everything through pychecker again.
4369 * Lots of small fixes. Ran everything through pychecker again.
4359
4370
4360 * Made loading of deep_reload an cmd line option. If it's not too
4371 * Made loading of deep_reload an cmd line option. If it's not too
4361 kosher, now people can just disable it. With -nodeep_reload it's
4372 kosher, now people can just disable it. With -nodeep_reload it's
4362 still available as dreload(), it just won't overwrite reload().
4373 still available as dreload(), it just won't overwrite reload().
4363
4374
4364 * Moved many options to the no| form (-opt and -noopt
4375 * Moved many options to the no| form (-opt and -noopt
4365 accepted). Cleaner.
4376 accepted). Cleaner.
4366
4377
4367 * Changed magic_log so that if called with no parameters, it uses
4378 * Changed magic_log so that if called with no parameters, it uses
4368 'rotate' mode. That way auto-generated logs aren't automatically
4379 'rotate' mode. That way auto-generated logs aren't automatically
4369 over-written. For normal logs, now a backup is made if it exists
4380 over-written. For normal logs, now a backup is made if it exists
4370 (only 1 level of backups). A new 'backup' mode was added to the
4381 (only 1 level of backups). A new 'backup' mode was added to the
4371 Logger class to support this. This was a request by Janko.
4382 Logger class to support this. This was a request by Janko.
4372
4383
4373 * Added @logoff/@logon to stop/restart an active log.
4384 * Added @logoff/@logon to stop/restart an active log.
4374
4385
4375 * Fixed a lot of bugs in log saving/replay. It was pretty
4386 * Fixed a lot of bugs in log saving/replay. It was pretty
4376 broken. Now special lines (!@,/) appear properly in the command
4387 broken. Now special lines (!@,/) appear properly in the command
4377 history after a log replay.
4388 history after a log replay.
4378
4389
4379 * Tried and failed to implement full session saving via pickle. My
4390 * Tried and failed to implement full session saving via pickle. My
4380 idea was to pickle __main__.__dict__, but modules can't be
4391 idea was to pickle __main__.__dict__, but modules can't be
4381 pickled. This would be a better alternative to replaying logs, but
4392 pickled. This would be a better alternative to replaying logs, but
4382 seems quite tricky to get to work. Changed -session to be called
4393 seems quite tricky to get to work. Changed -session to be called
4383 -logplay, which more accurately reflects what it does. And if we
4394 -logplay, which more accurately reflects what it does. And if we
4384 ever get real session saving working, -session is now available.
4395 ever get real session saving working, -session is now available.
4385
4396
4386 * Implemented color schemes for prompts also. As for tracebacks,
4397 * Implemented color schemes for prompts also. As for tracebacks,
4387 currently only NoColor and Linux are supported. But now the
4398 currently only NoColor and Linux are supported. But now the
4388 infrastructure is in place, based on a generic ColorScheme
4399 infrastructure is in place, based on a generic ColorScheme
4389 class. So writing and activating new schemes both for the prompts
4400 class. So writing and activating new schemes both for the prompts
4390 and the tracebacks should be straightforward.
4401 and the tracebacks should be straightforward.
4391
4402
4392 * Version 0.1.13 released, 0.1.14 opened.
4403 * Version 0.1.13 released, 0.1.14 opened.
4393
4404
4394 * Changed handling of options for output cache. Now counter is
4405 * Changed handling of options for output cache. Now counter is
4395 hardwired starting at 1 and one specifies the maximum number of
4406 hardwired starting at 1 and one specifies the maximum number of
4396 entries *in the outcache* (not the max prompt counter). This is
4407 entries *in the outcache* (not the max prompt counter). This is
4397 much better, since many statements won't increase the cache
4408 much better, since many statements won't increase the cache
4398 count. It also eliminated some confusing options, now there's only
4409 count. It also eliminated some confusing options, now there's only
4399 one: cache_size.
4410 one: cache_size.
4400
4411
4401 * Added 'alias' magic function and magic_alias option in the
4412 * Added 'alias' magic function and magic_alias option in the
4402 ipythonrc file. Now the user can easily define whatever names he
4413 ipythonrc file. Now the user can easily define whatever names he
4403 wants for the magic functions without having to play weird
4414 wants for the magic functions without having to play weird
4404 namespace games. This gives IPython a real shell-like feel.
4415 namespace games. This gives IPython a real shell-like feel.
4405
4416
4406 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4417 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4407 @ or not).
4418 @ or not).
4408
4419
4409 This was one of the last remaining 'visible' bugs (that I know
4420 This was one of the last remaining 'visible' bugs (that I know
4410 of). I think if I can clean up the session loading so it works
4421 of). I think if I can clean up the session loading so it works
4411 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4422 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4412 about licensing).
4423 about licensing).
4413
4424
4414 2001-11-25 Fernando Perez <fperez@colorado.edu>
4425 2001-11-25 Fernando Perez <fperez@colorado.edu>
4415
4426
4416 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4427 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4417 there's a cleaner distinction between what ? and ?? show.
4428 there's a cleaner distinction between what ? and ?? show.
4418
4429
4419 * Added screen_length option. Now the user can define his own
4430 * Added screen_length option. Now the user can define his own
4420 screen size for page() operations.
4431 screen size for page() operations.
4421
4432
4422 * Implemented magic shell-like functions with automatic code
4433 * Implemented magic shell-like functions with automatic code
4423 generation. Now adding another function is just a matter of adding
4434 generation. Now adding another function is just a matter of adding
4424 an entry to a dict, and the function is dynamically generated at
4435 an entry to a dict, and the function is dynamically generated at
4425 run-time. Python has some really cool features!
4436 run-time. Python has some really cool features!
4426
4437
4427 * Renamed many options to cleanup conventions a little. Now all
4438 * Renamed many options to cleanup conventions a little. Now all
4428 are lowercase, and only underscores where needed. Also in the code
4439 are lowercase, and only underscores where needed. Also in the code
4429 option name tables are clearer.
4440 option name tables are clearer.
4430
4441
4431 * Changed prompts a little. Now input is 'In [n]:' instead of
4442 * Changed prompts a little. Now input is 'In [n]:' instead of
4432 'In[n]:='. This allows it the numbers to be aligned with the
4443 'In[n]:='. This allows it the numbers to be aligned with the
4433 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4444 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4434 Python (it was a Mathematica thing). The '...' continuation prompt
4445 Python (it was a Mathematica thing). The '...' continuation prompt
4435 was also changed a little to align better.
4446 was also changed a little to align better.
4436
4447
4437 * Fixed bug when flushing output cache. Not all _p<n> variables
4448 * Fixed bug when flushing output cache. Not all _p<n> variables
4438 exist, so their deletion needs to be wrapped in a try:
4449 exist, so their deletion needs to be wrapped in a try:
4439
4450
4440 * Figured out how to properly use inspect.formatargspec() (it
4451 * Figured out how to properly use inspect.formatargspec() (it
4441 requires the args preceded by *). So I removed all the code from
4452 requires the args preceded by *). So I removed all the code from
4442 _get_pdef in Magic, which was just replicating that.
4453 _get_pdef in Magic, which was just replicating that.
4443
4454
4444 * Added test to prefilter to allow redefining magic function names
4455 * Added test to prefilter to allow redefining magic function names
4445 as variables. This is ok, since the @ form is always available,
4456 as variables. This is ok, since the @ form is always available,
4446 but whe should allow the user to define a variable called 'ls' if
4457 but whe should allow the user to define a variable called 'ls' if
4447 he needs it.
4458 he needs it.
4448
4459
4449 * Moved the ToDo information from README into a separate ToDo.
4460 * Moved the ToDo information from README into a separate ToDo.
4450
4461
4451 * General code cleanup and small bugfixes. I think it's close to a
4462 * General code cleanup and small bugfixes. I think it's close to a
4452 state where it can be released, obviously with a big 'beta'
4463 state where it can be released, obviously with a big 'beta'
4453 warning on it.
4464 warning on it.
4454
4465
4455 * Got the magic function split to work. Now all magics are defined
4466 * Got the magic function split to work. Now all magics are defined
4456 in a separate class. It just organizes things a bit, and now
4467 in a separate class. It just organizes things a bit, and now
4457 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4468 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4458 was too long).
4469 was too long).
4459
4470
4460 * Changed @clear to @reset to avoid potential confusions with
4471 * Changed @clear to @reset to avoid potential confusions with
4461 the shell command clear. Also renamed @cl to @clear, which does
4472 the shell command clear. Also renamed @cl to @clear, which does
4462 exactly what people expect it to from their shell experience.
4473 exactly what people expect it to from their shell experience.
4463
4474
4464 Added a check to the @reset command (since it's so
4475 Added a check to the @reset command (since it's so
4465 destructive, it's probably a good idea to ask for confirmation).
4476 destructive, it's probably a good idea to ask for confirmation).
4466 But now reset only works for full namespace resetting. Since the
4477 But now reset only works for full namespace resetting. Since the
4467 del keyword is already there for deleting a few specific
4478 del keyword is already there for deleting a few specific
4468 variables, I don't see the point of having a redundant magic
4479 variables, I don't see the point of having a redundant magic
4469 function for the same task.
4480 function for the same task.
4470
4481
4471 2001-11-24 Fernando Perez <fperez@colorado.edu>
4482 2001-11-24 Fernando Perez <fperez@colorado.edu>
4472
4483
4473 * Updated the builtin docs (esp. the ? ones).
4484 * Updated the builtin docs (esp. the ? ones).
4474
4485
4475 * Ran all the code through pychecker. Not terribly impressed with
4486 * Ran all the code through pychecker. Not terribly impressed with
4476 it: lots of spurious warnings and didn't really find anything of
4487 it: lots of spurious warnings and didn't really find anything of
4477 substance (just a few modules being imported and not used).
4488 substance (just a few modules being imported and not used).
4478
4489
4479 * Implemented the new ultraTB functionality into IPython. New
4490 * Implemented the new ultraTB functionality into IPython. New
4480 option: xcolors. This chooses color scheme. xmode now only selects
4491 option: xcolors. This chooses color scheme. xmode now only selects
4481 between Plain and Verbose. Better orthogonality.
4492 between Plain and Verbose. Better orthogonality.
4482
4493
4483 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4494 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4484 mode and color scheme for the exception handlers. Now it's
4495 mode and color scheme for the exception handlers. Now it's
4485 possible to have the verbose traceback with no coloring.
4496 possible to have the verbose traceback with no coloring.
4486
4497
4487 2001-11-23 Fernando Perez <fperez@colorado.edu>
4498 2001-11-23 Fernando Perez <fperez@colorado.edu>
4488
4499
4489 * Version 0.1.12 released, 0.1.13 opened.
4500 * Version 0.1.12 released, 0.1.13 opened.
4490
4501
4491 * Removed option to set auto-quote and auto-paren escapes by
4502 * Removed option to set auto-quote and auto-paren escapes by
4492 user. The chances of breaking valid syntax are just too high. If
4503 user. The chances of breaking valid syntax are just too high. If
4493 someone *really* wants, they can always dig into the code.
4504 someone *really* wants, they can always dig into the code.
4494
4505
4495 * Made prompt separators configurable.
4506 * Made prompt separators configurable.
4496
4507
4497 2001-11-22 Fernando Perez <fperez@colorado.edu>
4508 2001-11-22 Fernando Perez <fperez@colorado.edu>
4498
4509
4499 * Small bugfixes in many places.
4510 * Small bugfixes in many places.
4500
4511
4501 * Removed the MyCompleter class from ipplib. It seemed redundant
4512 * Removed the MyCompleter class from ipplib. It seemed redundant
4502 with the C-p,C-n history search functionality. Less code to
4513 with the C-p,C-n history search functionality. Less code to
4503 maintain.
4514 maintain.
4504
4515
4505 * Moved all the original ipython.py code into ipythonlib.py. Right
4516 * Moved all the original ipython.py code into ipythonlib.py. Right
4506 now it's just one big dump into a function called make_IPython, so
4517 now it's just one big dump into a function called make_IPython, so
4507 no real modularity has been gained. But at least it makes the
4518 no real modularity has been gained. But at least it makes the
4508 wrapper script tiny, and since ipythonlib is a module, it gets
4519 wrapper script tiny, and since ipythonlib is a module, it gets
4509 compiled and startup is much faster.
4520 compiled and startup is much faster.
4510
4521
4511 This is a reasobably 'deep' change, so we should test it for a
4522 This is a reasobably 'deep' change, so we should test it for a
4512 while without messing too much more with the code.
4523 while without messing too much more with the code.
4513
4524
4514 2001-11-21 Fernando Perez <fperez@colorado.edu>
4525 2001-11-21 Fernando Perez <fperez@colorado.edu>
4515
4526
4516 * Version 0.1.11 released, 0.1.12 opened for further work.
4527 * Version 0.1.11 released, 0.1.12 opened for further work.
4517
4528
4518 * Removed dependency on Itpl. It was only needed in one place. It
4529 * Removed dependency on Itpl. It was only needed in one place. It
4519 would be nice if this became part of python, though. It makes life
4530 would be nice if this became part of python, though. It makes life
4520 *a lot* easier in some cases.
4531 *a lot* easier in some cases.
4521
4532
4522 * Simplified the prefilter code a bit. Now all handlers are
4533 * Simplified the prefilter code a bit. Now all handlers are
4523 expected to explicitly return a value (at least a blank string).
4534 expected to explicitly return a value (at least a blank string).
4524
4535
4525 * Heavy edits in ipplib. Removed the help system altogether. Now
4536 * Heavy edits in ipplib. Removed the help system altogether. Now
4526 obj?/?? is used for inspecting objects, a magic @doc prints
4537 obj?/?? is used for inspecting objects, a magic @doc prints
4527 docstrings, and full-blown Python help is accessed via the 'help'
4538 docstrings, and full-blown Python help is accessed via the 'help'
4528 keyword. This cleans up a lot of code (less to maintain) and does
4539 keyword. This cleans up a lot of code (less to maintain) and does
4529 the job. Since 'help' is now a standard Python component, might as
4540 the job. Since 'help' is now a standard Python component, might as
4530 well use it and remove duplicate functionality.
4541 well use it and remove duplicate functionality.
4531
4542
4532 Also removed the option to use ipplib as a standalone program. By
4543 Also removed the option to use ipplib as a standalone program. By
4533 now it's too dependent on other parts of IPython to function alone.
4544 now it's too dependent on other parts of IPython to function alone.
4534
4545
4535 * Fixed bug in genutils.pager. It would crash if the pager was
4546 * Fixed bug in genutils.pager. It would crash if the pager was
4536 exited immediately after opening (broken pipe).
4547 exited immediately after opening (broken pipe).
4537
4548
4538 * Trimmed down the VerboseTB reporting a little. The header is
4549 * Trimmed down the VerboseTB reporting a little. The header is
4539 much shorter now and the repeated exception arguments at the end
4550 much shorter now and the repeated exception arguments at the end
4540 have been removed. For interactive use the old header seemed a bit
4551 have been removed. For interactive use the old header seemed a bit
4541 excessive.
4552 excessive.
4542
4553
4543 * Fixed small bug in output of @whos for variables with multi-word
4554 * Fixed small bug in output of @whos for variables with multi-word
4544 types (only first word was displayed).
4555 types (only first word was displayed).
4545
4556
4546 2001-11-17 Fernando Perez <fperez@colorado.edu>
4557 2001-11-17 Fernando Perez <fperez@colorado.edu>
4547
4558
4548 * Version 0.1.10 released, 0.1.11 opened for further work.
4559 * Version 0.1.10 released, 0.1.11 opened for further work.
4549
4560
4550 * Modified dirs and friends. dirs now *returns* the stack (not
4561 * Modified dirs and friends. dirs now *returns* the stack (not
4551 prints), so one can manipulate it as a variable. Convenient to
4562 prints), so one can manipulate it as a variable. Convenient to
4552 travel along many directories.
4563 travel along many directories.
4553
4564
4554 * Fixed bug in magic_pdef: would only work with functions with
4565 * Fixed bug in magic_pdef: would only work with functions with
4555 arguments with default values.
4566 arguments with default values.
4556
4567
4557 2001-11-14 Fernando Perez <fperez@colorado.edu>
4568 2001-11-14 Fernando Perez <fperez@colorado.edu>
4558
4569
4559 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4570 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4560 example with IPython. Various other minor fixes and cleanups.
4571 example with IPython. Various other minor fixes and cleanups.
4561
4572
4562 * Version 0.1.9 released, 0.1.10 opened for further work.
4573 * Version 0.1.9 released, 0.1.10 opened for further work.
4563
4574
4564 * Added sys.path to the list of directories searched in the
4575 * Added sys.path to the list of directories searched in the
4565 execfile= option. It used to be the current directory and the
4576 execfile= option. It used to be the current directory and the
4566 user's IPYTHONDIR only.
4577 user's IPYTHONDIR only.
4567
4578
4568 2001-11-13 Fernando Perez <fperez@colorado.edu>
4579 2001-11-13 Fernando Perez <fperez@colorado.edu>
4569
4580
4570 * Reinstated the raw_input/prefilter separation that Janko had
4581 * Reinstated the raw_input/prefilter separation that Janko had
4571 initially. This gives a more convenient setup for extending the
4582 initially. This gives a more convenient setup for extending the
4572 pre-processor from the outside: raw_input always gets a string,
4583 pre-processor from the outside: raw_input always gets a string,
4573 and prefilter has to process it. We can then redefine prefilter
4584 and prefilter has to process it. We can then redefine prefilter
4574 from the outside and implement extensions for special
4585 from the outside and implement extensions for special
4575 purposes.
4586 purposes.
4576
4587
4577 Today I got one for inputting PhysicalQuantity objects
4588 Today I got one for inputting PhysicalQuantity objects
4578 (from Scientific) without needing any function calls at
4589 (from Scientific) without needing any function calls at
4579 all. Extremely convenient, and it's all done as a user-level
4590 all. Extremely convenient, and it's all done as a user-level
4580 extension (no IPython code was touched). Now instead of:
4591 extension (no IPython code was touched). Now instead of:
4581 a = PhysicalQuantity(4.2,'m/s**2')
4592 a = PhysicalQuantity(4.2,'m/s**2')
4582 one can simply say
4593 one can simply say
4583 a = 4.2 m/s**2
4594 a = 4.2 m/s**2
4584 or even
4595 or even
4585 a = 4.2 m/s^2
4596 a = 4.2 m/s^2
4586
4597
4587 I use this, but it's also a proof of concept: IPython really is
4598 I use this, but it's also a proof of concept: IPython really is
4588 fully user-extensible, even at the level of the parsing of the
4599 fully user-extensible, even at the level of the parsing of the
4589 command line. It's not trivial, but it's perfectly doable.
4600 command line. It's not trivial, but it's perfectly doable.
4590
4601
4591 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4602 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4592 the problem of modules being loaded in the inverse order in which
4603 the problem of modules being loaded in the inverse order in which
4593 they were defined in
4604 they were defined in
4594
4605
4595 * Version 0.1.8 released, 0.1.9 opened for further work.
4606 * Version 0.1.8 released, 0.1.9 opened for further work.
4596
4607
4597 * Added magics pdef, source and file. They respectively show the
4608 * Added magics pdef, source and file. They respectively show the
4598 definition line ('prototype' in C), source code and full python
4609 definition line ('prototype' in C), source code and full python
4599 file for any callable object. The object inspector oinfo uses
4610 file for any callable object. The object inspector oinfo uses
4600 these to show the same information.
4611 these to show the same information.
4601
4612
4602 * Version 0.1.7 released, 0.1.8 opened for further work.
4613 * Version 0.1.7 released, 0.1.8 opened for further work.
4603
4614
4604 * Separated all the magic functions into a class called Magic. The
4615 * Separated all the magic functions into a class called Magic. The
4605 InteractiveShell class was becoming too big for Xemacs to handle
4616 InteractiveShell class was becoming too big for Xemacs to handle
4606 (de-indenting a line would lock it up for 10 seconds while it
4617 (de-indenting a line would lock it up for 10 seconds while it
4607 backtracked on the whole class!)
4618 backtracked on the whole class!)
4608
4619
4609 FIXME: didn't work. It can be done, but right now namespaces are
4620 FIXME: didn't work. It can be done, but right now namespaces are
4610 all messed up. Do it later (reverted it for now, so at least
4621 all messed up. Do it later (reverted it for now, so at least
4611 everything works as before).
4622 everything works as before).
4612
4623
4613 * Got the object introspection system (magic_oinfo) working! I
4624 * Got the object introspection system (magic_oinfo) working! I
4614 think this is pretty much ready for release to Janko, so he can
4625 think this is pretty much ready for release to Janko, so he can
4615 test it for a while and then announce it. Pretty much 100% of what
4626 test it for a while and then announce it. Pretty much 100% of what
4616 I wanted for the 'phase 1' release is ready. Happy, tired.
4627 I wanted for the 'phase 1' release is ready. Happy, tired.
4617
4628
4618 2001-11-12 Fernando Perez <fperez@colorado.edu>
4629 2001-11-12 Fernando Perez <fperez@colorado.edu>
4619
4630
4620 * Version 0.1.6 released, 0.1.7 opened for further work.
4631 * Version 0.1.6 released, 0.1.7 opened for further work.
4621
4632
4622 * Fixed bug in printing: it used to test for truth before
4633 * Fixed bug in printing: it used to test for truth before
4623 printing, so 0 wouldn't print. Now checks for None.
4634 printing, so 0 wouldn't print. Now checks for None.
4624
4635
4625 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4636 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4626 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4637 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4627 reaches by hand into the outputcache. Think of a better way to do
4638 reaches by hand into the outputcache. Think of a better way to do
4628 this later.
4639 this later.
4629
4640
4630 * Various small fixes thanks to Nathan's comments.
4641 * Various small fixes thanks to Nathan's comments.
4631
4642
4632 * Changed magic_pprint to magic_Pprint. This way it doesn't
4643 * Changed magic_pprint to magic_Pprint. This way it doesn't
4633 collide with pprint() and the name is consistent with the command
4644 collide with pprint() and the name is consistent with the command
4634 line option.
4645 line option.
4635
4646
4636 * Changed prompt counter behavior to be fully like
4647 * Changed prompt counter behavior to be fully like
4637 Mathematica's. That is, even input that doesn't return a result
4648 Mathematica's. That is, even input that doesn't return a result
4638 raises the prompt counter. The old behavior was kind of confusing
4649 raises the prompt counter. The old behavior was kind of confusing
4639 (getting the same prompt number several times if the operation
4650 (getting the same prompt number several times if the operation
4640 didn't return a result).
4651 didn't return a result).
4641
4652
4642 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4653 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4643
4654
4644 * Fixed -Classic mode (wasn't working anymore).
4655 * Fixed -Classic mode (wasn't working anymore).
4645
4656
4646 * Added colored prompts using Nathan's new code. Colors are
4657 * Added colored prompts using Nathan's new code. Colors are
4647 currently hardwired, they can be user-configurable. For
4658 currently hardwired, they can be user-configurable. For
4648 developers, they can be chosen in file ipythonlib.py, at the
4659 developers, they can be chosen in file ipythonlib.py, at the
4649 beginning of the CachedOutput class def.
4660 beginning of the CachedOutput class def.
4650
4661
4651 2001-11-11 Fernando Perez <fperez@colorado.edu>
4662 2001-11-11 Fernando Perez <fperez@colorado.edu>
4652
4663
4653 * Version 0.1.5 released, 0.1.6 opened for further work.
4664 * Version 0.1.5 released, 0.1.6 opened for further work.
4654
4665
4655 * Changed magic_env to *return* the environment as a dict (not to
4666 * Changed magic_env to *return* the environment as a dict (not to
4656 print it). This way it prints, but it can also be processed.
4667 print it). This way it prints, but it can also be processed.
4657
4668
4658 * Added Verbose exception reporting to interactive
4669 * Added Verbose exception reporting to interactive
4659 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4670 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4660 traceback. Had to make some changes to the ultraTB file. This is
4671 traceback. Had to make some changes to the ultraTB file. This is
4661 probably the last 'big' thing in my mental todo list. This ties
4672 probably the last 'big' thing in my mental todo list. This ties
4662 in with the next entry:
4673 in with the next entry:
4663
4674
4664 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4675 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4665 has to specify is Plain, Color or Verbose for all exception
4676 has to specify is Plain, Color or Verbose for all exception
4666 handling.
4677 handling.
4667
4678
4668 * Removed ShellServices option. All this can really be done via
4679 * Removed ShellServices option. All this can really be done via
4669 the magic system. It's easier to extend, cleaner and has automatic
4680 the magic system. It's easier to extend, cleaner and has automatic
4670 namespace protection and documentation.
4681 namespace protection and documentation.
4671
4682
4672 2001-11-09 Fernando Perez <fperez@colorado.edu>
4683 2001-11-09 Fernando Perez <fperez@colorado.edu>
4673
4684
4674 * Fixed bug in output cache flushing (missing parameter to
4685 * Fixed bug in output cache flushing (missing parameter to
4675 __init__). Other small bugs fixed (found using pychecker).
4686 __init__). Other small bugs fixed (found using pychecker).
4676
4687
4677 * Version 0.1.4 opened for bugfixing.
4688 * Version 0.1.4 opened for bugfixing.
4678
4689
4679 2001-11-07 Fernando Perez <fperez@colorado.edu>
4690 2001-11-07 Fernando Perez <fperez@colorado.edu>
4680
4691
4681 * Version 0.1.3 released, mainly because of the raw_input bug.
4692 * Version 0.1.3 released, mainly because of the raw_input bug.
4682
4693
4683 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4694 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4684 and when testing for whether things were callable, a call could
4695 and when testing for whether things were callable, a call could
4685 actually be made to certain functions. They would get called again
4696 actually be made to certain functions. They would get called again
4686 once 'really' executed, with a resulting double call. A disaster
4697 once 'really' executed, with a resulting double call. A disaster
4687 in many cases (list.reverse() would never work!).
4698 in many cases (list.reverse() would never work!).
4688
4699
4689 * Removed prefilter() function, moved its code to raw_input (which
4700 * Removed prefilter() function, moved its code to raw_input (which
4690 after all was just a near-empty caller for prefilter). This saves
4701 after all was just a near-empty caller for prefilter). This saves
4691 a function call on every prompt, and simplifies the class a tiny bit.
4702 a function call on every prompt, and simplifies the class a tiny bit.
4692
4703
4693 * Fix _ip to __ip name in magic example file.
4704 * Fix _ip to __ip name in magic example file.
4694
4705
4695 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4706 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4696 work with non-gnu versions of tar.
4707 work with non-gnu versions of tar.
4697
4708
4698 2001-11-06 Fernando Perez <fperez@colorado.edu>
4709 2001-11-06 Fernando Perez <fperez@colorado.edu>
4699
4710
4700 * Version 0.1.2. Just to keep track of the recent changes.
4711 * Version 0.1.2. Just to keep track of the recent changes.
4701
4712
4702 * Fixed nasty bug in output prompt routine. It used to check 'if
4713 * Fixed nasty bug in output prompt routine. It used to check 'if
4703 arg != None...'. Problem is, this fails if arg implements a
4714 arg != None...'. Problem is, this fails if arg implements a
4704 special comparison (__cmp__) which disallows comparing to
4715 special comparison (__cmp__) which disallows comparing to
4705 None. Found it when trying to use the PhysicalQuantity module from
4716 None. Found it when trying to use the PhysicalQuantity module from
4706 ScientificPython.
4717 ScientificPython.
4707
4718
4708 2001-11-05 Fernando Perez <fperez@colorado.edu>
4719 2001-11-05 Fernando Perez <fperez@colorado.edu>
4709
4720
4710 * Also added dirs. Now the pushd/popd/dirs family functions
4721 * Also added dirs. Now the pushd/popd/dirs family functions
4711 basically like the shell, with the added convenience of going home
4722 basically like the shell, with the added convenience of going home
4712 when called with no args.
4723 when called with no args.
4713
4724
4714 * pushd/popd slightly modified to mimic shell behavior more
4725 * pushd/popd slightly modified to mimic shell behavior more
4715 closely.
4726 closely.
4716
4727
4717 * Added env,pushd,popd from ShellServices as magic functions. I
4728 * Added env,pushd,popd from ShellServices as magic functions. I
4718 think the cleanest will be to port all desired functions from
4729 think the cleanest will be to port all desired functions from
4719 ShellServices as magics and remove ShellServices altogether. This
4730 ShellServices as magics and remove ShellServices altogether. This
4720 will provide a single, clean way of adding functionality
4731 will provide a single, clean way of adding functionality
4721 (shell-type or otherwise) to IP.
4732 (shell-type or otherwise) to IP.
4722
4733
4723 2001-11-04 Fernando Perez <fperez@colorado.edu>
4734 2001-11-04 Fernando Perez <fperez@colorado.edu>
4724
4735
4725 * Added .ipython/ directory to sys.path. This way users can keep
4736 * Added .ipython/ directory to sys.path. This way users can keep
4726 customizations there and access them via import.
4737 customizations there and access them via import.
4727
4738
4728 2001-11-03 Fernando Perez <fperez@colorado.edu>
4739 2001-11-03 Fernando Perez <fperez@colorado.edu>
4729
4740
4730 * Opened version 0.1.1 for new changes.
4741 * Opened version 0.1.1 for new changes.
4731
4742
4732 * Changed version number to 0.1.0: first 'public' release, sent to
4743 * Changed version number to 0.1.0: first 'public' release, sent to
4733 Nathan and Janko.
4744 Nathan and Janko.
4734
4745
4735 * Lots of small fixes and tweaks.
4746 * Lots of small fixes and tweaks.
4736
4747
4737 * Minor changes to whos format. Now strings are shown, snipped if
4748 * Minor changes to whos format. Now strings are shown, snipped if
4738 too long.
4749 too long.
4739
4750
4740 * Changed ShellServices to work on __main__ so they show up in @who
4751 * Changed ShellServices to work on __main__ so they show up in @who
4741
4752
4742 * Help also works with ? at the end of a line:
4753 * Help also works with ? at the end of a line:
4743 ?sin and sin?
4754 ?sin and sin?
4744 both produce the same effect. This is nice, as often I use the
4755 both produce the same effect. This is nice, as often I use the
4745 tab-complete to find the name of a method, but I used to then have
4756 tab-complete to find the name of a method, but I used to then have
4746 to go to the beginning of the line to put a ? if I wanted more
4757 to go to the beginning of the line to put a ? if I wanted more
4747 info. Now I can just add the ? and hit return. Convenient.
4758 info. Now I can just add the ? and hit return. Convenient.
4748
4759
4749 2001-11-02 Fernando Perez <fperez@colorado.edu>
4760 2001-11-02 Fernando Perez <fperez@colorado.edu>
4750
4761
4751 * Python version check (>=2.1) added.
4762 * Python version check (>=2.1) added.
4752
4763
4753 * Added LazyPython documentation. At this point the docs are quite
4764 * Added LazyPython documentation. At this point the docs are quite
4754 a mess. A cleanup is in order.
4765 a mess. A cleanup is in order.
4755
4766
4756 * Auto-installer created. For some bizarre reason, the zipfiles
4767 * Auto-installer created. For some bizarre reason, the zipfiles
4757 module isn't working on my system. So I made a tar version
4768 module isn't working on my system. So I made a tar version
4758 (hopefully the command line options in various systems won't kill
4769 (hopefully the command line options in various systems won't kill
4759 me).
4770 me).
4760
4771
4761 * Fixes to Struct in genutils. Now all dictionary-like methods are
4772 * Fixes to Struct in genutils. Now all dictionary-like methods are
4762 protected (reasonably).
4773 protected (reasonably).
4763
4774
4764 * Added pager function to genutils and changed ? to print usage
4775 * Added pager function to genutils and changed ? to print usage
4765 note through it (it was too long).
4776 note through it (it was too long).
4766
4777
4767 * Added the LazyPython functionality. Works great! I changed the
4778 * Added the LazyPython functionality. Works great! I changed the
4768 auto-quote escape to ';', it's on home row and next to '. But
4779 auto-quote escape to ';', it's on home row and next to '. But
4769 both auto-quote and auto-paren (still /) escapes are command-line
4780 both auto-quote and auto-paren (still /) escapes are command-line
4770 parameters.
4781 parameters.
4771
4782
4772
4783
4773 2001-11-01 Fernando Perez <fperez@colorado.edu>
4784 2001-11-01 Fernando Perez <fperez@colorado.edu>
4774
4785
4775 * Version changed to 0.0.7. Fairly large change: configuration now
4786 * Version changed to 0.0.7. Fairly large change: configuration now
4776 is all stored in a directory, by default .ipython. There, all
4787 is all stored in a directory, by default .ipython. There, all
4777 config files have normal looking names (not .names)
4788 config files have normal looking names (not .names)
4778
4789
4779 * Version 0.0.6 Released first to Lucas and Archie as a test
4790 * Version 0.0.6 Released first to Lucas and Archie as a test
4780 run. Since it's the first 'semi-public' release, change version to
4791 run. Since it's the first 'semi-public' release, change version to
4781 > 0.0.6 for any changes now.
4792 > 0.0.6 for any changes now.
4782
4793
4783 * Stuff I had put in the ipplib.py changelog:
4794 * Stuff I had put in the ipplib.py changelog:
4784
4795
4785 Changes to InteractiveShell:
4796 Changes to InteractiveShell:
4786
4797
4787 - Made the usage message a parameter.
4798 - Made the usage message a parameter.
4788
4799
4789 - Require the name of the shell variable to be given. It's a bit
4800 - Require the name of the shell variable to be given. It's a bit
4790 of a hack, but allows the name 'shell' not to be hardwire in the
4801 of a hack, but allows the name 'shell' not to be hardwire in the
4791 magic (@) handler, which is problematic b/c it requires
4802 magic (@) handler, which is problematic b/c it requires
4792 polluting the global namespace with 'shell'. This in turn is
4803 polluting the global namespace with 'shell'. This in turn is
4793 fragile: if a user redefines a variable called shell, things
4804 fragile: if a user redefines a variable called shell, things
4794 break.
4805 break.
4795
4806
4796 - magic @: all functions available through @ need to be defined
4807 - magic @: all functions available through @ need to be defined
4797 as magic_<name>, even though they can be called simply as
4808 as magic_<name>, even though they can be called simply as
4798 @<name>. This allows the special command @magic to gather
4809 @<name>. This allows the special command @magic to gather
4799 information automatically about all existing magic functions,
4810 information automatically about all existing magic functions,
4800 even if they are run-time user extensions, by parsing the shell
4811 even if they are run-time user extensions, by parsing the shell
4801 instance __dict__ looking for special magic_ names.
4812 instance __dict__ looking for special magic_ names.
4802
4813
4803 - mainloop: added *two* local namespace parameters. This allows
4814 - mainloop: added *two* local namespace parameters. This allows
4804 the class to differentiate between parameters which were there
4815 the class to differentiate between parameters which were there
4805 before and after command line initialization was processed. This
4816 before and after command line initialization was processed. This
4806 way, later @who can show things loaded at startup by the
4817 way, later @who can show things loaded at startup by the
4807 user. This trick was necessary to make session saving/reloading
4818 user. This trick was necessary to make session saving/reloading
4808 really work: ideally after saving/exiting/reloading a session,
4819 really work: ideally after saving/exiting/reloading a session,
4809 *everythin* should look the same, including the output of @who. I
4820 *everythin* should look the same, including the output of @who. I
4810 was only able to make this work with this double namespace
4821 was only able to make this work with this double namespace
4811 trick.
4822 trick.
4812
4823
4813 - added a header to the logfile which allows (almost) full
4824 - added a header to the logfile which allows (almost) full
4814 session restoring.
4825 session restoring.
4815
4826
4816 - prepend lines beginning with @ or !, with a and log
4827 - prepend lines beginning with @ or !, with a and log
4817 them. Why? !lines: may be useful to know what you did @lines:
4828 them. Why? !lines: may be useful to know what you did @lines:
4818 they may affect session state. So when restoring a session, at
4829 they may affect session state. So when restoring a session, at
4819 least inform the user of their presence. I couldn't quite get
4830 least inform the user of their presence. I couldn't quite get
4820 them to properly re-execute, but at least the user is warned.
4831 them to properly re-execute, but at least the user is warned.
4821
4832
4822 * Started ChangeLog.
4833 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now