##// END OF EJS Templates
- Fairly significant changes to include Vivian's patches for improved pdb...
fperez -
Show More
@@ -0,0 +1,109 b''
1 # -*- coding: utf-8 -*-
2 """
3 Color schemes for exception handling code in IPython.
4
5 $Id: Prompts.py 638 2005-07-18 03:01:41Z fperez $"""
6
7 #*****************************************************************************
8 # Copyright (C) 2005 Fernando Perez <fperez@colorado.edu>
9 #
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
13
14 from IPython import Release
15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 __license__ = Release.license
17 __version__ = Release.version
18
19 #****************************************************************************
20 # Required modules
21 from IPython.ColorANSI import ColorSchemeTable, TermColors, ColorScheme
22
23 ExceptionColors = ColorSchemeTable()
24
25 # Populate it with color schemes
26 C = TermColors # shorthand and local lookup
27 ExceptionColors.add_scheme(ColorScheme(
28 'NoColor',
29 # The color to be used for the top line
30 topline = C.NoColor,
31
32 # The colors to be used in the traceback
33 filename = C.NoColor,
34 lineno = C.NoColor,
35 name = C.NoColor,
36 vName = C.NoColor,
37 val = C.NoColor,
38 em = C.NoColor,
39
40 # Emphasized colors for the last frame of the traceback
41 normalEm = C.NoColor,
42 filenameEm = C.NoColor,
43 linenoEm = C.NoColor,
44 nameEm = C.NoColor,
45 valEm = C.NoColor,
46
47 # Colors for printing the exception
48 excName = C.NoColor,
49 line = C.NoColor,
50 caret = C.NoColor,
51 Normal = C.NoColor
52 ))
53
54 # make some schemes as instances so we can copy them for modification easily
55 ExceptionColors.add_scheme(ColorScheme(
56 'Linux',
57 # The color to be used for the top line
58 topline = C.LightRed,
59
60 # The colors to be used in the traceback
61 filename = C.Green,
62 lineno = C.Green,
63 name = C.Purple,
64 vName = C.Cyan,
65 val = C.Green,
66 em = C.LightCyan,
67
68 # Emphasized colors for the last frame of the traceback
69 normalEm = C.LightCyan,
70 filenameEm = C.LightGreen,
71 linenoEm = C.LightGreen,
72 nameEm = C.LightPurple,
73 valEm = C.LightBlue,
74
75 # Colors for printing the exception
76 excName = C.LightRed,
77 line = C.Yellow,
78 caret = C.White,
79 Normal = C.Normal
80 ))
81
82 # For light backgrounds, swap dark/light colors
83 ExceptionColors.add_scheme(ColorScheme(
84 'LightBG',
85 # The color to be used for the top line
86 topline = C.Red,
87
88 # The colors to be used in the traceback
89 filename = C.LightGreen,
90 lineno = C.LightGreen,
91 name = C.LightPurple,
92 vName = C.Cyan,
93 val = C.LightGreen,
94 em = C.Cyan,
95
96 # Emphasized colors for the last frame of the traceback
97 normalEm = C.Cyan,
98 filenameEm = C.Green,
99 linenoEm = C.Green,
100 nameEm = C.Purple,
101 valEm = C.Blue,
102
103 # Colors for printing the exception
104 excName = C.Red,
105 #line = C.Brown, # brown often is displayed as yellow
106 line = C.Red,
107 caret = C.Normal,
108 Normal = C.Normal
109 ))
@@ -1,155 +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 410 2004-11-04 07:58:17Z fperez $"""
4 $Id: ColorANSI.py 951 2005-12-25 00:57:24Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2002-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__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
17 __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
18
18
19 import os
19 import os
20 from UserDict import UserDict
21
20
22 from IPython.Struct import Struct
21 from IPython.Struct import Struct
23
22
24 def make_color_table(in_class):
23 def make_color_table(in_class):
25 """Build a set of color attributes in a class.
24 """Build a set of color attributes in a class.
26
25
27 Helper function for building the *TermColors classes."""
26 Helper function for building the *TermColors classes."""
28
27
29 color_templates = (
28 color_templates = (
30 ("Black" , "0;30"),
29 ("Black" , "0;30"),
31 ("Red" , "0;31"),
30 ("Red" , "0;31"),
32 ("Green" , "0;32"),
31 ("Green" , "0;32"),
33 ("Brown" , "0;33"),
32 ("Brown" , "0;33"),
34 ("Blue" , "0;34"),
33 ("Blue" , "0;34"),
35 ("Purple" , "0;35"),
34 ("Purple" , "0;35"),
36 ("Cyan" , "0;36"),
35 ("Cyan" , "0;36"),
37 ("LightGray" , "0;37"),
36 ("LightGray" , "0;37"),
38 ("DarkGray" , "1;30"),
37 ("DarkGray" , "1;30"),
39 ("LightRed" , "1;31"),
38 ("LightRed" , "1;31"),
40 ("LightGreen" , "1;32"),
39 ("LightGreen" , "1;32"),
41 ("Yellow" , "1;33"),
40 ("Yellow" , "1;33"),
42 ("LightBlue" , "1;34"),
41 ("LightBlue" , "1;34"),
43 ("LightPurple" , "1;35"),
42 ("LightPurple" , "1;35"),
44 ("LightCyan" , "1;36"),
43 ("LightCyan" , "1;36"),
45 ("White" , "1;37"), )
44 ("White" , "1;37"), )
46
45
47 for name,value in color_templates:
46 for name,value in color_templates:
48 setattr(in_class,name,in_class._base % value)
47 setattr(in_class,name,in_class._base % value)
49
48
50 class TermColors:
49 class TermColors:
51 """Color escape sequences.
50 """Color escape sequences.
52
51
53 This class defines the escape sequences for all the standard (ANSI?)
52 This class defines the escape sequences for all the standard (ANSI?)
54 colors in terminals. Also defines a NoColor escape which is just the null
53 colors in terminals. Also defines a NoColor escape which is just the null
55 string, suitable for defining 'dummy' color schemes in terminals which get
54 string, suitable for defining 'dummy' color schemes in terminals which get
56 confused by color escapes.
55 confused by color escapes.
57
56
58 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."""
59
58
60 NoColor = '' # for color schemes in color-less terminals.
59 NoColor = '' # for color schemes in color-less terminals.
61 Normal = '\033[0m' # Reset normal coloring
60 Normal = '\033[0m' # Reset normal coloring
62 _base = '\033[%sm' # Template for all other colors
61 _base = '\033[%sm' # Template for all other colors
63
62
64 # Build the actual color table as a set of class attributes:
63 # Build the actual color table as a set of class attributes:
65 make_color_table(TermColors)
64 make_color_table(TermColors)
66
65
67 class InputTermColors:
66 class InputTermColors:
68 """Color escape sequences for input prompts.
67 """Color escape sequences for input prompts.
69
68
70 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
71 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
72 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
73 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().
74
73
75 This class defines the escape sequences for all the standard (ANSI?)
74 This class defines the escape sequences for all the standard (ANSI?)
76 colors in terminals. Also defines a NoColor escape which is just the null
75 colors in terminals. Also defines a NoColor escape which is just the null
77 string, suitable for defining 'dummy' color schemes in terminals which get
76 string, suitable for defining 'dummy' color schemes in terminals which get
78 confused by color escapes.
77 confused by color escapes.
79
78
80 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."""
81
80
82 NoColor = '' # for color schemes in color-less terminals.
81 NoColor = '' # for color schemes in color-less terminals.
83 Normal = '\001\033[0m\002' # Reset normal coloring
82 Normal = '\001\033[0m\002' # Reset normal coloring
84 _base = '\001\033[%sm\002' # Template for all other colors
83 _base = '\001\033[%sm\002' # Template for all other colors
85
84
86 # Build the actual color table as a set of class attributes:
85 # Build the actual color table as a set of class attributes:
87 make_color_table(InputTermColors)
86 make_color_table(InputTermColors)
88
87
89 class ColorScheme:
88 class ColorScheme:
90 """Generic color scheme class. Just a name and a Struct."""
89 """Generic color scheme class. Just a name and a Struct."""
91 def __init__(self,__scheme_name_,colordict=None,**colormap):
90 def __init__(self,__scheme_name_,colordict=None,**colormap):
92 self.name = __scheme_name_
91 self.name = __scheme_name_
93 if colordict is None:
92 if colordict is None:
94 self.colors = Struct(**colormap)
93 self.colors = Struct(**colormap)
95 else:
94 else:
96 self.colors = Struct(colordict)
95 self.colors = Struct(colordict)
97
96
98 class ColorSchemeTable(UserDict):
97 def copy(self,name=None):
98 """Return a full copy of the object, optionally renaming it."""
99 if name is None:
100 name = self.name
101 return ColorScheme(name,self.colors.__dict__)
102
103 class ColorSchemeTable(dict):
99 """General class to handle tables of color schemes.
104 """General class to handle tables of color schemes.
100
105
101 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
102 attributes and some convenient methods.
107 attributes and some convenient methods.
103
108
104 active_scheme_name -> obvious
109 active_scheme_name -> obvious
105 active_colors -> actual color table of the active scheme"""
110 active_colors -> actual color table of the active scheme"""
106
111
107 def __init__(self,scheme_list=None,default_scheme=''):
112 def __init__(self,scheme_list=None,default_scheme=''):
108 """Create a table of color schemes.
113 """Create a table of color schemes.
109
114
110 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
111 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
112 the default active scheme.
117 the default active scheme.
113 """
118 """
114
119
115 UserDict.__init__(self)
120 # create object attributes to be set later
116 if scheme_list is None:
117 self.active_scheme_name = ''
121 self.active_scheme_name = ''
118 self.active_colors = None
122 self.active_colors = None
119 else:
123
124 if scheme_list:
120 if default_scheme == '':
125 if default_scheme == '':
121 raise ValueError,'you must specify the default color scheme'
126 raise ValueError,'you must specify the default color scheme'
122 for scheme in scheme_list:
127 for scheme in scheme_list:
123 self.add_scheme(scheme)
128 self.add_scheme(scheme)
124 self.set_active_scheme(default_scheme)
129 self.set_active_scheme(default_scheme)
125
130
131 def copy(self):
132 """Return full copy of object"""
133 return ColorSchemeTable(self.values(),self.active_scheme_name)
134
126 def add_scheme(self,new_scheme):
135 def add_scheme(self,new_scheme):
127 """Add a new color scheme to the table."""
136 """Add a new color scheme to the table."""
128 if not isinstance(new_scheme,ColorScheme):
137 if not isinstance(new_scheme,ColorScheme):
129 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
138 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
130 self[new_scheme.name] = new_scheme
139 self[new_scheme.name] = new_scheme
131
140
132 def set_active_scheme(self,scheme,case_sensitive=0):
141 def set_active_scheme(self,scheme,case_sensitive=0):
133 """Set the currently active scheme.
142 """Set the currently active scheme.
134
143
135 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
136 be changed by setting the parameter case_sensitive to true."""
145 be changed by setting the parameter case_sensitive to true."""
137
146
138 scheme_list = self.keys()
147 scheme_names = self.keys()
139 if case_sensitive:
148 if case_sensitive:
140 valid_schemes = scheme_list
149 valid_schemes = scheme_names
141 scheme_test = scheme
150 scheme_test = scheme
142 else:
151 else:
143 valid_schemes = [s.lower() for s in scheme_list]
152 valid_schemes = [s.lower() for s in scheme_names]
144 scheme_test = scheme.lower()
153 scheme_test = scheme.lower()
145 try:
154 try:
146 scheme_idx = valid_schemes.index(scheme_test)
155 scheme_idx = valid_schemes.index(scheme_test)
147 except ValueError:
156 except ValueError:
148 raise ValueError,'Unrecognized color scheme: ' + scheme + \
157 raise ValueError,'Unrecognized color scheme: ' + scheme + \
149 '\nValid schemes: '+str(scheme_list).replace("'', ",'')
158 '\nValid schemes: '+str(scheme_names).replace("'', ",'')
150 else:
159 else:
151 active = scheme_list[scheme_idx]
160 active = scheme_names[scheme_idx]
152 self.active_scheme_name = active
161 self.active_scheme_name = active
153 self.active_colors = self[active].colors
162 self.active_colors = self[active].colors
154 # Now allow using '' as an index for the current active scheme
163 # Now allow using '' as an index for the current active scheme
155 self[''] = self[active]
164 self[''] = self[active]
@@ -1,110 +1,110 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
3
4 $Id: CrashHandler.py 775 2005-09-01 20:24:59Z fperez $"""
4 $Id: CrashHandler.py 951 2005-12-25 00:57:24Z 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 __version__ = Release.version
16 __version__ = Release.version
17
17
18 #****************************************************************************
18 #****************************************************************************
19 # Required modules
19 # Required modules
20
20
21 # From the standard library
21 # From the standard library
22 import os,sys
22 import os,sys
23 from pprint import pprint,pformat
23 from pprint import pprint,pformat
24
24
25 # Homebrewed
25 # Homebrewed
26 from IPython.genutils import *
27 from IPython.Itpl import Itpl,itpl,printpl
26 from IPython.Itpl import Itpl,itpl,printpl
27 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
28 from IPython import ultraTB
28 from IPython import ultraTB
29 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
29 from IPython.genutils import *
30
30
31 #****************************************************************************
31 #****************************************************************************
32 class CrashHandler:
32 class CrashHandler:
33 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
33 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
34
34
35 def __init__(self,IP):
35 def __init__(self,IP):
36 self.IP = IP # IPython instance
36 self.IP = IP # IPython instance
37 self.bug_contact = Release.authors['Fernando'][0]
37 self.bug_contact = Release.authors['Fernando'][0]
38 self.mailto = Release.authors['Fernando'][1]
38 self.mailto = Release.authors['Fernando'][1]
39
39
40 def __call__(self,etype, evalue, etb):
40 def __call__(self,etype, evalue, etb):
41
41
42 # Report tracebacks shouldn't use color in general (safer for users)
42 # Report tracebacks shouldn't use color in general (safer for users)
43 color_scheme = 'NoColor'
43 color_scheme = 'NoColor'
44
44
45 # Use this ONLY for developer debugging (keep commented out for release)
45 # Use this ONLY for developer debugging (keep commented out for release)
46 #color_scheme = 'Linux' # dbg
46 #color_scheme = 'Linux' # dbg
47
47
48 try:
48 try:
49 rptdir = self.IP.rc.ipythondir
49 rptdir = self.IP.rc.ipythondir
50 except:
50 except:
51 rptdir = os.getcwd()
51 rptdir = os.getcwd()
52 if not os.path.isdir(rptdir):
52 if not os.path.isdir(rptdir):
53 rptdir = os.getcwd()
53 rptdir = os.getcwd()
54 self.report_name = os.path.join(rptdir,'IPython_crash_report.txt')
54 self.report_name = os.path.join(rptdir,'IPython_crash_report.txt')
55 self.TBhandler = ultraTB.VerboseTB(color_scheme=color_scheme,long_header=1)
55 self.TBhandler = ultraTB.VerboseTB(color_scheme=color_scheme,long_header=1)
56 traceback = self.TBhandler.text(etype,evalue,etb,context=31)
56 traceback = self.TBhandler.text(etype,evalue,etb,context=31)
57
57
58 # print traceback to screen
58 # print traceback to screen
59 print >> sys.stderr, traceback
59 print >> sys.stderr, traceback
60
60
61 # and generate a complete report on disk
61 # and generate a complete report on disk
62 try:
62 try:
63 report = open(self.report_name,'w')
63 report = open(self.report_name,'w')
64 except:
64 except:
65 print >> sys.stderr, 'Could not create crash report on disk.'
65 print >> sys.stderr, 'Could not create crash report on disk.'
66 return
66 return
67
67
68 msg = itpl('\n'+'*'*70+'\n'
68 msg = itpl('\n'+'*'*70+'\n'
69 """
69 """
70 Oops, IPython crashed. We do our best to make it stable, but...
70 Oops, IPython crashed. We do our best to make it stable, but...
71
71
72 A crash report was automatically generated with the following information:
72 A crash report was automatically generated with the following information:
73 - A verbatim copy of the traceback above this text.
73 - A verbatim copy of the traceback above this text.
74 - A copy of your input history during this session.
74 - A copy of your input history during this session.
75 - Data on your current IPython configuration.
75 - Data on your current IPython configuration.
76
76
77 It was left in the file named:
77 It was left in the file named:
78 \t'$self.report_name'
78 \t'$self.report_name'
79 If you can email this file to the developers, the information in it will help
79 If you can email this file to the developers, the information in it will help
80 them in understanding and correcting the problem.
80 them in understanding and correcting the problem.
81
81
82 You can mail it to $self.bug_contact at $self.mailto
82 You can mail it to $self.bug_contact at $self.mailto
83 with the subject 'IPython Crash Report'.
83 with the subject 'IPython Crash Report'.
84
84
85 If you want to do it now, the following command will work (under Unix):
85 If you want to do it now, the following command will work (under Unix):
86 mail -s 'IPython Crash Report' $self.mailto < $self.report_name
86 mail -s 'IPython Crash Report' $self.mailto < $self.report_name
87
87
88 To ensure accurate tracking of this issue, please file a report about it at:
88 To ensure accurate tracking of this issue, please file a report about it at:
89 http://www.scipy.net/roundup/ipython (IPython's online bug tracker).
89 http://www.scipy.net/roundup/ipython (IPython's online bug tracker).
90 """)
90 """)
91 print >> sys.stderr, msg
91 print >> sys.stderr, msg
92
92
93 sec_sep = '\n\n'+'*'*75+'\n\n'
93 sec_sep = '\n\n'+'*'*75+'\n\n'
94 report.write('*'*75+'\n\n'+'IPython post-mortem report\n\n')
94 report.write('*'*75+'\n\n'+'IPython post-mortem report\n\n')
95 report.write('IPython version: %s \n\n' % Release.version)
95 report.write('IPython version: %s \n\n' % Release.version)
96 report.write('SVN revision : %s \n\n' % Release.revision)
96 report.write('SVN revision : %s \n\n' % Release.revision)
97 report.write('Platform info : os.name -> %s, sys.platform -> %s' %
97 report.write('Platform info : os.name -> %s, sys.platform -> %s' %
98 (os.name,sys.platform) )
98 (os.name,sys.platform) )
99 report.write(sec_sep+'Current user configuration structure:\n\n')
99 report.write(sec_sep+'Current user configuration structure:\n\n')
100 report.write(pformat(self.IP.rc.dict()))
100 report.write(pformat(self.IP.rc.dict()))
101 report.write(sec_sep+'Crash traceback:\n\n' + traceback)
101 report.write(sec_sep+'Crash traceback:\n\n' + traceback)
102 try:
102 try:
103 report.write(sec_sep+"History of session input:")
103 report.write(sec_sep+"History of session input:")
104 for line in self.IP.user_ns['_ih']:
104 for line in self.IP.user_ns['_ih']:
105 report.write(line)
105 report.write(line)
106 report.write('\n*** Last line of input (may not be in above history):\n')
106 report.write('\n*** Last line of input (may not be in above history):\n')
107 report.write(self.IP._last_input_line+'\n')
107 report.write(self.IP._last_input_line+'\n')
108 except:
108 except:
109 pass
109 pass
110 report.close()
110 report.close()
@@ -1,53 +1,264 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 http://www.python.org/2.2.3/license.html
16 http://www.python.org/2.2.3/license.html
17
17
18 $Id: Debugger.py 590 2005-05-30 06:26:51Z fperez $"""
18 $Id: Debugger.py 951 2005-12-25 00:57:24Z fperez $"""
19
19
20 from IPython import Release
20 from IPython import Release
21 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __author__ = '%s <%s>' % Release.authors['Fernando']
22 __license__ = 'Python'
22 __license__ = 'Python'
23
23
24 import pdb,bdb,cmd,os,sys
24 import pdb,bdb,cmd,os,sys,linecache
25 from IPython import PyColorize, ColorANSI
26 from IPython.genutils import Term
27 from IPython.excolors import ExceptionColors
28
29 def _file_lines(fname):
30 """Return the contents of a named file as a list of lines.
31
32 This function never raises an IOError exception: if the file can't be
33 read, it simply returns an empty list."""
34
35 try:
36 outfile = open(fname)
37 except IOError:
38 return []
39 else:
40 out = outfile.readlines()
41 outfile.close()
42 return out
43
25
44
26 class Pdb(pdb.Pdb):
45 class Pdb(pdb.Pdb):
27 """Modified Pdb class, does not load readline."""
46 """Modified Pdb class, does not load readline."""
28 def __init__(self):
47 def __init__(self,color_scheme='NoColor'):
29 bdb.Bdb.__init__(self)
48 bdb.Bdb.__init__(self)
30 cmd.Cmd.__init__(self,completekey=None) # don't load readline
49 cmd.Cmd.__init__(self,completekey=None) # don't load readline
31 self.prompt = '(Pdb) '
50 self.prompt = 'ipdb> ' # The default prompt is '(Pdb)'
32 self.aliases = {}
51 self.aliases = {}
33
52
34 # Read $HOME/.pdbrc and ./.pdbrc
53 # Read $HOME/.pdbrc and ./.pdbrc
54 try:
55 self.rcLines = _file_lines(os.path.join(os.environ['HOME'],
56 ".pdbrc"))
57 except KeyError:
35 self.rcLines = []
58 self.rcLines = []
36 if os.environ.has_key('HOME'):
59 self.rcLines.extend(_file_lines(".pdbrc"))
37 envHome = os.environ['HOME']
60
61 # Create color table: we copy the default one from the traceback
62 # module and add a few attributes needed for debugging
63 self.color_scheme_table = ExceptionColors.copy()
64
65 # shorthands
66 C = ColorANSI.TermColors
67 cst = self.color_scheme_table
68
69 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
70 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
71
72 cst['Linux'].colors.breakpoint_enabled = C.LightRed
73 cst['Linux'].colors.breakpoint_disabled = C.Red
74
75 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
76 cst['LightBG'].colors.breakpoint_disabled = C.Red
77
78 self.set_colors(color_scheme)
79
80 def set_colors(self, scheme):
81 """Shorthand access to the color table scheme selector method."""
82 self.color_scheme_table.set_active_scheme(scheme)
83
84
85 def interaction(self, frame, traceback):
86 __IPYTHON__.set_completer_frame(frame)
87 pdb.Pdb.interaction(self, frame, traceback)
88
89
90 def do_up(self, arg):
91 pdb.Pdb.do_up(self, arg)
92 __IPYTHON__.set_completer_frame(self.curframe)
93 do_u = do_up
94
95
96 def do_down(self, arg):
97 pdb.Pdb.do_down(self, arg)
98 __IPYTHON__.set_completer_frame(self.curframe)
99 do_d = do_down
100
101
102 def postloop(self):
103 __IPYTHON__.set_completer_frame(None)
104
105
106 def print_stack_trace(self):
38 try:
107 try:
39 rcFile = open(os.path.join(envHome, ".pdbrc"))
108 for frame_lineno in self.stack:
40 except IOError:
109 self.print_stack_entry(frame_lineno, context = 5)
110 except KeyboardInterrupt:
41 pass
111 pass
112
113
114 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
115 context = 3):
116 frame, lineno = frame_lineno
117 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
118
119
120 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
121 import linecache, repr
122
123 ret = ""
124
125 Colors = self.color_scheme_table.active_colors
126 ColorsNormal = Colors.Normal
127 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
128 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
129 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
130 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
131 ColorsNormal)
132
133 frame, lineno = frame_lineno
134
135 return_value = ''
136 if '__return__' in frame.f_locals:
137 rv = frame.f_locals['__return__']
138 #return_value += '->'
139 return_value += repr.repr(rv) + '\n'
140 ret += return_value
141
142 #s = filename + '(' + `lineno` + ')'
143 filename = self.canonic(frame.f_code.co_filename)
144 link = tpl_link % filename
145
146 if frame.f_code.co_name:
147 func = frame.f_code.co_name
148 else:
149 func = "<lambda>"
150
151 call = ''
152 if func != '?':
153 if '__args__' in frame.f_locals:
154 args = repr.repr(frame.f_locals['__args__'])
155 else:
156 args = '()'
157 call = tpl_call % (func, args)
158
159 level = '%s %s\n' % (link, call)
160 ret += level
161
162 start = lineno - 1 - context//2
163 lines = linecache.getlines(filename)
164 start = max(start, 0)
165 start = min(start, len(lines) - context)
166 lines = lines[start : start + context]
167
168 for i in range(len(lines)):
169 line = lines[i]
170 if start + 1 + i == lineno:
171 ret += self.__format_line(tpl_line_em, filename, start + 1 + i, line, arrow = True)
172 else:
173 ret += self.__format_line(tpl_line, filename, start + 1 + i, line, arrow = False)
174
175 return ret
176
177
178 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
179 bp_mark = ""
180 bp_mark_color = ""
181
182 bp = None
183 if lineno in self.get_file_breaks(filename):
184 bps = self.get_breaks(filename, lineno)
185 bp = bps[-1]
186
187 if bp:
188 Colors = self.color_scheme_table.active_colors
189 bp_mark = str(bp.number)
190 bp_mark_color = Colors.breakpoint_enabled
191 if not bp.enabled:
192 bp_mark_color = Colors.breakpoint_disabled
193
194 numbers_width = 7
195 if arrow:
196 # This is the line with the error
197 pad = numbers_width - len(str(lineno)) - len(bp_mark)
198 if pad >= 3:
199 marker = '-'*(pad-3) + '-> '
200 elif pad == 2:
201 marker = '> '
202 elif pad == 1:
203 marker = '>'
204 else:
205 marker = ''
206 num = '%s%s' % (marker, str(lineno))
207 line = tpl_line % (bp_mark_color + bp_mark, num, line)
42 else:
208 else:
43 for line in rcFile.readlines():
209 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
44 self.rcLines.append(line)
210 line = tpl_line % (bp_mark_color + bp_mark, num, line)
45 rcFile.close()
211
212 return line
213
214
215 def do_list(self, arg):
216 self.lastcmd = 'list'
217 last = None
218 if arg:
46 try:
219 try:
47 rcFile = open(".pdbrc")
220 x = eval(arg, {}, {})
48 except IOError:
221 if type(x) == type(()):
49 pass
222 first, last = x
223 first = int(first)
224 last = int(last)
225 if last < first:
226 # Assume it's a count
227 last = first + last
228 else:
229 first = max(1, int(x) - 5)
230 except:
231 print '*** Error in argument:', `arg`
232 return
233 elif self.lineno is None:
234 first = max(1, self.curframe.f_lineno - 5)
50 else:
235 else:
51 for line in rcFile.readlines():
236 first = self.lineno + 1
52 self.rcLines.append(line)
237 if last is None:
53 rcFile.close()
238 last = first + 10
239 filename = self.curframe.f_code.co_filename
240 try:
241 Colors = self.color_scheme_table.active_colors
242 ColorsNormal = Colors.Normal
243 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
244 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
245 src = []
246 for lineno in range(first, last+1):
247 line = linecache.getline(filename, lineno)
248 if not line:
249 break
250
251 if lineno == self.curframe.f_lineno:
252 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
253 else:
254 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
255
256 src.append(line)
257 self.lineno = lineno
258
259 print >>Term.cout, ''.join(src)
260
261 except KeyboardInterrupt:
262 pass
263
264 do_l = do_list
@@ -1,2563 +1,2573 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 923 2005-11-15 08:51:15Z fperez $"""
4 $Id: Magic.py 951 2005-12-25 00:57:24Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time
24 import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time
25 import Debugger
26 from getopt import getopt
27 from pprint import pprint, pformat
28 from cStringIO import StringIO
29
30 # profile isn't bundled by default in Debian for license reasons
25 try:
31 try:
26 import profile,pstats
32 import profile,pstats
27 except ImportError:
33 except ImportError:
28 profile = pstats = None
34 profile = pstats = None
29 from getopt import getopt
30 from pprint import pprint, pformat
31 from cStringIO import StringIO
32
35
33 # Homebrewed
36 # Homebrewed
34 from IPython.Struct import Struct
37 from IPython.Struct import Struct
35 from IPython.Itpl import Itpl, itpl, printpl,itplns
38 from IPython.Itpl import Itpl, itpl, printpl,itplns
36 from IPython.FakeModule import FakeModule
39 from IPython.FakeModule import FakeModule
37 from IPython.PyColorize import Parser
40 from IPython.PyColorize import Parser
38 from IPython import OInspect
41 from IPython import OInspect
39 from IPython import wildcard
42 from IPython import wildcard
40 from IPython.genutils import *
43 from IPython.genutils import *
41
44
42 # Globals to be set later by Magic constructor
45 # Globals to be set later by Magic constructor
43 MAGIC_PREFIX = ''
46 MAGIC_PREFIX = ''
44 MAGIC_ESCAPE = ''
47 MAGIC_ESCAPE = ''
45
48
46 #***************************************************************************
49 #***************************************************************************
47 # Utility functions
50 # Utility functions
48 def magic2python(cmd):
51 def magic2python(cmd):
49 """Convert a command string of magic syntax to valid Python code."""
52 """Convert a command string of magic syntax to valid Python code."""
50
53
51 if cmd.startswith('#'+MAGIC_ESCAPE) or \
54 if cmd.startswith('#'+MAGIC_ESCAPE) or \
52 cmd.startswith(MAGIC_ESCAPE):
55 cmd.startswith(MAGIC_ESCAPE):
53 if cmd[0]=='#':
56 if cmd[0]=='#':
54 cmd = cmd[1:]
57 cmd = cmd[1:]
55 # we need to return the proper line end later
58 # we need to return the proper line end later
56 if cmd[-1] == '\n':
59 if cmd[-1] == '\n':
57 endl = '\n'
60 endl = '\n'
58 else:
61 else:
59 endl = ''
62 endl = ''
60 try:
63 try:
61 func,args = cmd[1:].split(' ',1)
64 func,args = cmd[1:].split(' ',1)
62 except:
65 except:
63 func,args = cmd[1:].rstrip(),''
66 func,args = cmd[1:].rstrip(),''
64 args = args.replace('"','\\"').replace("'","\\'").rstrip()
67 args = args.replace('"','\\"').replace("'","\\'").rstrip()
65 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
68 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
66 else:
69 else:
67 return cmd
70 return cmd
68
71
69 def on_off(tag):
72 def on_off(tag):
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
73 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 return ['OFF','ON'][tag]
74 return ['OFF','ON'][tag]
72
75
73
76
74 #****************************************************************************
77 #****************************************************************************
75 # Utility classes
78 # Utility classes
76 class Macro:
79 class Macro:
77 """Simple class to store the value of macros as strings.
80 """Simple class to store the value of macros as strings.
78
81
79 This allows us to later exec them by checking when something is an
82 This allows us to later exec them by checking when something is an
80 instance of this class."""
83 instance of this class."""
81
84
82 def __init__(self,cmds):
85 def __init__(self,cmds):
83 """Build a macro from a list of commands."""
86 """Build a macro from a list of commands."""
84
87
85 # Since the list may include multi-line entries, first make sure that
88 # Since the list may include multi-line entries, first make sure that
86 # they've been all broken up before passing it to magic2python
89 # they've been all broken up before passing it to magic2python
87 cmdlist = map(magic2python,''.join(cmds).split('\n'))
90 cmdlist = map(magic2python,''.join(cmds).split('\n'))
88 self.value = '\n'.join(cmdlist)
91 self.value = '\n'.join(cmdlist)
89
92
90 def __str__(self):
93 def __str__(self):
91 return self.value
94 return self.value
92
95
93 #***************************************************************************
96 #***************************************************************************
94 # Main class implementing Magic functionality
97 # Main class implementing Magic functionality
95 class Magic:
98 class Magic:
96 """Magic functions for InteractiveShell.
99 """Magic functions for InteractiveShell.
97
100
98 Shell functions which can be reached as %function_name. All magic
101 Shell functions which can be reached as %function_name. All magic
99 functions should accept a string, which they can parse for their own
102 functions should accept a string, which they can parse for their own
100 needs. This can make some functions easier to type, eg `%cd ../`
103 needs. This can make some functions easier to type, eg `%cd ../`
101 vs. `%cd("../")`
104 vs. `%cd("../")`
102
105
103 ALL definitions MUST begin with the prefix magic_. The user won't need it
106 ALL definitions MUST begin with the prefix magic_. The user won't need it
104 at the command line, but it is is needed in the definition. """
107 at the command line, but it is is needed in the definition. """
105
108
106 # class globals
109 # class globals
107 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
110 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
108 'Automagic is ON, % prefix NOT needed for magic functions.']
111 'Automagic is ON, % prefix NOT needed for magic functions.']
109
112
110 #......................................................................
113 #......................................................................
111 # some utility functions
114 # some utility functions
112
115
113 def __init__(self,shell):
116 def __init__(self,shell):
114 # XXX This is hackish, clean up later to avoid these messy globals
117 # XXX This is hackish, clean up later to avoid these messy globals
115 global MAGIC_PREFIX, MAGIC_ESCAPE
118 global MAGIC_PREFIX, MAGIC_ESCAPE
116
119
117 self.options_table = {}
120 self.options_table = {}
118 MAGIC_PREFIX = shell.name+'.magic_'
121 MAGIC_PREFIX = shell.name+'.magic_'
119 MAGIC_ESCAPE = shell.ESC_MAGIC
122 MAGIC_ESCAPE = shell.ESC_MAGIC
120 if profile is None:
123 if profile is None:
121 self.magic_prun = self.profile_missing_notice
124 self.magic_prun = self.profile_missing_notice
122
125
123 def profile_missing_notice(self, *args, **kwargs):
126 def profile_missing_notice(self, *args, **kwargs):
124 error("""\
127 error("""\
125 The profile module could not be found. If you are a Debian user,
128 The profile module could not be found. If you are a Debian user,
126 it has been removed from the standard Debian package because of its non-free
129 it has been removed from the standard Debian package because of its non-free
127 license. To use profiling, please install"python2.3-profiler" from non-free.""")
130 license. To use profiling, please install"python2.3-profiler" from non-free.""")
128
131
129 def default_option(self,fn,optstr):
132 def default_option(self,fn,optstr):
130 """Make an entry in the options_table for fn, with value optstr"""
133 """Make an entry in the options_table for fn, with value optstr"""
131
134
132 if fn not in self.lsmagic():
135 if fn not in self.lsmagic():
133 error("%s is not a magic function" % fn)
136 error("%s is not a magic function" % fn)
134 self.options_table[fn] = optstr
137 self.options_table[fn] = optstr
135
138
136 def lsmagic(self):
139 def lsmagic(self):
137 """Return a list of currently available magic functions.
140 """Return a list of currently available magic functions.
138
141
139 Gives a list of the bare names after mangling (['ls','cd', ...], not
142 Gives a list of the bare names after mangling (['ls','cd', ...], not
140 ['magic_ls','magic_cd',...]"""
143 ['magic_ls','magic_cd',...]"""
141
144
142 # FIXME. This needs a cleanup, in the way the magics list is built.
145 # FIXME. This needs a cleanup, in the way the magics list is built.
143
146
144 # magics in class definition
147 # magics in class definition
145 class_magic = lambda fn: fn.startswith('magic_') and \
148 class_magic = lambda fn: fn.startswith('magic_') and \
146 callable(Magic.__dict__[fn])
149 callable(Magic.__dict__[fn])
147 # in instance namespace (run-time user additions)
150 # in instance namespace (run-time user additions)
148 inst_magic = lambda fn: fn.startswith('magic_') and \
151 inst_magic = lambda fn: fn.startswith('magic_') and \
149 callable(self.__dict__[fn])
152 callable(self.__dict__[fn])
150 # and bound magics by user (so they can access self):
153 # and bound magics by user (so they can access self):
151 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
154 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
152 callable(self.__class__.__dict__[fn])
155 callable(self.__class__.__dict__[fn])
153 magics = filter(class_magic,Magic.__dict__.keys()) + \
156 magics = filter(class_magic,Magic.__dict__.keys()) + \
154 filter(inst_magic,self.__dict__.keys()) + \
157 filter(inst_magic,self.__dict__.keys()) + \
155 filter(inst_bound_magic,self.__class__.__dict__.keys())
158 filter(inst_bound_magic,self.__class__.__dict__.keys())
156 out = []
159 out = []
157 for fn in magics:
160 for fn in magics:
158 out.append(fn.replace('magic_','',1))
161 out.append(fn.replace('magic_','',1))
159 out.sort()
162 out.sort()
160 return out
163 return out
161
164
162 def set_shell(self,shell):
165 def set_shell(self,shell):
163 self.shell = shell
166 self.shell = shell
164 self.alias_table = shell.alias_table
167 self.alias_table = shell.alias_table
165
168
166 def extract_input_slices(self,slices):
169 def extract_input_slices(self,slices):
167 """Return as a string a set of input history slices.
170 """Return as a string a set of input history slices.
168
171
169 The set of slices is given as a list of strings (like ['1','4:8','9'],
172 The set of slices is given as a list of strings (like ['1','4:8','9'],
170 since this function is for use by magic functions which get their
173 since this function is for use by magic functions which get their
171 arguments as strings."""
174 arguments as strings."""
172
175
173 cmds = []
176 cmds = []
174 for chunk in slices:
177 for chunk in slices:
175 if ':' in chunk:
178 if ':' in chunk:
176 ini,fin = map(int,chunk.split(':'))
179 ini,fin = map(int,chunk.split(':'))
177 else:
180 else:
178 ini = int(chunk)
181 ini = int(chunk)
179 fin = ini+1
182 fin = ini+1
180 cmds.append(self.shell.input_hist[ini:fin])
183 cmds.append(self.shell.input_hist[ini:fin])
181 return cmds
184 return cmds
182
185
183 def _ofind(self,oname):
186 def _ofind(self,oname):
184 """Find an object in the available namespaces.
187 """Find an object in the available namespaces.
185
188
186 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
189 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
187
190
188 Has special code to detect magic functions.
191 Has special code to detect magic functions.
189 """
192 """
190
193
191 oname = oname.strip()
194 oname = oname.strip()
192
195
193 # Namespaces to search in:
196 # Namespaces to search in:
194 user_ns = self.shell.user_ns
197 user_ns = self.shell.user_ns
195 internal_ns = self.shell.internal_ns
198 internal_ns = self.shell.internal_ns
196 builtin_ns = __builtin__.__dict__
199 builtin_ns = __builtin__.__dict__
197 alias_ns = self.shell.alias_table
200 alias_ns = self.shell.alias_table
198
201
199 # Put them in a list. The order is important so that we find things in
202 # Put them in a list. The order is important so that we find things in
200 # the same order that Python finds them.
203 # the same order that Python finds them.
201 namespaces = [ ('Interactive',user_ns),
204 namespaces = [ ('Interactive',user_ns),
202 ('IPython internal',internal_ns),
205 ('IPython internal',internal_ns),
203 ('Python builtin',builtin_ns),
206 ('Python builtin',builtin_ns),
204 ('Alias',alias_ns),
207 ('Alias',alias_ns),
205 ]
208 ]
206
209
207 # initialize results to 'null'
210 # initialize results to 'null'
208 found = 0; obj = None; ospace = None; ds = None;
211 found = 0; obj = None; ospace = None; ds = None;
209 ismagic = 0; isalias = 0
212 ismagic = 0; isalias = 0
210
213
211 # Look for the given name by splitting it in parts. If the head is
214 # Look for the given name by splitting it in parts. If the head is
212 # found, then we look for all the remaining parts as members, and only
215 # found, then we look for all the remaining parts as members, and only
213 # declare success if we can find them all.
216 # declare success if we can find them all.
214 oname_parts = oname.split('.')
217 oname_parts = oname.split('.')
215 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
218 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
216 for nsname,ns in namespaces:
219 for nsname,ns in namespaces:
217 try:
220 try:
218 obj = ns[oname_head]
221 obj = ns[oname_head]
219 except KeyError:
222 except KeyError:
220 continue
223 continue
221 else:
224 else:
222 for part in oname_rest:
225 for part in oname_rest:
223 try:
226 try:
224 obj = getattr(obj,part)
227 obj = getattr(obj,part)
225 except:
228 except:
226 # Blanket except b/c some badly implemented objects
229 # Blanket except b/c some badly implemented objects
227 # allow __getattr__ to raise exceptions other than
230 # allow __getattr__ to raise exceptions other than
228 # AttributeError, which then crashes IPython.
231 # AttributeError, which then crashes IPython.
229 break
232 break
230 else:
233 else:
231 # If we finish the for loop (no break), we got all members
234 # If we finish the for loop (no break), we got all members
232 found = 1
235 found = 1
233 ospace = nsname
236 ospace = nsname
234 if ns == alias_ns:
237 if ns == alias_ns:
235 isalias = 1
238 isalias = 1
236 break # namespace loop
239 break # namespace loop
237
240
238 # Try to see if it's magic
241 # Try to see if it's magic
239 if not found:
242 if not found:
240 if oname.startswith(self.shell.ESC_MAGIC):
243 if oname.startswith(self.shell.ESC_MAGIC):
241 oname = oname[1:]
244 oname = oname[1:]
242 obj = getattr(self,'magic_'+oname,None)
245 obj = getattr(self,'magic_'+oname,None)
243 if obj is not None:
246 if obj is not None:
244 found = 1
247 found = 1
245 ospace = 'IPython internal'
248 ospace = 'IPython internal'
246 ismagic = 1
249 ismagic = 1
247
250
248 # Last try: special-case some literals like '', [], {}, etc:
251 # Last try: special-case some literals like '', [], {}, etc:
249 if not found and oname_head in ["''",'""','[]','{}','()']:
252 if not found and oname_head in ["''",'""','[]','{}','()']:
250 obj = eval(oname_head)
253 obj = eval(oname_head)
251 found = 1
254 found = 1
252 ospace = 'Interactive'
255 ospace = 'Interactive'
253
256
254 return {'found':found, 'obj':obj, 'namespace':ospace,
257 return {'found':found, 'obj':obj, 'namespace':ospace,
255 'ismagic':ismagic, 'isalias':isalias}
258 'ismagic':ismagic, 'isalias':isalias}
256
259
257 def arg_err(self,func):
260 def arg_err(self,func):
258 """Print docstring if incorrect arguments were passed"""
261 """Print docstring if incorrect arguments were passed"""
259 print 'Error in arguments:'
262 print 'Error in arguments:'
260 print OInspect.getdoc(func)
263 print OInspect.getdoc(func)
261
264
262
265
263 def format_latex(self,str):
266 def format_latex(self,str):
264 """Format a string for latex inclusion."""
267 """Format a string for latex inclusion."""
265
268
266 # Characters that need to be escaped for latex:
269 # Characters that need to be escaped for latex:
267 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
270 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
268 # Magic command names as headers:
271 # Magic command names as headers:
269 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
272 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
270 re.MULTILINE)
273 re.MULTILINE)
271 # Magic commands
274 # Magic commands
272 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
275 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
273 re.MULTILINE)
276 re.MULTILINE)
274 # Paragraph continue
277 # Paragraph continue
275 par_re = re.compile(r'\\$',re.MULTILINE)
278 par_re = re.compile(r'\\$',re.MULTILINE)
276
279
277 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
280 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
278 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
281 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
279 str = par_re.sub(r'\\\\',str)
282 str = par_re.sub(r'\\\\',str)
280 str = escape_re.sub(r'\\\1',str)
283 str = escape_re.sub(r'\\\1',str)
281 return str
284 return str
282
285
283 def format_screen(self,str):
286 def format_screen(self,str):
284 """Format a string for screen printing.
287 """Format a string for screen printing.
285
288
286 This removes some latex-type format codes."""
289 This removes some latex-type format codes."""
287 # Paragraph continue
290 # Paragraph continue
288 par_re = re.compile(r'\\$',re.MULTILINE)
291 par_re = re.compile(r'\\$',re.MULTILINE)
289 str = par_re.sub('',str)
292 str = par_re.sub('',str)
290 return str
293 return str
291
294
292 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
295 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
293 """Parse options passed to an argument string.
296 """Parse options passed to an argument string.
294
297
295 The interface is similar to that of getopt(), but it returns back a
298 The interface is similar to that of getopt(), but it returns back a
296 Struct with the options as keys and the stripped argument string still
299 Struct with the options as keys and the stripped argument string still
297 as a string.
300 as a string.
298
301
299 arg_str is quoted as a true sys.argv vector by using shlex.split.
302 arg_str is quoted as a true sys.argv vector by using shlex.split.
300 This allows us to easily expand variables, glob files, quote
303 This allows us to easily expand variables, glob files, quote
301 arguments, etc.
304 arguments, etc.
302
305
303 Options:
306 Options:
304 -mode: default 'string'. If given as 'list', the argument string is
307 -mode: default 'string'. If given as 'list', the argument string is
305 returned as a list (split on whitespace) instead of a string.
308 returned as a list (split on whitespace) instead of a string.
306
309
307 -list_all: put all option values in lists. Normally only options
310 -list_all: put all option values in lists. Normally only options
308 appearing more than once are put in a list."""
311 appearing more than once are put in a list."""
309
312
310 # inject default options at the beginning of the input line
313 # inject default options at the beginning of the input line
311 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
314 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
312 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
315 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
313
316
314 mode = kw.get('mode','string')
317 mode = kw.get('mode','string')
315 if mode not in ['string','list']:
318 if mode not in ['string','list']:
316 raise ValueError,'incorrect mode given: %s' % mode
319 raise ValueError,'incorrect mode given: %s' % mode
317 # Get options
320 # Get options
318 list_all = kw.get('list_all',0)
321 list_all = kw.get('list_all',0)
319
322
320 # Check if we have more than one argument to warrant extra processing:
323 # Check if we have more than one argument to warrant extra processing:
321 odict = {} # Dictionary with options
324 odict = {} # Dictionary with options
322 args = arg_str.split()
325 args = arg_str.split()
323 if len(args) >= 1:
326 if len(args) >= 1:
324 # If the list of inputs only has 0 or 1 thing in it, there's no
327 # If the list of inputs only has 0 or 1 thing in it, there's no
325 # need to look for options
328 # need to look for options
326 argv = shlex_split(arg_str)
329 argv = shlex_split(arg_str)
327 # Do regular option processing
330 # Do regular option processing
328 opts,args = getopt(argv,opt_str,*long_opts)
331 opts,args = getopt(argv,opt_str,*long_opts)
329 for o,a in opts:
332 for o,a in opts:
330 if o.startswith('--'):
333 if o.startswith('--'):
331 o = o[2:]
334 o = o[2:]
332 else:
335 else:
333 o = o[1:]
336 o = o[1:]
334 try:
337 try:
335 odict[o].append(a)
338 odict[o].append(a)
336 except AttributeError:
339 except AttributeError:
337 odict[o] = [odict[o],a]
340 odict[o] = [odict[o],a]
338 except KeyError:
341 except KeyError:
339 if list_all:
342 if list_all:
340 odict[o] = [a]
343 odict[o] = [a]
341 else:
344 else:
342 odict[o] = a
345 odict[o] = a
343
346
344 # Prepare opts,args for return
347 # Prepare opts,args for return
345 opts = Struct(odict)
348 opts = Struct(odict)
346 if mode == 'string':
349 if mode == 'string':
347 args = ' '.join(args)
350 args = ' '.join(args)
348
351
349 return opts,args
352 return opts,args
350
353
351 #......................................................................
354 #......................................................................
352 # And now the actual magic functions
355 # And now the actual magic functions
353
356
354 # Functions for IPython shell work (vars,funcs, config, etc)
357 # Functions for IPython shell work (vars,funcs, config, etc)
355 def magic_lsmagic(self, parameter_s = ''):
358 def magic_lsmagic(self, parameter_s = ''):
356 """List currently available magic functions."""
359 """List currently available magic functions."""
357 mesc = self.shell.ESC_MAGIC
360 mesc = self.shell.ESC_MAGIC
358 print 'Available magic functions:\n'+mesc+\
361 print 'Available magic functions:\n'+mesc+\
359 (' '+mesc).join(self.lsmagic())
362 (' '+mesc).join(self.lsmagic())
360 print '\n' + Magic.auto_status[self.shell.rc.automagic]
363 print '\n' + Magic.auto_status[self.shell.rc.automagic]
361 return None
364 return None
362
365
363 def magic_magic(self, parameter_s = ''):
366 def magic_magic(self, parameter_s = ''):
364 """Print information about the magic function system."""
367 """Print information about the magic function system."""
365
368
366 mode = ''
369 mode = ''
367 try:
370 try:
368 if parameter_s.split()[0] == '-latex':
371 if parameter_s.split()[0] == '-latex':
369 mode = 'latex'
372 mode = 'latex'
370 except:
373 except:
371 pass
374 pass
372
375
373 magic_docs = []
376 magic_docs = []
374 for fname in self.lsmagic():
377 for fname in self.lsmagic():
375 mname = 'magic_' + fname
378 mname = 'magic_' + fname
376 for space in (Magic,self,self.__class__):
379 for space in (Magic,self,self.__class__):
377 try:
380 try:
378 fn = space.__dict__[mname]
381 fn = space.__dict__[mname]
379 except KeyError:
382 except KeyError:
380 pass
383 pass
381 else:
384 else:
382 break
385 break
383 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
386 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
384 fname,fn.__doc__))
387 fname,fn.__doc__))
385 magic_docs = ''.join(magic_docs)
388 magic_docs = ''.join(magic_docs)
386
389
387 if mode == 'latex':
390 if mode == 'latex':
388 print self.format_latex(magic_docs)
391 print self.format_latex(magic_docs)
389 return
392 return
390 else:
393 else:
391 magic_docs = self.format_screen(magic_docs)
394 magic_docs = self.format_screen(magic_docs)
392
395
393 outmsg = """
396 outmsg = """
394 IPython's 'magic' functions
397 IPython's 'magic' functions
395 ===========================
398 ===========================
396
399
397 The magic function system provides a series of functions which allow you to
400 The magic function system provides a series of functions which allow you to
398 control the behavior of IPython itself, plus a lot of system-type
401 control the behavior of IPython itself, plus a lot of system-type
399 features. All these functions are prefixed with a % character, but parameters
402 features. All these functions are prefixed with a % character, but parameters
400 are given without parentheses or quotes.
403 are given without parentheses or quotes.
401
404
402 NOTE: If you have 'automagic' enabled (via the command line option or with the
405 NOTE: If you have 'automagic' enabled (via the command line option or with the
403 %automagic function), you don't need to type in the % explicitly. By default,
406 %automagic function), you don't need to type in the % explicitly. By default,
404 IPython ships with automagic on, so you should only rarely need the % escape.
407 IPython ships with automagic on, so you should only rarely need the % escape.
405
408
406 Example: typing '%cd mydir' (without the quotes) changes you working directory
409 Example: typing '%cd mydir' (without the quotes) changes you working directory
407 to 'mydir', if it exists.
410 to 'mydir', if it exists.
408
411
409 You can define your own magic functions to extend the system. See the supplied
412 You can define your own magic functions to extend the system. See the supplied
410 ipythonrc and example-magic.py files for details (in your ipython
413 ipythonrc and example-magic.py files for details (in your ipython
411 configuration directory, typically $HOME/.ipython/).
414 configuration directory, typically $HOME/.ipython/).
412
415
413 You can also define your own aliased names for magic functions. In your
416 You can also define your own aliased names for magic functions. In your
414 ipythonrc file, placing a line like:
417 ipythonrc file, placing a line like:
415
418
416 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
419 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
417
420
418 will define %pf as a new name for %profile.
421 will define %pf as a new name for %profile.
419
422
420 You can also call magics in code using the ipmagic() function, which IPython
423 You can also call magics in code using the ipmagic() function, which IPython
421 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
424 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
422
425
423 For a list of the available magic functions, use %lsmagic. For a description
426 For a list of the available magic functions, use %lsmagic. For a description
424 of any of them, type %magic_name?, e.g. '%cd?'.
427 of any of them, type %magic_name?, e.g. '%cd?'.
425
428
426 Currently the magic system has the following functions:\n"""
429 Currently the magic system has the following functions:\n"""
427
430
428 mesc = self.shell.ESC_MAGIC
431 mesc = self.shell.ESC_MAGIC
429 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
432 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
430 "\n\n%s%s\n\n%s" % (outmsg,
433 "\n\n%s%s\n\n%s" % (outmsg,
431 magic_docs,mesc,mesc,
434 magic_docs,mesc,mesc,
432 (' '+mesc).join(self.lsmagic()),
435 (' '+mesc).join(self.lsmagic()),
433 Magic.auto_status[self.shell.rc.automagic] ) )
436 Magic.auto_status[self.shell.rc.automagic] ) )
434
437
435 page(outmsg,screen_lines=self.shell.rc.screen_length)
438 page(outmsg,screen_lines=self.shell.rc.screen_length)
436
439
437 def magic_automagic(self, parameter_s = ''):
440 def magic_automagic(self, parameter_s = ''):
438 """Make magic functions callable without having to type the initial %.
441 """Make magic functions callable without having to type the initial %.
439
442
440 Toggles on/off (when off, you must call it as %automagic, of
443 Toggles on/off (when off, you must call it as %automagic, of
441 course). Note that magic functions have lowest priority, so if there's
444 course). Note that magic functions have lowest priority, so if there's
442 a variable whose name collides with that of a magic fn, automagic
445 a variable whose name collides with that of a magic fn, automagic
443 won't work for that function (you get the variable instead). However,
446 won't work for that function (you get the variable instead). However,
444 if you delete the variable (del var), the previously shadowed magic
447 if you delete the variable (del var), the previously shadowed magic
445 function becomes visible to automagic again."""
448 function becomes visible to automagic again."""
446
449
447 rc = self.shell.rc
450 rc = self.shell.rc
448 rc.automagic = not rc.automagic
451 rc.automagic = not rc.automagic
449 print '\n' + Magic.auto_status[rc.automagic]
452 print '\n' + Magic.auto_status[rc.automagic]
450
453
451 def magic_autocall(self, parameter_s = ''):
454 def magic_autocall(self, parameter_s = ''):
452 """Make functions callable without having to type parentheses.
455 """Make functions callable without having to type parentheses.
453
456
454 This toggles the autocall command line option on and off."""
457 This toggles the autocall command line option on and off."""
455
458
456 rc = self.shell.rc
459 rc = self.shell.rc
457 rc.autocall = not rc.autocall
460 rc.autocall = not rc.autocall
458 print "Automatic calling is:",['OFF','ON'][rc.autocall]
461 print "Automatic calling is:",['OFF','ON'][rc.autocall]
459
462
460 def magic_autoindent(self, parameter_s = ''):
463 def magic_autoindent(self, parameter_s = ''):
461 """Toggle autoindent on/off (if available)."""
464 """Toggle autoindent on/off (if available)."""
462
465
463 self.shell.set_autoindent()
466 self.shell.set_autoindent()
464 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
467 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
465
468
466 def magic_system_verbose(self, parameter_s = ''):
469 def magic_system_verbose(self, parameter_s = ''):
467 """Toggle verbose printing of system calls on/off."""
470 """Toggle verbose printing of system calls on/off."""
468
471
469 self.shell.rc_set_toggle('system_verbose')
472 self.shell.rc_set_toggle('system_verbose')
470 print "System verbose printing is:",\
473 print "System verbose printing is:",\
471 ['OFF','ON'][self.shell.rc.system_verbose]
474 ['OFF','ON'][self.shell.rc.system_verbose]
472
475
473 def magic_history(self, parameter_s = ''):
476 def magic_history(self, parameter_s = ''):
474 """Print input history (_i<n> variables), with most recent last.
477 """Print input history (_i<n> variables), with most recent last.
475
478
476 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
479 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
477 %history [-n] n -> print at most n inputs\\
480 %history [-n] n -> print at most n inputs\\
478 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
481 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
479
482
480 Each input's number <n> is shown, and is accessible as the
483 Each input's number <n> is shown, and is accessible as the
481 automatically generated variable _i<n>. Multi-line statements are
484 automatically generated variable _i<n>. Multi-line statements are
482 printed starting at a new line for easy copy/paste.
485 printed starting at a new line for easy copy/paste.
483
486
484 If option -n is used, input numbers are not printed. This is useful if
487 If option -n is used, input numbers are not printed. This is useful if
485 you want to get a printout of many lines which can be directly pasted
488 you want to get a printout of many lines which can be directly pasted
486 into a text editor.
489 into a text editor.
487
490
488 This feature is only available if numbered prompts are in use."""
491 This feature is only available if numbered prompts are in use."""
489
492
490 if not self.do_full_cache:
493 if not self.do_full_cache:
491 print 'This feature is only available if numbered prompts are in use.'
494 print 'This feature is only available if numbered prompts are in use.'
492 return
495 return
493 opts,args = self.parse_options(parameter_s,'n',mode='list')
496 opts,args = self.parse_options(parameter_s,'n',mode='list')
494
497
495 default_length = 40
498 default_length = 40
496 if len(args) == 0:
499 if len(args) == 0:
497 final = self.outputcache.prompt_count
500 final = self.outputcache.prompt_count
498 init = max(1,final-default_length)
501 init = max(1,final-default_length)
499 elif len(args) == 1:
502 elif len(args) == 1:
500 final = self.outputcache.prompt_count
503 final = self.outputcache.prompt_count
501 init = max(1,final-int(args[0]))
504 init = max(1,final-int(args[0]))
502 elif len(args) == 2:
505 elif len(args) == 2:
503 init,final = map(int,args)
506 init,final = map(int,args)
504 else:
507 else:
505 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
508 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
506 print self.magic_hist.__doc__
509 print self.magic_hist.__doc__
507 return
510 return
508 width = len(str(final))
511 width = len(str(final))
509 line_sep = ['','\n']
512 line_sep = ['','\n']
510 input_hist = self.shell.input_hist
513 input_hist = self.shell.input_hist
511 print_nums = not opts.has_key('n')
514 print_nums = not opts.has_key('n')
512 for in_num in range(init,final):
515 for in_num in range(init,final):
513 inline = input_hist[in_num]
516 inline = input_hist[in_num]
514 multiline = inline.count('\n') > 1
517 multiline = inline.count('\n') > 1
515 if print_nums:
518 if print_nums:
516 print str(in_num).ljust(width)+':'+ line_sep[multiline],
519 print str(in_num).ljust(width)+':'+ line_sep[multiline],
517 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
520 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
518 inline.startswith('#!'):
521 inline.startswith('#!'):
519 print inline[1:],
522 print inline[1:],
520 else:
523 else:
521 print inline,
524 print inline,
522
525
523 def magic_hist(self, parameter_s=''):
526 def magic_hist(self, parameter_s=''):
524 """Alternate name for %history."""
527 """Alternate name for %history."""
525 return self.magic_history(parameter_s)
528 return self.magic_history(parameter_s)
526
529
527 def magic_p(self, parameter_s=''):
530 def magic_p(self, parameter_s=''):
528 """Just a short alias for Python's 'print'."""
531 """Just a short alias for Python's 'print'."""
529 exec 'print ' + parameter_s in self.shell.user_ns
532 exec 'print ' + parameter_s in self.shell.user_ns
530
533
531 def magic_r(self, parameter_s=''):
534 def magic_r(self, parameter_s=''):
532 """Repeat previous input.
535 """Repeat previous input.
533
536
534 If given an argument, repeats the previous command which starts with
537 If given an argument, repeats the previous command which starts with
535 the same string, otherwise it just repeats the previous input.
538 the same string, otherwise it just repeats the previous input.
536
539
537 Shell escaped commands (with ! as first character) are not recognized
540 Shell escaped commands (with ! as first character) are not recognized
538 by this system, only pure python code and magic commands.
541 by this system, only pure python code and magic commands.
539 """
542 """
540
543
541 start = parameter_s.strip()
544 start = parameter_s.strip()
542 esc_magic = self.shell.ESC_MAGIC
545 esc_magic = self.shell.ESC_MAGIC
543 # Identify magic commands even if automagic is on (which means
546 # Identify magic commands even if automagic is on (which means
544 # the in-memory version is different from that typed by the user).
547 # the in-memory version is different from that typed by the user).
545 if self.shell.rc.automagic:
548 if self.shell.rc.automagic:
546 start_magic = esc_magic+start
549 start_magic = esc_magic+start
547 else:
550 else:
548 start_magic = start
551 start_magic = start
549 # Look through the input history in reverse
552 # Look through the input history in reverse
550 for n in range(len(self.shell.input_hist)-2,0,-1):
553 for n in range(len(self.shell.input_hist)-2,0,-1):
551 input = self.shell.input_hist[n]
554 input = self.shell.input_hist[n]
552 # skip plain 'r' lines so we don't recurse to infinity
555 # skip plain 'r' lines so we don't recurse to infinity
553 if input != 'ipmagic("r")\n' and \
556 if input != 'ipmagic("r")\n' and \
554 (input.startswith(start) or input.startswith(start_magic)):
557 (input.startswith(start) or input.startswith(start_magic)):
555 #print 'match',`input` # dbg
558 #print 'match',`input` # dbg
556 if input.startswith(esc_magic):
559 if input.startswith(esc_magic):
557 input = magic2python(input)
560 input = magic2python(input)
558 #print 'modified',`input` # dbg
561 #print 'modified',`input` # dbg
559 print 'Executing:',input,
562 print 'Executing:',input,
560 exec input in self.shell.user_ns
563 exec input in self.shell.user_ns
561 return
564 return
562 print 'No previous input matching `%s` found.' % start
565 print 'No previous input matching `%s` found.' % start
563
566
564 def magic_page(self, parameter_s=''):
567 def magic_page(self, parameter_s=''):
565 """Pretty print the object and display it through a pager.
568 """Pretty print the object and display it through a pager.
566
569
567 If no parameter is given, use _ (last output)."""
570 If no parameter is given, use _ (last output)."""
568 # After a function contributed by Olivier Aubert, slightly modified.
571 # After a function contributed by Olivier Aubert, slightly modified.
569
572
570 oname = parameter_s and parameter_s or '_'
573 oname = parameter_s and parameter_s or '_'
571 info = self._ofind(oname)
574 info = self._ofind(oname)
572 if info['found']:
575 if info['found']:
573 page(pformat(info['obj']))
576 page(pformat(info['obj']))
574 else:
577 else:
575 print 'Object `%s` not found' % oname
578 print 'Object `%s` not found' % oname
576
579
577 def magic_profile(self, parameter_s=''):
580 def magic_profile(self, parameter_s=''):
578 """Print your currently active IPyhton profile."""
581 """Print your currently active IPyhton profile."""
579 if self.shell.rc.profile:
582 if self.shell.rc.profile:
580 printpl('Current IPython profile: $self.shell.rc.profile.')
583 printpl('Current IPython profile: $self.shell.rc.profile.')
581 else:
584 else:
582 print 'No profile active.'
585 print 'No profile active.'
583
586
584 def _inspect(self,meth,oname,**kw):
587 def _inspect(self,meth,oname,**kw):
585 """Generic interface to the inspector system.
588 """Generic interface to the inspector system.
586
589
587 This function is meant to be called by pdef, pdoc & friends."""
590 This function is meant to be called by pdef, pdoc & friends."""
588
591
589 oname = oname.strip()
592 oname = oname.strip()
590 info = Struct(self._ofind(oname))
593 info = Struct(self._ofind(oname))
591 if info.found:
594 if info.found:
592 pmethod = getattr(self.shell.inspector,meth)
595 pmethod = getattr(self.shell.inspector,meth)
593 formatter = info.ismagic and self.format_screen or None
596 formatter = info.ismagic and self.format_screen or None
594 if meth == 'pdoc':
597 if meth == 'pdoc':
595 pmethod(info.obj,oname,formatter)
598 pmethod(info.obj,oname,formatter)
596 elif meth == 'pinfo':
599 elif meth == 'pinfo':
597 pmethod(info.obj,oname,formatter,info,**kw)
600 pmethod(info.obj,oname,formatter,info,**kw)
598 else:
601 else:
599 pmethod(info.obj,oname)
602 pmethod(info.obj,oname)
600 else:
603 else:
601 print 'Object `%s` not found.' % oname
604 print 'Object `%s` not found.' % oname
602 return 'not found' # so callers can take other action
605 return 'not found' # so callers can take other action
603
606
604 def magic_pdef(self, parameter_s=''):
607 def magic_pdef(self, parameter_s=''):
605 """Print the definition header for any callable object.
608 """Print the definition header for any callable object.
606
609
607 If the object is a class, print the constructor information."""
610 If the object is a class, print the constructor information."""
608 self._inspect('pdef',parameter_s)
611 self._inspect('pdef',parameter_s)
609
612
610 def magic_pdoc(self, parameter_s=''):
613 def magic_pdoc(self, parameter_s=''):
611 """Print the docstring for an object.
614 """Print the docstring for an object.
612
615
613 If the given object is a class, it will print both the class and the
616 If the given object is a class, it will print both the class and the
614 constructor docstrings."""
617 constructor docstrings."""
615 self._inspect('pdoc',parameter_s)
618 self._inspect('pdoc',parameter_s)
616
619
617 def magic_psource(self, parameter_s=''):
620 def magic_psource(self, parameter_s=''):
618 """Print (or run through pager) the source code for an object."""
621 """Print (or run through pager) the source code for an object."""
619 self._inspect('psource',parameter_s)
622 self._inspect('psource',parameter_s)
620
623
621 def magic_pfile(self, parameter_s=''):
624 def magic_pfile(self, parameter_s=''):
622 """Print (or run through pager) the file where an object is defined.
625 """Print (or run through pager) the file where an object is defined.
623
626
624 The file opens at the line where the object definition begins. IPython
627 The file opens at the line where the object definition begins. IPython
625 will honor the environment variable PAGER if set, and otherwise will
628 will honor the environment variable PAGER if set, and otherwise will
626 do its best to print the file in a convenient form.
629 do its best to print the file in a convenient form.
627
630
628 If the given argument is not an object currently defined, IPython will
631 If the given argument is not an object currently defined, IPython will
629 try to interpret it as a filename (automatically adding a .py extension
632 try to interpret it as a filename (automatically adding a .py extension
630 if needed). You can thus use %pfile as a syntax highlighting code
633 if needed). You can thus use %pfile as a syntax highlighting code
631 viewer."""
634 viewer."""
632
635
633 # first interpret argument as an object name
636 # first interpret argument as an object name
634 out = self._inspect('pfile',parameter_s)
637 out = self._inspect('pfile',parameter_s)
635 # if not, try the input as a filename
638 # if not, try the input as a filename
636 if out == 'not found':
639 if out == 'not found':
637 try:
640 try:
638 filename = get_py_filename(parameter_s)
641 filename = get_py_filename(parameter_s)
639 except IOError,msg:
642 except IOError,msg:
640 print msg
643 print msg
641 return
644 return
642 page(self.shell.inspector.format(file(filename).read()))
645 page(self.shell.inspector.format(file(filename).read()))
643
646
644 def magic_pinfo(self, parameter_s=''):
647 def magic_pinfo(self, parameter_s=''):
645 """Provide detailed information about an object.
648 """Provide detailed information about an object.
646
649
647 '%pinfo object' is just a synonym for object? or ?object."""
650 '%pinfo object' is just a synonym for object? or ?object."""
648
651
649 #print 'pinfo par: <%s>' % parameter_s # dbg
652 #print 'pinfo par: <%s>' % parameter_s # dbg
650
653
651 # detail_level: 0 -> obj? , 1 -> obj??
654 # detail_level: 0 -> obj? , 1 -> obj??
652 detail_level = 0
655 detail_level = 0
653 # We need to detect if we got called as 'pinfo pinfo foo', which can
656 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 # happen if the user types 'pinfo foo?' at the cmd line.
657 # happen if the user types 'pinfo foo?' at the cmd line.
655 pinfo,qmark1,oname,qmark2 = \
658 pinfo,qmark1,oname,qmark2 = \
656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
659 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 if pinfo or qmark1 or qmark2:
660 if pinfo or qmark1 or qmark2:
658 detail_level = 1
661 detail_level = 1
659 if "*" in oname:
662 if "*" in oname:
660 self.magic_psearch(oname)
663 self.magic_psearch(oname)
661 else:
664 else:
662 self._inspect('pinfo',oname,detail_level=detail_level)
665 self._inspect('pinfo',oname,detail_level=detail_level)
663
666
664 def magic_psearch(self, parameter_s=''):
667 def magic_psearch(self, parameter_s=''):
665 """Search for object in namespaces by wildcard.
668 """Search for object in namespaces by wildcard.
666
669
667 %psearch [options] PATTERN [OBJECT TYPE]
670 %psearch [options] PATTERN [OBJECT TYPE]
668
671
669 Note: ? can be used as a synonym for %psearch, at the beginning or at
672 Note: ? can be used as a synonym for %psearch, at the beginning or at
670 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
673 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
671 rest of the command line must be unchanged (options come first), so
674 rest of the command line must be unchanged (options come first), so
672 for example the following forms are equivalent
675 for example the following forms are equivalent
673
676
674 %psearch -i a* function
677 %psearch -i a* function
675 -i a* function?
678 -i a* function?
676 ?-i a* function
679 ?-i a* function
677
680
678 Arguments:
681 Arguments:
679
682
680 PATTERN
683 PATTERN
681
684
682 where PATTERN is a string containing * as a wildcard similar to its
685 where PATTERN is a string containing * as a wildcard similar to its
683 use in a shell. The pattern is matched in all namespaces on the
686 use in a shell. The pattern is matched in all namespaces on the
684 search path. By default objects starting with a single _ are not
687 search path. By default objects starting with a single _ are not
685 matched, many IPython generated objects have a single
688 matched, many IPython generated objects have a single
686 underscore. The default is case insensitive matching. Matching is
689 underscore. The default is case insensitive matching. Matching is
687 also done on the attributes of objects and not only on the objects
690 also done on the attributes of objects and not only on the objects
688 in a module.
691 in a module.
689
692
690 [OBJECT TYPE]
693 [OBJECT TYPE]
691
694
692 Is the name of a python type from the types module. The name is
695 Is the name of a python type from the types module. The name is
693 given in lowercase without the ending type, ex. StringType is
696 given in lowercase without the ending type, ex. StringType is
694 written string. By adding a type here only objects matching the
697 written string. By adding a type here only objects matching the
695 given type are matched. Using all here makes the pattern match all
698 given type are matched. Using all here makes the pattern match all
696 types (this is the default).
699 types (this is the default).
697
700
698 Options:
701 Options:
699
702
700 -a: makes the pattern match even objects whose names start with a
703 -a: makes the pattern match even objects whose names start with a
701 single underscore. These names are normally ommitted from the
704 single underscore. These names are normally ommitted from the
702 search.
705 search.
703
706
704 -i/-c: make the pattern case insensitive/sensitive. If neither of
707 -i/-c: make the pattern case insensitive/sensitive. If neither of
705 these options is given, the default is read from your ipythonrc
708 these options is given, the default is read from your ipythonrc
706 file. The option name which sets this value is
709 file. The option name which sets this value is
707 'wildcards_case_sensitive'. If this option is not specified in your
710 'wildcards_case_sensitive'. If this option is not specified in your
708 ipythonrc file, IPython's internal default is to do a case sensitive
711 ipythonrc file, IPython's internal default is to do a case sensitive
709 search.
712 search.
710
713
711 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
714 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
712 specifiy can be searched in any of the following namespaces:
715 specifiy can be searched in any of the following namespaces:
713 'builtin', 'user', 'user_global','internal', 'alias', where
716 'builtin', 'user', 'user_global','internal', 'alias', where
714 'builtin' and 'user' are the search defaults. Note that you should
717 'builtin' and 'user' are the search defaults. Note that you should
715 not use quotes when specifying namespaces.
718 not use quotes when specifying namespaces.
716
719
717 'Builtin' contains the python module builtin, 'user' contains all
720 'Builtin' contains the python module builtin, 'user' contains all
718 user data, 'alias' only contain the shell aliases and no python
721 user data, 'alias' only contain the shell aliases and no python
719 objects, 'internal' contains objects used by IPython. The
722 objects, 'internal' contains objects used by IPython. The
720 'user_global' namespace is only used by embedded IPython instances,
723 'user_global' namespace is only used by embedded IPython instances,
721 and it contains module-level globals. You can add namespaces to the
724 and it contains module-level globals. You can add namespaces to the
722 search with -s or exclude them with -e (these options can be given
725 search with -s or exclude them with -e (these options can be given
723 more than once).
726 more than once).
724
727
725 Examples:
728 Examples:
726
729
727 %psearch a* -> objects beginning with an a
730 %psearch a* -> objects beginning with an a
728 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
731 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
729 %psearch a* function -> all functions beginning with an a
732 %psearch a* function -> all functions beginning with an a
730 %psearch re.e* -> objects beginning with an e in module re
733 %psearch re.e* -> objects beginning with an e in module re
731 %psearch r*.e* -> objects that start with e in modules starting in r
734 %psearch r*.e* -> objects that start with e in modules starting in r
732 %psearch r*.* string -> all strings in modules beginning with r
735 %psearch r*.* string -> all strings in modules beginning with r
733
736
734 Case sensitve search:
737 Case sensitve search:
735
738
736 %psearch -c a* list all object beginning with lower case a
739 %psearch -c a* list all object beginning with lower case a
737
740
738 Show objects beginning with a single _:
741 Show objects beginning with a single _:
739
742
740 %psearch -a _* list objects beginning with a single underscore"""
743 %psearch -a _* list objects beginning with a single underscore"""
741
744
742 # default namespaces to be searched
745 # default namespaces to be searched
743 def_search = ['user','builtin']
746 def_search = ['user','builtin']
744
747
745 # Process options/args
748 # Process options/args
746 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
749 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
747 opt = opts.get
750 opt = opts.get
748 shell = self.shell
751 shell = self.shell
749 psearch = shell.inspector.psearch
752 psearch = shell.inspector.psearch
750
753
751 # select case options
754 # select case options
752 if opts.has_key('i'):
755 if opts.has_key('i'):
753 ignore_case = True
756 ignore_case = True
754 elif opts.has_key('c'):
757 elif opts.has_key('c'):
755 ignore_case = False
758 ignore_case = False
756 else:
759 else:
757 ignore_case = not shell.rc.wildcards_case_sensitive
760 ignore_case = not shell.rc.wildcards_case_sensitive
758
761
759 # Build list of namespaces to search from user options
762 # Build list of namespaces to search from user options
760 def_search.extend(opt('s',[]))
763 def_search.extend(opt('s',[]))
761 ns_exclude = ns_exclude=opt('e',[])
764 ns_exclude = ns_exclude=opt('e',[])
762 ns_search = [nm for nm in def_search if nm not in ns_exclude]
765 ns_search = [nm for nm in def_search if nm not in ns_exclude]
763
766
764 # Call the actual search
767 # Call the actual search
765 try:
768 try:
766 psearch(args,shell.ns_table,ns_search,
769 psearch(args,shell.ns_table,ns_search,
767 show_all=opt('a'),ignore_case=ignore_case)
770 show_all=opt('a'),ignore_case=ignore_case)
768 except:
771 except:
769 shell.showtraceback()
772 shell.showtraceback()
770
773
771 def magic_who_ls(self, parameter_s=''):
774 def magic_who_ls(self, parameter_s=''):
772 """Return a sorted list of all interactive variables.
775 """Return a sorted list of all interactive variables.
773
776
774 If arguments are given, only variables of types matching these
777 If arguments are given, only variables of types matching these
775 arguments are returned."""
778 arguments are returned."""
776
779
777 user_ns = self.shell.user_ns
780 user_ns = self.shell.user_ns
778 out = []
781 out = []
779 typelist = parameter_s.split()
782 typelist = parameter_s.split()
780 for i in self.shell.user_ns.keys():
783 for i in self.shell.user_ns.keys():
781 if not (i.startswith('_') or i.startswith('_i')) \
784 if not (i.startswith('_') or i.startswith('_i')) \
782 and not (self.internal_ns.has_key(i) or
785 and not (self.internal_ns.has_key(i) or
783 self.user_config_ns.has_key(i)):
786 self.user_config_ns.has_key(i)):
784 if typelist:
787 if typelist:
785 if type(user_ns[i]).__name__ in typelist:
788 if type(user_ns[i]).__name__ in typelist:
786 out.append(i)
789 out.append(i)
787 else:
790 else:
788 out.append(i)
791 out.append(i)
789 out.sort()
792 out.sort()
790 return out
793 return out
791
794
792 def magic_who(self, parameter_s=''):
795 def magic_who(self, parameter_s=''):
793 """Print all interactive variables, with some minimal formatting.
796 """Print all interactive variables, with some minimal formatting.
794
797
795 If any arguments are given, only variables whose type matches one of
798 If any arguments are given, only variables whose type matches one of
796 these are printed. For example:
799 these are printed. For example:
797
800
798 %who function str
801 %who function str
799
802
800 will only list functions and strings, excluding all other types of
803 will only list functions and strings, excluding all other types of
801 variables. To find the proper type names, simply use type(var) at a
804 variables. To find the proper type names, simply use type(var) at a
802 command line to see how python prints type names. For example:
805 command line to see how python prints type names. For example:
803
806
804 In [1]: type('hello')\\
807 In [1]: type('hello')\\
805 Out[1]: <type 'str'>
808 Out[1]: <type 'str'>
806
809
807 indicates that the type name for strings is 'str'.
810 indicates that the type name for strings is 'str'.
808
811
809 %who always excludes executed names loaded through your configuration
812 %who always excludes executed names loaded through your configuration
810 file and things which are internal to IPython.
813 file and things which are internal to IPython.
811
814
812 This is deliberate, as typically you may load many modules and the
815 This is deliberate, as typically you may load many modules and the
813 purpose of %who is to show you only what you've manually defined."""
816 purpose of %who is to show you only what you've manually defined."""
814
817
815 varlist = self.magic_who_ls(parameter_s)
818 varlist = self.magic_who_ls(parameter_s)
816 if not varlist:
819 if not varlist:
817 print 'Interactive namespace is empty.'
820 print 'Interactive namespace is empty.'
818 return
821 return
819
822
820 # if we have variables, move on...
823 # if we have variables, move on...
821
824
822 # stupid flushing problem: when prompts have no separators, stdout is
825 # stupid flushing problem: when prompts have no separators, stdout is
823 # getting lost. I'm starting to think this is a python bug. I'm having
826 # getting lost. I'm starting to think this is a python bug. I'm having
824 # to force a flush with a print because even a sys.stdout.flush
827 # to force a flush with a print because even a sys.stdout.flush
825 # doesn't seem to do anything!
828 # doesn't seem to do anything!
826
829
827 count = 0
830 count = 0
828 for i in varlist:
831 for i in varlist:
829 print i+'\t',
832 print i+'\t',
830 count += 1
833 count += 1
831 if count > 8:
834 if count > 8:
832 count = 0
835 count = 0
833 print
836 print
834 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
837 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
835
838
836 print # well, this does force a flush at the expense of an extra \n
839 print # well, this does force a flush at the expense of an extra \n
837
840
838 def magic_whos(self, parameter_s=''):
841 def magic_whos(self, parameter_s=''):
839 """Like %who, but gives some extra information about each variable.
842 """Like %who, but gives some extra information about each variable.
840
843
841 The same type filtering of %who can be applied here.
844 The same type filtering of %who can be applied here.
842
845
843 For all variables, the type is printed. Additionally it prints:
846 For all variables, the type is printed. Additionally it prints:
844
847
845 - For {},[],(): their length.
848 - For {},[],(): their length.
846
849
847 - For Numeric arrays, a summary with shape, number of elements,
850 - For Numeric arrays, a summary with shape, number of elements,
848 typecode and size in memory.
851 typecode and size in memory.
849
852
850 - Everything else: a string representation, snipping their middle if
853 - Everything else: a string representation, snipping their middle if
851 too long."""
854 too long."""
852
855
853 varnames = self.magic_who_ls(parameter_s)
856 varnames = self.magic_who_ls(parameter_s)
854 if not varnames:
857 if not varnames:
855 print 'Interactive namespace is empty.'
858 print 'Interactive namespace is empty.'
856 return
859 return
857
860
858 # if we have variables, move on...
861 # if we have variables, move on...
859
862
860 # for these types, show len() instead of data:
863 # for these types, show len() instead of data:
861 seq_types = [types.DictType,types.ListType,types.TupleType]
864 seq_types = [types.DictType,types.ListType,types.TupleType]
862
865
863 # for Numeric arrays, display summary info
866 # for Numeric arrays, display summary info
864 try:
867 try:
865 import Numeric
868 import Numeric
866 except ImportError:
869 except ImportError:
867 array_type = None
870 array_type = None
868 else:
871 else:
869 array_type = Numeric.ArrayType.__name__
872 array_type = Numeric.ArrayType.__name__
870
873
871 # Find all variable names and types so we can figure out column sizes
874 # Find all variable names and types so we can figure out column sizes
872 get_vars = lambda i: self.shell.user_ns[i]
875 get_vars = lambda i: self.shell.user_ns[i]
873 type_name = lambda v: type(v).__name__
876 type_name = lambda v: type(v).__name__
874 varlist = map(get_vars,varnames)
877 varlist = map(get_vars,varnames)
875 typelist = map(type_name,varlist)
878 typelist = map(type_name,varlist)
876 # column labels and # of spaces as separator
879 # column labels and # of spaces as separator
877 varlabel = 'Variable'
880 varlabel = 'Variable'
878 typelabel = 'Type'
881 typelabel = 'Type'
879 datalabel = 'Data/Info'
882 datalabel = 'Data/Info'
880 colsep = 3
883 colsep = 3
881 # variable format strings
884 # variable format strings
882 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
885 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
883 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
886 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
884 aformat = "%s: %s elems, type `%s`, %s bytes"
887 aformat = "%s: %s elems, type `%s`, %s bytes"
885 # find the size of the columns to format the output nicely
888 # find the size of the columns to format the output nicely
886 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
889 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
887 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
890 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
888 # table header
891 # table header
889 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
892 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
890 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
893 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
891 # and the table itself
894 # and the table itself
892 kb = 1024
895 kb = 1024
893 Mb = 1048576 # kb**2
896 Mb = 1048576 # kb**2
894 for vname,var,vtype in zip(varnames,varlist,typelist):
897 for vname,var,vtype in zip(varnames,varlist,typelist):
895 print itpl(vformat),
898 print itpl(vformat),
896 if vtype in seq_types:
899 if vtype in seq_types:
897 print len(var)
900 print len(var)
898 elif vtype==array_type:
901 elif vtype==array_type:
899 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
902 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
900 vsize = Numeric.size(var)
903 vsize = Numeric.size(var)
901 vbytes = vsize*var.itemsize()
904 vbytes = vsize*var.itemsize()
902 if vbytes < 100000:
905 if vbytes < 100000:
903 print aformat % (vshape,vsize,var.typecode(),vbytes)
906 print aformat % (vshape,vsize,var.typecode(),vbytes)
904 else:
907 else:
905 print aformat % (vshape,vsize,var.typecode(),vbytes),
908 print aformat % (vshape,vsize,var.typecode(),vbytes),
906 if vbytes < Mb:
909 if vbytes < Mb:
907 print '(%s kb)' % (vbytes/kb,)
910 print '(%s kb)' % (vbytes/kb,)
908 else:
911 else:
909 print '(%s Mb)' % (vbytes/Mb,)
912 print '(%s Mb)' % (vbytes/Mb,)
910 else:
913 else:
911 vstr = str(var)
914 vstr = str(var)
912 if len(vstr) < 50:
915 if len(vstr) < 50:
913 print vstr
916 print vstr
914 else:
917 else:
915 printpl(vfmt_short)
918 printpl(vfmt_short)
916
919
917 def magic_reset(self, parameter_s=''):
920 def magic_reset(self, parameter_s=''):
918 """Resets the namespace by removing all names defined by the user.
921 """Resets the namespace by removing all names defined by the user.
919
922
920 Input/Output history are left around in case you need them."""
923 Input/Output history are left around in case you need them."""
921
924
922 ans = raw_input(
925 ans = raw_input(
923 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
926 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
924 if not ans.lower() == 'y':
927 if not ans.lower() == 'y':
925 print 'Nothing done.'
928 print 'Nothing done.'
926 return
929 return
927 user_ns = self.shell.user_ns
930 user_ns = self.shell.user_ns
928 for i in self.magic_who_ls():
931 for i in self.magic_who_ls():
929 del(user_ns[i])
932 del(user_ns[i])
930
933
931 def magic_config(self,parameter_s=''):
934 def magic_config(self,parameter_s=''):
932 """Show IPython's internal configuration."""
935 """Show IPython's internal configuration."""
933
936
934 page('Current configuration structure:\n'+
937 page('Current configuration structure:\n'+
935 pformat(self.shell.rc.dict()))
938 pformat(self.shell.rc.dict()))
936
939
937 def magic_logstart(self,parameter_s=''):
940 def magic_logstart(self,parameter_s=''):
938 """Start logging anywhere in a session.
941 """Start logging anywhere in a session.
939
942
940 %logstart [log_name [log_mode]]
943 %logstart [log_name [log_mode]]
941
944
942 If no name is given, it defaults to a file named 'ipython.log' in your
945 If no name is given, it defaults to a file named 'ipython.log' in your
943 current directory, in 'rotate' mode (see below).
946 current directory, in 'rotate' mode (see below).
944
947
945 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
948 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
946 history up to that point and then continues logging.
949 history up to that point and then continues logging.
947
950
948 %logstart takes a second optional parameter: logging mode. This can be one
951 %logstart takes a second optional parameter: logging mode. This can be one
949 of (note that the modes are given unquoted):\\
952 of (note that the modes are given unquoted):\\
950 over: overwrite existing log.\\
953 over: overwrite existing log.\\
951 backup: rename (if exists) to name~ and start name.\\
954 backup: rename (if exists) to name~ and start name.\\
952 append: well, that says it.\\
955 append: well, that says it.\\
953 rotate: create rotating logs name.1~, name.2~, etc.
956 rotate: create rotating logs name.1~, name.2~, etc.
954 """
957 """
955
958
956 #FIXME. This function should all be moved to the Logger class.
959 #FIXME. This function should all be moved to the Logger class.
957
960
958 valid_modes = qw('over backup append rotate')
961 valid_modes = qw('over backup append rotate')
959 if self.LOG:
962 if self.LOG:
960 print 'Logging is already in place. Logfile:',self.LOG
963 print 'Logging is already in place. Logfile:',self.LOG
961 return
964 return
962
965
963 par = parameter_s.strip()
966 par = parameter_s.strip()
964 if not par:
967 if not par:
965 logname = self.LOGDEF
968 logname = self.LOGDEF
966 logmode = 'rotate' # use rotate for the auto-generated logs
969 logmode = 'rotate' # use rotate for the auto-generated logs
967 else:
970 else:
968 try:
971 try:
969 logname,logmode = par.split()
972 logname,logmode = par.split()
970 except:
973 except:
971 try:
974 try:
972 logname = par
975 logname = par
973 logmode = 'backup'
976 logmode = 'backup'
974 except:
977 except:
975 warn('Usage: %log [log_name [log_mode]]')
978 warn('Usage: %log [log_name [log_mode]]')
976 return
979 return
977 if not logmode in valid_modes:
980 if not logmode in valid_modes:
978 warn('Logging NOT activated.\n'
981 warn('Logging NOT activated.\n'
979 'Usage: %log [log_name [log_mode]]\n'
982 'Usage: %log [log_name [log_mode]]\n'
980 'Valid modes: '+str(valid_modes))
983 'Valid modes: '+str(valid_modes))
981 return
984 return
982
985
983 # If we made it this far, I think we're ok:
986 # If we made it this far, I think we're ok:
984 print 'Activating auto-logging.'
987 print 'Activating auto-logging.'
985 print 'Current session state plus future input saved to:',logname
988 print 'Current session state plus future input saved to:',logname
986 print 'Logging mode: ',logmode
989 print 'Logging mode: ',logmode
987 # put logname into rc struct as if it had been called on the command line,
990 # put logname into rc struct as if it had been called on the command line,
988 # so it ends up saved in the log header
991 # so it ends up saved in the log header
989 # Save it in case we need to restore it...
992 # Save it in case we need to restore it...
990 old_logfile = self.shell.rc.opts.get('logfile','')
993 old_logfile = self.shell.rc.opts.get('logfile','')
991 logname = os.path.expanduser(logname)
994 logname = os.path.expanduser(logname)
992 self.shell.rc.opts.logfile = logname
995 self.shell.rc.opts.logfile = logname
993 self.LOGMODE = logmode # FIXME: this should be set through a function.
996 self.LOGMODE = logmode # FIXME: this should be set through a function.
994 try:
997 try:
995 header = str(self.LOGHEAD)
998 header = str(self.LOGHEAD)
996 self.create_log(header,logname)
999 self.create_log(header,logname)
997 self.logstart(header,logname)
1000 self.logstart(header,logname)
998 except:
1001 except:
999 self.LOG = '' # we are NOT logging, something went wrong
1002 self.LOG = '' # we are NOT logging, something went wrong
1000 self.shell.rc.opts.logfile = old_logfile
1003 self.shell.rc.opts.logfile = old_logfile
1001 warn("Couldn't start log: "+str(sys.exc_info()[1]))
1004 warn("Couldn't start log: "+str(sys.exc_info()[1]))
1002 else: # log input history up to this point
1005 else: # log input history up to this point
1003 self.logfile.write(self.shell.user_ns['_ih'][1:])
1006 self.logfile.write(self.shell.user_ns['_ih'][1:])
1004 self.logfile.flush()
1007 self.logfile.flush()
1005
1008
1006 def magic_logoff(self,parameter_s=''):
1009 def magic_logoff(self,parameter_s=''):
1007 """Temporarily stop logging.
1010 """Temporarily stop logging.
1008
1011
1009 You must have previously started logging."""
1012 You must have previously started logging."""
1010 self.switch_log(0)
1013 self.switch_log(0)
1011
1014
1012 def magic_logon(self,parameter_s=''):
1015 def magic_logon(self,parameter_s=''):
1013 """Restart logging.
1016 """Restart logging.
1014
1017
1015 This function is for restarting logging which you've temporarily
1018 This function is for restarting logging which you've temporarily
1016 stopped with %logoff. For starting logging for the first time, you
1019 stopped with %logoff. For starting logging for the first time, you
1017 must use the %logstart function, which allows you to specify an
1020 must use the %logstart function, which allows you to specify an
1018 optional log filename."""
1021 optional log filename."""
1019
1022
1020 self.switch_log(1)
1023 self.switch_log(1)
1021
1024
1022 def magic_logstate(self,parameter_s=''):
1025 def magic_logstate(self,parameter_s=''):
1023 """Print the status of the logging system."""
1026 """Print the status of the logging system."""
1024
1027
1025 self.logstate()
1028 self.logstate()
1026
1029
1027 def magic_pdb(self, parameter_s=''):
1030 def magic_pdb(self, parameter_s=''):
1028 """Control the calling of the pdb interactive debugger.
1031 """Control the calling of the pdb interactive debugger.
1029
1032
1030 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1033 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1031 argument it works as a toggle.
1034 argument it works as a toggle.
1032
1035
1033 When an exception is triggered, IPython can optionally call the
1036 When an exception is triggered, IPython can optionally call the
1034 interactive pdb debugger after the traceback printout. %pdb toggles
1037 interactive pdb debugger after the traceback printout. %pdb toggles
1035 this feature on and off."""
1038 this feature on and off."""
1036
1039
1037 par = parameter_s.strip().lower()
1040 par = parameter_s.strip().lower()
1038
1041
1039 if par:
1042 if par:
1040 try:
1043 try:
1041 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1044 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1042 except KeyError:
1045 except KeyError:
1043 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
1046 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
1044 return
1047 return
1045 else:
1048 else:
1046 self.shell.InteractiveTB.call_pdb = pdb
1049 self.shell.InteractiveTB.call_pdb = pdb
1047 else:
1050 else:
1048 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
1051 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
1049 print 'Automatic pdb calling has been turned',\
1052 print 'Automatic pdb calling has been turned',\
1050 on_off(self.shell.InteractiveTB.call_pdb)
1053 on_off(self.shell.InteractiveTB.call_pdb)
1051
1054
1052
1055
1053 def magic_prun(self, parameter_s ='',user_mode=1,
1056 def magic_prun(self, parameter_s ='',user_mode=1,
1054 opts=None,arg_lst=None,prog_ns=None):
1057 opts=None,arg_lst=None,prog_ns=None):
1055
1058
1056 """Run a statement through the python code profiler.
1059 """Run a statement through the python code profiler.
1057
1060
1058 Usage:\\
1061 Usage:\\
1059 %prun [options] statement
1062 %prun [options] statement
1060
1063
1061 The given statement (which doesn't require quote marks) is run via the
1064 The given statement (which doesn't require quote marks) is run via the
1062 python profiler in a manner similar to the profile.run() function.
1065 python profiler in a manner similar to the profile.run() function.
1063 Namespaces are internally managed to work correctly; profile.run
1066 Namespaces are internally managed to work correctly; profile.run
1064 cannot be used in IPython because it makes certain assumptions about
1067 cannot be used in IPython because it makes certain assumptions about
1065 namespaces which do not hold under IPython.
1068 namespaces which do not hold under IPython.
1066
1069
1067 Options:
1070 Options:
1068
1071
1069 -l <limit>: you can place restrictions on what or how much of the
1072 -l <limit>: you can place restrictions on what or how much of the
1070 profile gets printed. The limit value can be:
1073 profile gets printed. The limit value can be:
1071
1074
1072 * A string: only information for function names containing this string
1075 * A string: only information for function names containing this string
1073 is printed.
1076 is printed.
1074
1077
1075 * An integer: only these many lines are printed.
1078 * An integer: only these many lines are printed.
1076
1079
1077 * A float (between 0 and 1): this fraction of the report is printed
1080 * A float (between 0 and 1): this fraction of the report is printed
1078 (for example, use a limit of 0.4 to see the topmost 40% only).
1081 (for example, use a limit of 0.4 to see the topmost 40% only).
1079
1082
1080 You can combine several limits with repeated use of the option. For
1083 You can combine several limits with repeated use of the option. For
1081 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1084 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1082 information about class constructors.
1085 information about class constructors.
1083
1086
1084 -r: return the pstats.Stats object generated by the profiling. This
1087 -r: return the pstats.Stats object generated by the profiling. This
1085 object has all the information about the profile in it, and you can
1088 object has all the information about the profile in it, and you can
1086 later use it for further analysis or in other functions.
1089 later use it for further analysis or in other functions.
1087
1090
1088 Since magic functions have a particular form of calling which prevents
1091 Since magic functions have a particular form of calling which prevents
1089 you from writing something like:\\
1092 you from writing something like:\\
1090 In [1]: p = %prun -r print 4 # invalid!\\
1093 In [1]: p = %prun -r print 4 # invalid!\\
1091 you must instead use IPython's automatic variables to assign this:\\
1094 you must instead use IPython's automatic variables to assign this:\\
1092 In [1]: %prun -r print 4 \\
1095 In [1]: %prun -r print 4 \\
1093 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1096 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1094 In [2]: stats = _
1097 In [2]: stats = _
1095
1098
1096 If you really need to assign this value via an explicit function call,
1099 If you really need to assign this value via an explicit function call,
1097 you can always tap directly into the true name of the magic function
1100 you can always tap directly into the true name of the magic function
1098 by using the ipmagic function (which IPython automatically adds to the
1101 by using the ipmagic function (which IPython automatically adds to the
1099 builtins):\\
1102 builtins):\\
1100 In [3]: stats = ipmagic('prun','-r print 4')
1103 In [3]: stats = ipmagic('prun','-r print 4')
1101
1104
1102 You can type ipmagic? for more details on ipmagic.
1105 You can type ipmagic? for more details on ipmagic.
1103
1106
1104 -s <key>: sort profile by given key. You can provide more than one key
1107 -s <key>: sort profile by given key. You can provide more than one key
1105 by using the option several times: '-s key1 -s key2 -s key3...'. The
1108 by using the option several times: '-s key1 -s key2 -s key3...'. The
1106 default sorting key is 'time'.
1109 default sorting key is 'time'.
1107
1110
1108 The following is copied verbatim from the profile documentation
1111 The following is copied verbatim from the profile documentation
1109 referenced below:
1112 referenced below:
1110
1113
1111 When more than one key is provided, additional keys are used as
1114 When more than one key is provided, additional keys are used as
1112 secondary criteria when the there is equality in all keys selected
1115 secondary criteria when the there is equality in all keys selected
1113 before them.
1116 before them.
1114
1117
1115 Abbreviations can be used for any key names, as long as the
1118 Abbreviations can be used for any key names, as long as the
1116 abbreviation is unambiguous. The following are the keys currently
1119 abbreviation is unambiguous. The following are the keys currently
1117 defined:
1120 defined:
1118
1121
1119 Valid Arg Meaning\\
1122 Valid Arg Meaning\\
1120 "calls" call count\\
1123 "calls" call count\\
1121 "cumulative" cumulative time\\
1124 "cumulative" cumulative time\\
1122 "file" file name\\
1125 "file" file name\\
1123 "module" file name\\
1126 "module" file name\\
1124 "pcalls" primitive call count\\
1127 "pcalls" primitive call count\\
1125 "line" line number\\
1128 "line" line number\\
1126 "name" function name\\
1129 "name" function name\\
1127 "nfl" name/file/line\\
1130 "nfl" name/file/line\\
1128 "stdname" standard name\\
1131 "stdname" standard name\\
1129 "time" internal time
1132 "time" internal time
1130
1133
1131 Note that all sorts on statistics are in descending order (placing
1134 Note that all sorts on statistics are in descending order (placing
1132 most time consuming items first), where as name, file, and line number
1135 most time consuming items first), where as name, file, and line number
1133 searches are in ascending order (i.e., alphabetical). The subtle
1136 searches are in ascending order (i.e., alphabetical). The subtle
1134 distinction between "nfl" and "stdname" is that the standard name is a
1137 distinction between "nfl" and "stdname" is that the standard name is a
1135 sort of the name as printed, which means that the embedded line
1138 sort of the name as printed, which means that the embedded line
1136 numbers get compared in an odd way. For example, lines 3, 20, and 40
1139 numbers get compared in an odd way. For example, lines 3, 20, and 40
1137 would (if the file names were the same) appear in the string order
1140 would (if the file names were the same) appear in the string order
1138 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1141 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1139 line numbers. In fact, sort_stats("nfl") is the same as
1142 line numbers. In fact, sort_stats("nfl") is the same as
1140 sort_stats("name", "file", "line").
1143 sort_stats("name", "file", "line").
1141
1144
1142 -T <filename>: save profile results as shown on screen to a text
1145 -T <filename>: save profile results as shown on screen to a text
1143 file. The profile is still shown on screen.
1146 file. The profile is still shown on screen.
1144
1147
1145 -D <filename>: save (via dump_stats) profile statistics to given
1148 -D <filename>: save (via dump_stats) profile statistics to given
1146 filename. This data is in a format understod by the pstats module, and
1149 filename. This data is in a format understod by the pstats module, and
1147 is generated by a call to the dump_stats() method of profile
1150 is generated by a call to the dump_stats() method of profile
1148 objects. The profile is still shown on screen.
1151 objects. The profile is still shown on screen.
1149
1152
1150 If you want to run complete programs under the profiler's control, use
1153 If you want to run complete programs under the profiler's control, use
1151 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1154 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1152 contains profiler specific options as described here.
1155 contains profiler specific options as described here.
1153
1156
1154 You can read the complete documentation for the profile module with:\\
1157 You can read the complete documentation for the profile module with:\\
1155 In [1]: import profile; profile.help() """
1158 In [1]: import profile; profile.help() """
1156
1159
1157 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1160 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1158 # protect user quote marks
1161 # protect user quote marks
1159 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1162 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1160
1163
1161 if user_mode: # regular user call
1164 if user_mode: # regular user call
1162 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1165 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1163 list_all=1)
1166 list_all=1)
1164 namespace = self.shell.user_ns
1167 namespace = self.shell.user_ns
1165 else: # called to run a program by %run -p
1168 else: # called to run a program by %run -p
1166 try:
1169 try:
1167 filename = get_py_filename(arg_lst[0])
1170 filename = get_py_filename(arg_lst[0])
1168 except IOError,msg:
1171 except IOError,msg:
1169 error(msg)
1172 error(msg)
1170 return
1173 return
1171
1174
1172 arg_str = 'execfile(filename,prog_ns)'
1175 arg_str = 'execfile(filename,prog_ns)'
1173 namespace = locals()
1176 namespace = locals()
1174
1177
1175 opts.merge(opts_def)
1178 opts.merge(opts_def)
1176
1179
1177 prof = profile.Profile()
1180 prof = profile.Profile()
1178 try:
1181 try:
1179 prof = prof.runctx(arg_str,namespace,namespace)
1182 prof = prof.runctx(arg_str,namespace,namespace)
1180 sys_exit = ''
1183 sys_exit = ''
1181 except SystemExit:
1184 except SystemExit:
1182 sys_exit = """*** SystemExit exception caught in code being profiled."""
1185 sys_exit = """*** SystemExit exception caught in code being profiled."""
1183
1186
1184 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1187 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1185
1188
1186 lims = opts.l
1189 lims = opts.l
1187 if lims:
1190 if lims:
1188 lims = [] # rebuild lims with ints/floats/strings
1191 lims = [] # rebuild lims with ints/floats/strings
1189 for lim in opts.l:
1192 for lim in opts.l:
1190 try:
1193 try:
1191 lims.append(int(lim))
1194 lims.append(int(lim))
1192 except ValueError:
1195 except ValueError:
1193 try:
1196 try:
1194 lims.append(float(lim))
1197 lims.append(float(lim))
1195 except ValueError:
1198 except ValueError:
1196 lims.append(lim)
1199 lims.append(lim)
1197
1200
1198 # trap output
1201 # trap output
1199 sys_stdout = sys.stdout
1202 sys_stdout = sys.stdout
1200 stdout_trap = StringIO()
1203 stdout_trap = StringIO()
1201 try:
1204 try:
1202 sys.stdout = stdout_trap
1205 sys.stdout = stdout_trap
1203 stats.print_stats(*lims)
1206 stats.print_stats(*lims)
1204 finally:
1207 finally:
1205 sys.stdout = sys_stdout
1208 sys.stdout = sys_stdout
1206 output = stdout_trap.getvalue()
1209 output = stdout_trap.getvalue()
1207 output = output.rstrip()
1210 output = output.rstrip()
1208
1211
1209 page(output,screen_lines=self.shell.rc.screen_length)
1212 page(output,screen_lines=self.shell.rc.screen_length)
1210 print sys_exit,
1213 print sys_exit,
1211
1214
1212 dump_file = opts.D[0]
1215 dump_file = opts.D[0]
1213 text_file = opts.T[0]
1216 text_file = opts.T[0]
1214 if dump_file:
1217 if dump_file:
1215 prof.dump_stats(dump_file)
1218 prof.dump_stats(dump_file)
1216 print '\n*** Profile stats marshalled to file',\
1219 print '\n*** Profile stats marshalled to file',\
1217 `dump_file`+'.',sys_exit
1220 `dump_file`+'.',sys_exit
1218 if text_file:
1221 if text_file:
1219 file(text_file,'w').write(output)
1222 file(text_file,'w').write(output)
1220 print '\n*** Profile printout saved to text file',\
1223 print '\n*** Profile printout saved to text file',\
1221 `text_file`+'.',sys_exit
1224 `text_file`+'.',sys_exit
1222
1225
1223 if opts.has_key('r'):
1226 if opts.has_key('r'):
1224 return stats
1227 return stats
1225 else:
1228 else:
1226 return None
1229 return None
1227
1230
1228 def magic_run(self, parameter_s ='',runner=None):
1231 def magic_run(self, parameter_s ='',runner=None):
1229 """Run the named file inside IPython as a program.
1232 """Run the named file inside IPython as a program.
1230
1233
1231 Usage:\\
1234 Usage:\\
1232 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1235 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1233
1236
1234 Parameters after the filename are passed as command-line arguments to
1237 Parameters after the filename are passed as command-line arguments to
1235 the program (put in sys.argv). Then, control returns to IPython's
1238 the program (put in sys.argv). Then, control returns to IPython's
1236 prompt.
1239 prompt.
1237
1240
1238 This is similar to running at a system prompt:\\
1241 This is similar to running at a system prompt:\\
1239 $ python file args\\
1242 $ python file args\\
1240 but with the advantage of giving you IPython's tracebacks, and of
1243 but with the advantage of giving you IPython's tracebacks, and of
1241 loading all variables into your interactive namespace for further use
1244 loading all variables into your interactive namespace for further use
1242 (unless -p is used, see below).
1245 (unless -p is used, see below).
1243
1246
1244 The file is executed in a namespace initially consisting only of
1247 The file is executed in a namespace initially consisting only of
1245 __name__=='__main__' and sys.argv constructed as indicated. It thus
1248 __name__=='__main__' and sys.argv constructed as indicated. It thus
1246 sees its environment as if it were being run as a stand-alone
1249 sees its environment as if it were being run as a stand-alone
1247 program. But after execution, the IPython interactive namespace gets
1250 program. But after execution, the IPython interactive namespace gets
1248 updated with all variables defined in the program (except for __name__
1251 updated with all variables defined in the program (except for __name__
1249 and sys.argv). This allows for very convenient loading of code for
1252 and sys.argv). This allows for very convenient loading of code for
1250 interactive work, while giving each program a 'clean sheet' to run in.
1253 interactive work, while giving each program a 'clean sheet' to run in.
1251
1254
1252 Options:
1255 Options:
1253
1256
1254 -n: __name__ is NOT set to '__main__', but to the running file's name
1257 -n: __name__ is NOT set to '__main__', but to the running file's name
1255 without extension (as python does under import). This allows running
1258 without extension (as python does under import). This allows running
1256 scripts and reloading the definitions in them without calling code
1259 scripts and reloading the definitions in them without calling code
1257 protected by an ' if __name__ == "__main__" ' clause.
1260 protected by an ' if __name__ == "__main__" ' clause.
1258
1261
1259 -i: run the file in IPython's namespace instead of an empty one. This
1262 -i: run the file in IPython's namespace instead of an empty one. This
1260 is useful if you are experimenting with code written in a text editor
1263 is useful if you are experimenting with code written in a text editor
1261 which depends on variables defined interactively.
1264 which depends on variables defined interactively.
1262
1265
1263 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1266 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1264 being run. This is particularly useful if IPython is being used to
1267 being run. This is particularly useful if IPython is being used to
1265 run unittests, which always exit with a sys.exit() call. In such
1268 run unittests, which always exit with a sys.exit() call. In such
1266 cases you are interested in the output of the test results, not in
1269 cases you are interested in the output of the test results, not in
1267 seeing a traceback of the unittest module.
1270 seeing a traceback of the unittest module.
1268
1271
1269 -t: print timing information at the end of the run. IPython will give
1272 -t: print timing information at the end of the run. IPython will give
1270 you an estimated CPU time consumption for your script, which under
1273 you an estimated CPU time consumption for your script, which under
1271 Unix uses the resource module to avoid the wraparound problems of
1274 Unix uses the resource module to avoid the wraparound problems of
1272 time.clock(). Under Unix, an estimate of time spent on system tasks
1275 time.clock(). Under Unix, an estimate of time spent on system tasks
1273 is also given (for Windows platforms this is reported as 0.0).
1276 is also given (for Windows platforms this is reported as 0.0).
1274
1277
1275 If -t is given, an additional -N<N> option can be given, where <N>
1278 If -t is given, an additional -N<N> option can be given, where <N>
1276 must be an integer indicating how many times you want the script to
1279 must be an integer indicating how many times you want the script to
1277 run. The final timing report will include total and per run results.
1280 run. The final timing report will include total and per run results.
1278
1281
1279 For example (testing the script uniq_stable.py):
1282 For example (testing the script uniq_stable.py):
1280
1283
1281 In [1]: run -t uniq_stable
1284 In [1]: run -t uniq_stable
1282
1285
1283 IPython CPU timings (estimated):\\
1286 IPython CPU timings (estimated):\\
1284 User : 0.19597 s.\\
1287 User : 0.19597 s.\\
1285 System: 0.0 s.\\
1288 System: 0.0 s.\\
1286
1289
1287 In [2]: run -t -N5 uniq_stable
1290 In [2]: run -t -N5 uniq_stable
1288
1291
1289 IPython CPU timings (estimated):\\
1292 IPython CPU timings (estimated):\\
1290 Total runs performed: 5\\
1293 Total runs performed: 5\\
1291 Times : Total Per run\\
1294 Times : Total Per run\\
1292 User : 0.910862 s, 0.1821724 s.\\
1295 User : 0.910862 s, 0.1821724 s.\\
1293 System: 0.0 s, 0.0 s.
1296 System: 0.0 s, 0.0 s.
1294
1297
1295 -d: run your program under the control of pdb, the Python debugger.
1298 -d: run your program under the control of pdb, the Python debugger.
1296 This allows you to execute your program step by step, watch variables,
1299 This allows you to execute your program step by step, watch variables,
1297 etc. Internally, what IPython does is similar to calling:
1300 etc. Internally, what IPython does is similar to calling:
1298
1301
1299 pdb.run('execfile("YOURFILENAME")')
1302 pdb.run('execfile("YOURFILENAME")')
1300
1303
1301 with a breakpoint set on line 1 of your file. You can change the line
1304 with a breakpoint set on line 1 of your file. You can change the line
1302 number for this automatic breakpoint to be <N> by using the -bN option
1305 number for this automatic breakpoint to be <N> by using the -bN option
1303 (where N must be an integer). For example:
1306 (where N must be an integer). For example:
1304
1307
1305 %run -d -b40 myscript
1308 %run -d -b40 myscript
1306
1309
1307 will set the first breakpoint at line 40 in myscript.py. Note that
1310 will set the first breakpoint at line 40 in myscript.py. Note that
1308 the first breakpoint must be set on a line which actually does
1311 the first breakpoint must be set on a line which actually does
1309 something (not a comment or docstring) for it to stop execution.
1312 something (not a comment or docstring) for it to stop execution.
1310
1313
1311 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1314 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1312 first enter 'c' (without qoutes) to start execution up to the first
1315 first enter 'c' (without qoutes) to start execution up to the first
1313 breakpoint.
1316 breakpoint.
1314
1317
1315 Entering 'help' gives information about the use of the debugger. You
1318 Entering 'help' gives information about the use of the debugger. You
1316 can easily see pdb's full documentation with "import pdb;pdb.help()"
1319 can easily see pdb's full documentation with "import pdb;pdb.help()"
1317 at a prompt.
1320 at a prompt.
1318
1321
1319 -p: run program under the control of the Python profiler module (which
1322 -p: run program under the control of the Python profiler module (which
1320 prints a detailed report of execution times, function calls, etc).
1323 prints a detailed report of execution times, function calls, etc).
1321
1324
1322 You can pass other options after -p which affect the behavior of the
1325 You can pass other options after -p which affect the behavior of the
1323 profiler itself. See the docs for %prun for details.
1326 profiler itself. See the docs for %prun for details.
1324
1327
1325 In this mode, the program's variables do NOT propagate back to the
1328 In this mode, the program's variables do NOT propagate back to the
1326 IPython interactive namespace (because they remain in the namespace
1329 IPython interactive namespace (because they remain in the namespace
1327 where the profiler executes them).
1330 where the profiler executes them).
1328
1331
1329 Internally this triggers a call to %prun, see its documentation for
1332 Internally this triggers a call to %prun, see its documentation for
1330 details on the options available specifically for profiling."""
1333 details on the options available specifically for profiling."""
1331
1334
1332 # get arguments and set sys.argv for program to be run.
1335 # get arguments and set sys.argv for program to be run.
1333 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1336 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1334 mode='list',list_all=1)
1337 mode='list',list_all=1)
1335
1338
1336 try:
1339 try:
1337 filename = get_py_filename(arg_lst[0])
1340 filename = get_py_filename(arg_lst[0])
1338 except IndexError:
1341 except IndexError:
1339 warn('you must provide at least a filename.')
1342 warn('you must provide at least a filename.')
1340 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1343 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1341 return
1344 return
1342 except IOError,msg:
1345 except IOError,msg:
1343 error(msg)
1346 error(msg)
1344 return
1347 return
1345
1348
1346 # Control the response to exit() calls made by the script being run
1349 # Control the response to exit() calls made by the script being run
1347 exit_ignore = opts.has_key('e')
1350 exit_ignore = opts.has_key('e')
1348
1351
1349 # Make sure that the running script gets a proper sys.argv as if it
1352 # Make sure that the running script gets a proper sys.argv as if it
1350 # were run from a system shell.
1353 # were run from a system shell.
1351 save_argv = sys.argv # save it for later restoring
1354 save_argv = sys.argv # save it for later restoring
1352 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1355 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1353
1356
1354 if opts.has_key('i'):
1357 if opts.has_key('i'):
1355 prog_ns = self.shell.user_ns
1358 prog_ns = self.shell.user_ns
1356 __name__save = self.shell.user_ns['__name__']
1359 __name__save = self.shell.user_ns['__name__']
1357 prog_ns['__name__'] = '__main__'
1360 prog_ns['__name__'] = '__main__'
1358 else:
1361 else:
1359 if opts.has_key('n'):
1362 if opts.has_key('n'):
1360 name = os.path.splitext(os.path.basename(filename))[0]
1363 name = os.path.splitext(os.path.basename(filename))[0]
1361 else:
1364 else:
1362 name = '__main__'
1365 name = '__main__'
1363 prog_ns = {'__name__':name}
1366 prog_ns = {'__name__':name}
1364
1367
1365 # pickle fix. See iplib for an explanation
1368 # pickle fix. See iplib for an explanation
1366 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1369 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1367
1370
1368 stats = None
1371 stats = None
1369 try:
1372 try:
1370 if opts.has_key('p'):
1373 if opts.has_key('p'):
1371 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1374 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1372 else:
1375 else:
1373 if opts.has_key('d'):
1376 if opts.has_key('d'):
1374 deb = pdb.Pdb()
1377 deb = Debugger.Pdb(self.shell.rc.colors)
1375 # reset Breakpoint state, which is moronically kept
1378 # reset Breakpoint state, which is moronically kept
1376 # in a class
1379 # in a class
1377 bdb.Breakpoint.next = 1
1380 bdb.Breakpoint.next = 1
1378 bdb.Breakpoint.bplist = {}
1381 bdb.Breakpoint.bplist = {}
1379 bdb.Breakpoint.bpbynumber = [None]
1382 bdb.Breakpoint.bpbynumber = [None]
1380 # Set an initial breakpoint to stop execution
1383 # Set an initial breakpoint to stop execution
1381 maxtries = 10
1384 maxtries = 10
1382 bp = int(opts.get('b',[1])[0])
1385 bp = int(opts.get('b',[1])[0])
1383 checkline = deb.checkline(filename,bp)
1386 checkline = deb.checkline(filename,bp)
1384 if not checkline:
1387 if not checkline:
1385 for bp in range(bp+1,bp+maxtries+1):
1388 for bp in range(bp+1,bp+maxtries+1):
1386 if deb.checkline(filename,bp):
1389 if deb.checkline(filename,bp):
1387 break
1390 break
1388 else:
1391 else:
1389 msg = ("\nI failed to find a valid line to set "
1392 msg = ("\nI failed to find a valid line to set "
1390 "a breakpoint\n"
1393 "a breakpoint\n"
1391 "after trying up to line: %s.\n"
1394 "after trying up to line: %s.\n"
1392 "Please set a valid breakpoint manually "
1395 "Please set a valid breakpoint manually "
1393 "with the -b option." % bp)
1396 "with the -b option." % bp)
1394 error(msg)
1397 error(msg)
1395 return
1398 return
1396 # if we find a good linenumber, set the breakpoint
1399 # if we find a good linenumber, set the breakpoint
1397 deb.do_break('%s:%s' % (filename,bp))
1400 deb.do_break('%s:%s' % (filename,bp))
1398 # Start file run
1401 # Start file run
1399 print "NOTE: Enter 'c' at the",
1402 print "NOTE: Enter 'c' at the",
1400 print "(Pdb) prompt to start your script."
1403 print "ipdb> prompt to start your script."
1404 try:
1401 deb.run('execfile("%s")' % filename,prog_ns)
1405 deb.run('execfile("%s")' % filename,prog_ns)
1406 except:
1407 etype, value, tb = sys.exc_info()
1408 # Skip three frames in the traceback: the %run one,
1409 # one inside bdb.py, and the command-line typed by the
1410 # user (run by exec in pdb itself).
1411 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1402 else:
1412 else:
1403 if runner is None:
1413 if runner is None:
1404 runner = self.shell.safe_execfile
1414 runner = self.shell.safe_execfile
1405 if opts.has_key('t'):
1415 if opts.has_key('t'):
1406 try:
1416 try:
1407 nruns = int(opts['N'][0])
1417 nruns = int(opts['N'][0])
1408 if nruns < 1:
1418 if nruns < 1:
1409 error('Number of runs must be >=1')
1419 error('Number of runs must be >=1')
1410 return
1420 return
1411 except (KeyError):
1421 except (KeyError):
1412 nruns = 1
1422 nruns = 1
1413 if nruns == 1:
1423 if nruns == 1:
1414 t0 = clock2()
1424 t0 = clock2()
1415 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1425 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1416 t1 = clock2()
1426 t1 = clock2()
1417 t_usr = t1[0]-t0[0]
1427 t_usr = t1[0]-t0[0]
1418 t_sys = t1[1]-t1[1]
1428 t_sys = t1[1]-t1[1]
1419 print "\nIPython CPU timings (estimated):"
1429 print "\nIPython CPU timings (estimated):"
1420 print " User : %10s s." % t_usr
1430 print " User : %10s s." % t_usr
1421 print " System: %10s s." % t_sys
1431 print " System: %10s s." % t_sys
1422 else:
1432 else:
1423 runs = range(nruns)
1433 runs = range(nruns)
1424 t0 = clock2()
1434 t0 = clock2()
1425 for nr in runs:
1435 for nr in runs:
1426 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1436 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1427 t1 = clock2()
1437 t1 = clock2()
1428 t_usr = t1[0]-t0[0]
1438 t_usr = t1[0]-t0[0]
1429 t_sys = t1[1]-t1[1]
1439 t_sys = t1[1]-t1[1]
1430 print "\nIPython CPU timings (estimated):"
1440 print "\nIPython CPU timings (estimated):"
1431 print "Total runs performed:",nruns
1441 print "Total runs performed:",nruns
1432 print " Times : %10s %10s" % ('Total','Per run')
1442 print " Times : %10s %10s" % ('Total','Per run')
1433 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1443 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1434 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1444 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1435
1445
1436 else:
1446 else:
1437 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1447 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1438 if opts.has_key('i'):
1448 if opts.has_key('i'):
1439 self.shell.user_ns['__name__'] = __name__save
1449 self.shell.user_ns['__name__'] = __name__save
1440 else:
1450 else:
1441 # update IPython interactive namespace
1451 # update IPython interactive namespace
1442 del prog_ns['__name__']
1452 del prog_ns['__name__']
1443 self.shell.user_ns.update(prog_ns)
1453 self.shell.user_ns.update(prog_ns)
1444 finally:
1454 finally:
1445 sys.argv = save_argv
1455 sys.argv = save_argv
1446 return stats
1456 return stats
1447
1457
1448 def magic_runlog(self, parameter_s =''):
1458 def magic_runlog(self, parameter_s =''):
1449 """Run files as logs.
1459 """Run files as logs.
1450
1460
1451 Usage:\\
1461 Usage:\\
1452 %runlog file1 file2 ...
1462 %runlog file1 file2 ...
1453
1463
1454 Run the named files (treating them as log files) in sequence inside
1464 Run the named files (treating them as log files) in sequence inside
1455 the interpreter, and return to the prompt. This is much slower than
1465 the interpreter, and return to the prompt. This is much slower than
1456 %run because each line is executed in a try/except block, but it
1466 %run because each line is executed in a try/except block, but it
1457 allows running files with syntax errors in them.
1467 allows running files with syntax errors in them.
1458
1468
1459 Normally IPython will guess when a file is one of its own logfiles, so
1469 Normally IPython will guess when a file is one of its own logfiles, so
1460 you can typically use %run even for logs. This shorthand allows you to
1470 you can typically use %run even for logs. This shorthand allows you to
1461 force any file to be treated as a log file."""
1471 force any file to be treated as a log file."""
1462
1472
1463 for f in parameter_s.split():
1473 for f in parameter_s.split():
1464 self.shell.safe_execfile(f,self.shell.user_ns,
1474 self.shell.safe_execfile(f,self.shell.user_ns,
1465 self.shell.user_ns,islog=1)
1475 self.shell.user_ns,islog=1)
1466
1476
1467 def magic_time(self,parameter_s = ''):
1477 def magic_time(self,parameter_s = ''):
1468 """Time execution of a Python statement or expression.
1478 """Time execution of a Python statement or expression.
1469
1479
1470 The CPU and wall clock times are printed, and the value of the
1480 The CPU and wall clock times are printed, and the value of the
1471 expression (if any) is returned. Note that under Win32, system time
1481 expression (if any) is returned. Note that under Win32, system time
1472 is always reported as 0, since it can not be measured.
1482 is always reported as 0, since it can not be measured.
1473
1483
1474 This function provides very basic timing functionality. In Python
1484 This function provides very basic timing functionality. In Python
1475 2.3, the timeit module offers more control and sophistication, but for
1485 2.3, the timeit module offers more control and sophistication, but for
1476 now IPython supports Python 2.2, so we can not rely on timeit being
1486 now IPython supports Python 2.2, so we can not rely on timeit being
1477 present.
1487 present.
1478
1488
1479 Some examples:
1489 Some examples:
1480
1490
1481 In [1]: time 2**128
1491 In [1]: time 2**128
1482 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1492 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1483 Wall time: 0.00
1493 Wall time: 0.00
1484 Out[1]: 340282366920938463463374607431768211456L
1494 Out[1]: 340282366920938463463374607431768211456L
1485
1495
1486 In [2]: n = 1000000
1496 In [2]: n = 1000000
1487
1497
1488 In [3]: time sum(range(n))
1498 In [3]: time sum(range(n))
1489 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1499 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1490 Wall time: 1.37
1500 Wall time: 1.37
1491 Out[3]: 499999500000L
1501 Out[3]: 499999500000L
1492
1502
1493 In [4]: time print 'hello world'
1503 In [4]: time print 'hello world'
1494 hello world
1504 hello world
1495 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1505 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1496 Wall time: 0.00
1506 Wall time: 0.00
1497 """
1507 """
1498
1508
1499 # fail immediately if the given expression can't be compiled
1509 # fail immediately if the given expression can't be compiled
1500 try:
1510 try:
1501 mode = 'eval'
1511 mode = 'eval'
1502 code = compile(parameter_s,'<timed eval>',mode)
1512 code = compile(parameter_s,'<timed eval>',mode)
1503 except SyntaxError:
1513 except SyntaxError:
1504 mode = 'exec'
1514 mode = 'exec'
1505 code = compile(parameter_s,'<timed exec>',mode)
1515 code = compile(parameter_s,'<timed exec>',mode)
1506 # skew measurement as little as possible
1516 # skew measurement as little as possible
1507 glob = self.shell.user_ns
1517 glob = self.shell.user_ns
1508 clk = clock2
1518 clk = clock2
1509 wtime = time.time
1519 wtime = time.time
1510 # time execution
1520 # time execution
1511 wall_st = wtime()
1521 wall_st = wtime()
1512 if mode=='eval':
1522 if mode=='eval':
1513 st = clk()
1523 st = clk()
1514 out = eval(code,glob)
1524 out = eval(code,glob)
1515 end = clk()
1525 end = clk()
1516 else:
1526 else:
1517 st = clk()
1527 st = clk()
1518 exec code in glob
1528 exec code in glob
1519 end = clk()
1529 end = clk()
1520 out = None
1530 out = None
1521 wall_end = wtime()
1531 wall_end = wtime()
1522 # Compute actual times and report
1532 # Compute actual times and report
1523 wall_time = wall_end-wall_st
1533 wall_time = wall_end-wall_st
1524 cpu_user = end[0]-st[0]
1534 cpu_user = end[0]-st[0]
1525 cpu_sys = end[1]-st[1]
1535 cpu_sys = end[1]-st[1]
1526 cpu_tot = cpu_user+cpu_sys
1536 cpu_tot = cpu_user+cpu_sys
1527 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1537 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1528 (cpu_user,cpu_sys,cpu_tot)
1538 (cpu_user,cpu_sys,cpu_tot)
1529 print "Wall time: %.2f" % wall_time
1539 print "Wall time: %.2f" % wall_time
1530 return out
1540 return out
1531
1541
1532 def magic_macro(self,parameter_s = ''):
1542 def magic_macro(self,parameter_s = ''):
1533 """Define a set of input lines as a macro for future re-execution.
1543 """Define a set of input lines as a macro for future re-execution.
1534
1544
1535 Usage:\\
1545 Usage:\\
1536 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1546 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1537
1547
1538 This will define a global variable called `name` which is a string
1548 This will define a global variable called `name` which is a string
1539 made of joining the slices and lines you specify (n1,n2,... numbers
1549 made of joining the slices and lines you specify (n1,n2,... numbers
1540 above) from your input history into a single string. This variable
1550 above) from your input history into a single string. This variable
1541 acts like an automatic function which re-executes those lines as if
1551 acts like an automatic function which re-executes those lines as if
1542 you had typed them. You just type 'name' at the prompt and the code
1552 you had typed them. You just type 'name' at the prompt and the code
1543 executes.
1553 executes.
1544
1554
1545 Note that the slices use the standard Python slicing notation (5:8
1555 Note that the slices use the standard Python slicing notation (5:8
1546 means include lines numbered 5,6,7).
1556 means include lines numbered 5,6,7).
1547
1557
1548 For example, if your history contains (%hist prints it):
1558 For example, if your history contains (%hist prints it):
1549
1559
1550 44: x=1\\
1560 44: x=1\\
1551 45: y=3\\
1561 45: y=3\\
1552 46: z=x+y\\
1562 46: z=x+y\\
1553 47: print x\\
1563 47: print x\\
1554 48: a=5\\
1564 48: a=5\\
1555 49: print 'x',x,'y',y\\
1565 49: print 'x',x,'y',y\\
1556
1566
1557 you can create a macro with lines 44 through 47 (included) and line 49
1567 you can create a macro with lines 44 through 47 (included) and line 49
1558 called my_macro with:
1568 called my_macro with:
1559
1569
1560 In [51]: %macro my_macro 44:48 49
1570 In [51]: %macro my_macro 44:48 49
1561
1571
1562 Now, typing `my_macro` (without quotes) will re-execute all this code
1572 Now, typing `my_macro` (without quotes) will re-execute all this code
1563 in one pass.
1573 in one pass.
1564
1574
1565 You don't need to give the line-numbers in order, and any given line
1575 You don't need to give the line-numbers in order, and any given line
1566 number can appear multiple times. You can assemble macros with any
1576 number can appear multiple times. You can assemble macros with any
1567 lines from your input history in any order.
1577 lines from your input history in any order.
1568
1578
1569 The macro is a simple object which holds its value in an attribute,
1579 The macro is a simple object which holds its value in an attribute,
1570 but IPython's display system checks for macros and executes them as
1580 but IPython's display system checks for macros and executes them as
1571 code instead of printing them when you type their name.
1581 code instead of printing them when you type their name.
1572
1582
1573 You can view a macro's contents by explicitly printing it with:
1583 You can view a macro's contents by explicitly printing it with:
1574
1584
1575 'print macro_name'.
1585 'print macro_name'.
1576
1586
1577 For one-off cases which DON'T contain magic function calls in them you
1587 For one-off cases which DON'T contain magic function calls in them you
1578 can obtain similar results by explicitly executing slices from your
1588 can obtain similar results by explicitly executing slices from your
1579 input history with:
1589 input history with:
1580
1590
1581 In [60]: exec In[44:48]+In[49]"""
1591 In [60]: exec In[44:48]+In[49]"""
1582
1592
1583 args = parameter_s.split()
1593 args = parameter_s.split()
1584 name,ranges = args[0], args[1:]
1594 name,ranges = args[0], args[1:]
1585 #print 'rng',ranges # dbg
1595 #print 'rng',ranges # dbg
1586 cmds = self.extract_input_slices(ranges)
1596 cmds = self.extract_input_slices(ranges)
1587 macro = Macro(cmds)
1597 macro = Macro(cmds)
1588 self.shell.user_ns.update({name:macro})
1598 self.shell.user_ns.update({name:macro})
1589 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1599 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1590 print 'Macro contents:'
1600 print 'Macro contents:'
1591 print str(macro).rstrip(),
1601 print str(macro).rstrip(),
1592
1602
1593 def magic_save(self,parameter_s = ''):
1603 def magic_save(self,parameter_s = ''):
1594 """Save a set of lines to a given filename.
1604 """Save a set of lines to a given filename.
1595
1605
1596 Usage:\\
1606 Usage:\\
1597 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1607 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1598
1608
1599 This function uses the same syntax as %macro for line extraction, but
1609 This function uses the same syntax as %macro for line extraction, but
1600 instead of creating a macro it saves the resulting string to the
1610 instead of creating a macro it saves the resulting string to the
1601 filename you specify.
1611 filename you specify.
1602
1612
1603 It adds a '.py' extension to the file if you don't do so yourself, and
1613 It adds a '.py' extension to the file if you don't do so yourself, and
1604 it asks for confirmation before overwriting existing files."""
1614 it asks for confirmation before overwriting existing files."""
1605
1615
1606 args = parameter_s.split()
1616 args = parameter_s.split()
1607 fname,ranges = args[0], args[1:]
1617 fname,ranges = args[0], args[1:]
1608 if not fname.endswith('.py'):
1618 if not fname.endswith('.py'):
1609 fname += '.py'
1619 fname += '.py'
1610 if os.path.isfile(fname):
1620 if os.path.isfile(fname):
1611 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1621 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1612 if ans.lower() not in ['y','yes']:
1622 if ans.lower() not in ['y','yes']:
1613 print 'Operation cancelled.'
1623 print 'Operation cancelled.'
1614 return
1624 return
1615 cmds = ''.join(self.extract_input_slices(ranges))
1625 cmds = ''.join(self.extract_input_slices(ranges))
1616 f = file(fname,'w')
1626 f = file(fname,'w')
1617 f.write(cmds)
1627 f.write(cmds)
1618 f.close()
1628 f.close()
1619 print 'The following commands were written to file `%s`:' % fname
1629 print 'The following commands were written to file `%s`:' % fname
1620 print cmds
1630 print cmds
1621
1631
1622 def magic_ed(self,parameter_s = ''):
1632 def magic_ed(self,parameter_s = ''):
1623 """Alias to %edit."""
1633 """Alias to %edit."""
1624 return self.magic_edit(parameter_s)
1634 return self.magic_edit(parameter_s)
1625
1635
1626 def magic_edit(self,parameter_s = '',last_call=['','']):
1636 def magic_edit(self,parameter_s = '',last_call=['','']):
1627 """Bring up an editor and execute the resulting code.
1637 """Bring up an editor and execute the resulting code.
1628
1638
1629 Usage:
1639 Usage:
1630 %edit [options] [args]
1640 %edit [options] [args]
1631
1641
1632 %edit runs IPython's editor hook. The default version of this hook is
1642 %edit runs IPython's editor hook. The default version of this hook is
1633 set to call the __IPYTHON__.rc.editor command. This is read from your
1643 set to call the __IPYTHON__.rc.editor command. This is read from your
1634 environment variable $EDITOR. If this isn't found, it will default to
1644 environment variable $EDITOR. If this isn't found, it will default to
1635 vi under Linux/Unix and to notepad under Windows. See the end of this
1645 vi under Linux/Unix and to notepad under Windows. See the end of this
1636 docstring for how to change the editor hook.
1646 docstring for how to change the editor hook.
1637
1647
1638 You can also set the value of this editor via the command line option
1648 You can also set the value of this editor via the command line option
1639 '-editor' or in your ipythonrc file. This is useful if you wish to use
1649 '-editor' or in your ipythonrc file. This is useful if you wish to use
1640 specifically for IPython an editor different from your typical default
1650 specifically for IPython an editor different from your typical default
1641 (and for Windows users who typically don't set environment variables).
1651 (and for Windows users who typically don't set environment variables).
1642
1652
1643 This command allows you to conveniently edit multi-line code right in
1653 This command allows you to conveniently edit multi-line code right in
1644 your IPython session.
1654 your IPython session.
1645
1655
1646 If called without arguments, %edit opens up an empty editor with a
1656 If called without arguments, %edit opens up an empty editor with a
1647 temporary file and will execute the contents of this file when you
1657 temporary file and will execute the contents of this file when you
1648 close it (don't forget to save it!).
1658 close it (don't forget to save it!).
1649
1659
1650 Options:
1660 Options:
1651
1661
1652 -p: this will call the editor with the same data as the previous time
1662 -p: this will call the editor with the same data as the previous time
1653 it was used, regardless of how long ago (in your current session) it
1663 it was used, regardless of how long ago (in your current session) it
1654 was.
1664 was.
1655
1665
1656 -x: do not execute the edited code immediately upon exit. This is
1666 -x: do not execute the edited code immediately upon exit. This is
1657 mainly useful if you are editing programs which need to be called with
1667 mainly useful if you are editing programs which need to be called with
1658 command line arguments, which you can then do using %run.
1668 command line arguments, which you can then do using %run.
1659
1669
1660 Arguments:
1670 Arguments:
1661
1671
1662 If arguments are given, the following possibilites exist:
1672 If arguments are given, the following possibilites exist:
1663
1673
1664 - The arguments are numbers or pairs of colon-separated numbers (like
1674 - The arguments are numbers or pairs of colon-separated numbers (like
1665 1 4:8 9). These are interpreted as lines of previous input to be
1675 1 4:8 9). These are interpreted as lines of previous input to be
1666 loaded into the editor. The syntax is the same of the %macro command.
1676 loaded into the editor. The syntax is the same of the %macro command.
1667
1677
1668 - If the argument doesn't start with a number, it is evaluated as a
1678 - If the argument doesn't start with a number, it is evaluated as a
1669 variable and its contents loaded into the editor. You can thus edit
1679 variable and its contents loaded into the editor. You can thus edit
1670 any string which contains python code (including the result of
1680 any string which contains python code (including the result of
1671 previous edits).
1681 previous edits).
1672
1682
1673 - If the argument is the name of an object (other than a string),
1683 - If the argument is the name of an object (other than a string),
1674 IPython will try to locate the file where it was defined and open the
1684 IPython will try to locate the file where it was defined and open the
1675 editor at the point where it is defined. You can use `%edit function`
1685 editor at the point where it is defined. You can use `%edit function`
1676 to load an editor exactly at the point where 'function' is defined,
1686 to load an editor exactly at the point where 'function' is defined,
1677 edit it and have the file be executed automatically.
1687 edit it and have the file be executed automatically.
1678
1688
1679 Note: opening at an exact line is only supported under Unix, and some
1689 Note: opening at an exact line is only supported under Unix, and some
1680 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1690 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1681 '+NUMBER' parameter necessary for this feature. Good editors like
1691 '+NUMBER' parameter necessary for this feature. Good editors like
1682 (X)Emacs, vi, jed, pico and joe all do.
1692 (X)Emacs, vi, jed, pico and joe all do.
1683
1693
1684 - If the argument is not found as a variable, IPython will look for a
1694 - If the argument is not found as a variable, IPython will look for a
1685 file with that name (adding .py if necessary) and load it into the
1695 file with that name (adding .py if necessary) and load it into the
1686 editor. It will execute its contents with execfile() when you exit,
1696 editor. It will execute its contents with execfile() when you exit,
1687 loading any code in the file into your interactive namespace.
1697 loading any code in the file into your interactive namespace.
1688
1698
1689 After executing your code, %edit will return as output the code you
1699 After executing your code, %edit will return as output the code you
1690 typed in the editor (except when it was an existing file). This way
1700 typed in the editor (except when it was an existing file). This way
1691 you can reload the code in further invocations of %edit as a variable,
1701 you can reload the code in further invocations of %edit as a variable,
1692 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1702 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1693 the output.
1703 the output.
1694
1704
1695 Note that %edit is also available through the alias %ed.
1705 Note that %edit is also available through the alias %ed.
1696
1706
1697 This is an example of creating a simple function inside the editor and
1707 This is an example of creating a simple function inside the editor and
1698 then modifying it. First, start up the editor:
1708 then modifying it. First, start up the editor:
1699
1709
1700 In [1]: ed\\
1710 In [1]: ed\\
1701 Editing... done. Executing edited code...\\
1711 Editing... done. Executing edited code...\\
1702 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1712 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1703
1713
1704 We can then call the function foo():
1714 We can then call the function foo():
1705
1715
1706 In [2]: foo()\\
1716 In [2]: foo()\\
1707 foo() was defined in an editing session
1717 foo() was defined in an editing session
1708
1718
1709 Now we edit foo. IPython automatically loads the editor with the
1719 Now we edit foo. IPython automatically loads the editor with the
1710 (temporary) file where foo() was previously defined:
1720 (temporary) file where foo() was previously defined:
1711
1721
1712 In [3]: ed foo\\
1722 In [3]: ed foo\\
1713 Editing... done. Executing edited code...
1723 Editing... done. Executing edited code...
1714
1724
1715 And if we call foo() again we get the modified version:
1725 And if we call foo() again we get the modified version:
1716
1726
1717 In [4]: foo()\\
1727 In [4]: foo()\\
1718 foo() has now been changed!
1728 foo() has now been changed!
1719
1729
1720 Here is an example of how to edit a code snippet successive
1730 Here is an example of how to edit a code snippet successive
1721 times. First we call the editor:
1731 times. First we call the editor:
1722
1732
1723 In [8]: ed\\
1733 In [8]: ed\\
1724 Editing... done. Executing edited code...\\
1734 Editing... done. Executing edited code...\\
1725 hello\\
1735 hello\\
1726 Out[8]: "print 'hello'\\n"
1736 Out[8]: "print 'hello'\\n"
1727
1737
1728 Now we call it again with the previous output (stored in _):
1738 Now we call it again with the previous output (stored in _):
1729
1739
1730 In [9]: ed _\\
1740 In [9]: ed _\\
1731 Editing... done. Executing edited code...\\
1741 Editing... done. Executing edited code...\\
1732 hello world\\
1742 hello world\\
1733 Out[9]: "print 'hello world'\\n"
1743 Out[9]: "print 'hello world'\\n"
1734
1744
1735 Now we call it with the output #8 (stored in _8, also as Out[8]):
1745 Now we call it with the output #8 (stored in _8, also as Out[8]):
1736
1746
1737 In [10]: ed _8\\
1747 In [10]: ed _8\\
1738 Editing... done. Executing edited code...\\
1748 Editing... done. Executing edited code...\\
1739 hello again\\
1749 hello again\\
1740 Out[10]: "print 'hello again'\\n"
1750 Out[10]: "print 'hello again'\\n"
1741
1751
1742
1752
1743 Changing the default editor hook:
1753 Changing the default editor hook:
1744
1754
1745 If you wish to write your own editor hook, you can put it in a
1755 If you wish to write your own editor hook, you can put it in a
1746 configuration file which you load at startup time. The default hook
1756 configuration file which you load at startup time. The default hook
1747 is defined in the IPython.hooks module, and you can use that as a
1757 is defined in the IPython.hooks module, and you can use that as a
1748 starting example for further modifications. That file also has
1758 starting example for further modifications. That file also has
1749 general instructions on how to set a new hook for use once you've
1759 general instructions on how to set a new hook for use once you've
1750 defined it."""
1760 defined it."""
1751
1761
1752 # FIXME: This function has become a convoluted mess. It needs a
1762 # FIXME: This function has become a convoluted mess. It needs a
1753 # ground-up rewrite with clean, simple logic.
1763 # ground-up rewrite with clean, simple logic.
1754
1764
1755 def make_filename(arg):
1765 def make_filename(arg):
1756 "Make a filename from the given args"
1766 "Make a filename from the given args"
1757 try:
1767 try:
1758 filename = get_py_filename(arg)
1768 filename = get_py_filename(arg)
1759 except IOError:
1769 except IOError:
1760 if args.endswith('.py'):
1770 if args.endswith('.py'):
1761 filename = arg
1771 filename = arg
1762 else:
1772 else:
1763 filename = None
1773 filename = None
1764 return filename
1774 return filename
1765
1775
1766 # custom exceptions
1776 # custom exceptions
1767 class DataIsObject(Exception): pass
1777 class DataIsObject(Exception): pass
1768
1778
1769 opts,args = self.parse_options(parameter_s,'px')
1779 opts,args = self.parse_options(parameter_s,'px')
1770
1780
1771 # Default line number value
1781 # Default line number value
1772 lineno = None
1782 lineno = None
1773 if opts.has_key('p'):
1783 if opts.has_key('p'):
1774 args = '_%s' % last_call[0]
1784 args = '_%s' % last_call[0]
1775 if not self.shell.user_ns.has_key(args):
1785 if not self.shell.user_ns.has_key(args):
1776 args = last_call[1]
1786 args = last_call[1]
1777
1787
1778 # use last_call to remember the state of the previous call, but don't
1788 # use last_call to remember the state of the previous call, but don't
1779 # let it be clobbered by successive '-p' calls.
1789 # let it be clobbered by successive '-p' calls.
1780 try:
1790 try:
1781 last_call[0] = self.shell.outputcache.prompt_count
1791 last_call[0] = self.shell.outputcache.prompt_count
1782 if not opts.has_key('p'):
1792 if not opts.has_key('p'):
1783 last_call[1] = parameter_s
1793 last_call[1] = parameter_s
1784 except:
1794 except:
1785 pass
1795 pass
1786
1796
1787 # by default this is done with temp files, except when the given
1797 # by default this is done with temp files, except when the given
1788 # arg is a filename
1798 # arg is a filename
1789 use_temp = 1
1799 use_temp = 1
1790
1800
1791 if re.match(r'\d',args):
1801 if re.match(r'\d',args):
1792 # Mode where user specifies ranges of lines, like in %macro.
1802 # Mode where user specifies ranges of lines, like in %macro.
1793 # This means that you can't edit files whose names begin with
1803 # This means that you can't edit files whose names begin with
1794 # numbers this way. Tough.
1804 # numbers this way. Tough.
1795 ranges = args.split()
1805 ranges = args.split()
1796 data = ''.join(self.extract_input_slices(ranges))
1806 data = ''.join(self.extract_input_slices(ranges))
1797 elif args.endswith('.py'):
1807 elif args.endswith('.py'):
1798 filename = make_filename(args)
1808 filename = make_filename(args)
1799 data = ''
1809 data = ''
1800 use_temp = 0
1810 use_temp = 0
1801 elif args:
1811 elif args:
1802 try:
1812 try:
1803 # Load the parameter given as a variable. If not a string,
1813 # Load the parameter given as a variable. If not a string,
1804 # process it as an object instead (below)
1814 # process it as an object instead (below)
1805
1815
1806 #print '*** args',args,'type',type(args) # dbg
1816 #print '*** args',args,'type',type(args) # dbg
1807 data = eval(args,self.shell.user_ns)
1817 data = eval(args,self.shell.user_ns)
1808 if not type(data) in StringTypes:
1818 if not type(data) in StringTypes:
1809 raise DataIsObject
1819 raise DataIsObject
1810 except (NameError,SyntaxError):
1820 except (NameError,SyntaxError):
1811 # given argument is not a variable, try as a filename
1821 # given argument is not a variable, try as a filename
1812 filename = make_filename(args)
1822 filename = make_filename(args)
1813 if filename is None:
1823 if filename is None:
1814 warn("Argument given (%s) can't be found as a variable "
1824 warn("Argument given (%s) can't be found as a variable "
1815 "or as a filename." % args)
1825 "or as a filename." % args)
1816 return
1826 return
1817 data = ''
1827 data = ''
1818 use_temp = 0
1828 use_temp = 0
1819 except DataIsObject:
1829 except DataIsObject:
1820 # For objects, try to edit the file where they are defined
1830 # For objects, try to edit the file where they are defined
1821 try:
1831 try:
1822 filename = inspect.getabsfile(data)
1832 filename = inspect.getabsfile(data)
1823 datafile = 1
1833 datafile = 1
1824 except TypeError:
1834 except TypeError:
1825 filename = make_filename(args)
1835 filename = make_filename(args)
1826 datafile = 1
1836 datafile = 1
1827 warn('Could not find file where `%s` is defined.\n'
1837 warn('Could not find file where `%s` is defined.\n'
1828 'Opening a file named `%s`' % (args,filename))
1838 'Opening a file named `%s`' % (args,filename))
1829 # Now, make sure we can actually read the source (if it was in
1839 # Now, make sure we can actually read the source (if it was in
1830 # a temp file it's gone by now).
1840 # a temp file it's gone by now).
1831 if datafile:
1841 if datafile:
1832 try:
1842 try:
1833 lineno = inspect.getsourcelines(data)[1]
1843 lineno = inspect.getsourcelines(data)[1]
1834 except IOError:
1844 except IOError:
1835 filename = make_filename(args)
1845 filename = make_filename(args)
1836 if filename is None:
1846 if filename is None:
1837 warn('The file `%s` where `%s` was defined cannot '
1847 warn('The file `%s` where `%s` was defined cannot '
1838 'be read.' % (filename,data))
1848 'be read.' % (filename,data))
1839 return
1849 return
1840 use_temp = 0
1850 use_temp = 0
1841 else:
1851 else:
1842 data = ''
1852 data = ''
1843
1853
1844 if use_temp:
1854 if use_temp:
1845 filename = tempfile.mktemp('.py')
1855 filename = tempfile.mktemp('.py')
1846 self.shell.tempfiles.append(filename)
1856 self.shell.tempfiles.append(filename)
1847
1857
1848 if data and use_temp:
1858 if data and use_temp:
1849 tmp_file = open(filename,'w')
1859 tmp_file = open(filename,'w')
1850 tmp_file.write(data)
1860 tmp_file.write(data)
1851 tmp_file.close()
1861 tmp_file.close()
1852
1862
1853 # do actual editing here
1863 # do actual editing here
1854 print 'Editing...',
1864 print 'Editing...',
1855 sys.stdout.flush()
1865 sys.stdout.flush()
1856 self.shell.hooks.editor(filename,lineno)
1866 self.shell.hooks.editor(filename,lineno)
1857 if opts.has_key('x'): # -x prevents actual execution
1867 if opts.has_key('x'): # -x prevents actual execution
1858 print
1868 print
1859 else:
1869 else:
1860 print 'done. Executing edited code...'
1870 print 'done. Executing edited code...'
1861 try:
1871 try:
1862 execfile(filename,self.shell.user_ns)
1872 execfile(filename,self.shell.user_ns)
1863 except IOError,msg:
1873 except IOError,msg:
1864 if msg.filename == filename:
1874 if msg.filename == filename:
1865 warn('File not found. Did you forget to save?')
1875 warn('File not found. Did you forget to save?')
1866 return
1876 return
1867 else:
1877 else:
1868 self.shell.showtraceback()
1878 self.shell.showtraceback()
1869 except:
1879 except:
1870 self.shell.showtraceback()
1880 self.shell.showtraceback()
1871 if use_temp:
1881 if use_temp:
1872 contents = open(filename).read()
1882 contents = open(filename).read()
1873 return contents
1883 return contents
1874
1884
1875 def magic_xmode(self,parameter_s = ''):
1885 def magic_xmode(self,parameter_s = ''):
1876 """Switch modes for the exception handlers.
1886 """Switch modes for the exception handlers.
1877
1887
1878 Valid modes: Plain, Context and Verbose.
1888 Valid modes: Plain, Context and Verbose.
1879
1889
1880 If called without arguments, acts as a toggle."""
1890 If called without arguments, acts as a toggle."""
1881
1891
1882 new_mode = parameter_s.strip().capitalize()
1892 new_mode = parameter_s.strip().capitalize()
1883 try:
1893 try:
1884 self.InteractiveTB.set_mode(mode = new_mode)
1894 self.InteractiveTB.set_mode(mode = new_mode)
1885 print 'Exception reporting mode:',self.InteractiveTB.mode
1895 print 'Exception reporting mode:',self.InteractiveTB.mode
1886 except:
1896 except:
1887 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1897 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1888
1898
1889 def magic_colors(self,parameter_s = ''):
1899 def magic_colors(self,parameter_s = ''):
1890 """Switch color scheme for prompts, info system and exception handlers.
1900 """Switch color scheme for prompts, info system and exception handlers.
1891
1901
1892 Currently implemented schemes: NoColor, Linux, LightBG.
1902 Currently implemented schemes: NoColor, Linux, LightBG.
1893
1903
1894 Color scheme names are not case-sensitive."""
1904 Color scheme names are not case-sensitive."""
1895
1905
1896 new_scheme = parameter_s.strip()
1906 new_scheme = parameter_s.strip()
1897 if not new_scheme:
1907 if not new_scheme:
1898 print 'You must specify a color scheme.'
1908 print 'You must specify a color scheme.'
1899 return
1909 return
1900 # Under Windows, check for Gary Bishop's readline, which is necessary
1910 # Under Windows, check for Gary Bishop's readline, which is necessary
1901 # for ANSI coloring
1911 # for ANSI coloring
1902 if os.name in ['nt','dos']:
1912 if os.name in ['nt','dos']:
1903 try:
1913 try:
1904 import readline
1914 import readline
1905 except ImportError:
1915 except ImportError:
1906 has_readline = 0
1916 has_readline = 0
1907 else:
1917 else:
1908 try:
1918 try:
1909 readline.GetOutputFile()
1919 readline.GetOutputFile()
1910 except AttributeError:
1920 except AttributeError:
1911 has_readline = 0
1921 has_readline = 0
1912 else:
1922 else:
1913 has_readline = 1
1923 has_readline = 1
1914 if not has_readline:
1924 if not has_readline:
1915 msg = """\
1925 msg = """\
1916 Proper color support under MS Windows requires Gary Bishop's readline library.
1926 Proper color support under MS Windows requires Gary Bishop's readline library.
1917 You can find it at:
1927 You can find it at:
1918 http://sourceforge.net/projects/uncpythontools
1928 http://sourceforge.net/projects/uncpythontools
1919 Gary's readline needs the ctypes module, from:
1929 Gary's readline needs the ctypes module, from:
1920 http://starship.python.net/crew/theller/ctypes
1930 http://starship.python.net/crew/theller/ctypes
1921
1931
1922 Defaulting color scheme to 'NoColor'"""
1932 Defaulting color scheme to 'NoColor'"""
1923 new_scheme = 'NoColor'
1933 new_scheme = 'NoColor'
1924 warn(msg)
1934 warn(msg)
1925
1935
1926 # Set prompt colors
1936 # Set prompt colors
1927 try:
1937 try:
1928 self.shell.outputcache.set_colors(new_scheme)
1938 self.shell.outputcache.set_colors(new_scheme)
1929 except:
1939 except:
1930 warn('Error changing prompt color schemes.\n'
1940 warn('Error changing prompt color schemes.\n'
1931 + str(sys.exc_info()[1]))
1941 + str(sys.exc_info()[1]))
1932 else:
1942 else:
1933 self.shell.rc.colors = \
1943 self.shell.rc.colors = \
1934 self.shell.outputcache.color_table.active_scheme_name
1944 self.shell.outputcache.color_table.active_scheme_name
1935 # Set exception colors
1945 # Set exception colors
1936 try:
1946 try:
1937 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1947 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1938 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1948 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1939 except:
1949 except:
1940 warn('Error changing exception color schemes.\n'
1950 warn('Error changing exception color schemes.\n'
1941 + str(sys.exc_info()[1]))
1951 + str(sys.exc_info()[1]))
1942 # Set info (for 'object?') colors
1952 # Set info (for 'object?') colors
1943 if self.shell.rc.color_info:
1953 if self.shell.rc.color_info:
1944 try:
1954 try:
1945 self.shell.inspector.set_active_scheme(new_scheme)
1955 self.shell.inspector.set_active_scheme(new_scheme)
1946 except:
1956 except:
1947 warn('Error changing object inspector color schemes.\n'
1957 warn('Error changing object inspector color schemes.\n'
1948 + str(sys.exc_info()[1]))
1958 + str(sys.exc_info()[1]))
1949 else:
1959 else:
1950 self.shell.inspector.set_active_scheme('NoColor')
1960 self.shell.inspector.set_active_scheme('NoColor')
1951
1961
1952 def magic_color_info(self,parameter_s = ''):
1962 def magic_color_info(self,parameter_s = ''):
1953 """Toggle color_info.
1963 """Toggle color_info.
1954
1964
1955 The color_info configuration parameter controls whether colors are
1965 The color_info configuration parameter controls whether colors are
1956 used for displaying object details (by things like %psource, %pfile or
1966 used for displaying object details (by things like %psource, %pfile or
1957 the '?' system). This function toggles this value with each call.
1967 the '?' system). This function toggles this value with each call.
1958
1968
1959 Note that unless you have a fairly recent pager (less works better
1969 Note that unless you have a fairly recent pager (less works better
1960 than more) in your system, using colored object information displays
1970 than more) in your system, using colored object information displays
1961 will not work properly. Test it and see."""
1971 will not work properly. Test it and see."""
1962
1972
1963 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1973 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1964 self.magic_colors(self.shell.rc.colors)
1974 self.magic_colors(self.shell.rc.colors)
1965 print 'Object introspection functions have now coloring:',
1975 print 'Object introspection functions have now coloring:',
1966 print ['OFF','ON'][self.shell.rc.color_info]
1976 print ['OFF','ON'][self.shell.rc.color_info]
1967
1977
1968 def magic_Pprint(self, parameter_s=''):
1978 def magic_Pprint(self, parameter_s=''):
1969 """Toggle pretty printing on/off."""
1979 """Toggle pretty printing on/off."""
1970
1980
1971 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1981 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1972 print 'Pretty printing has been turned', \
1982 print 'Pretty printing has been turned', \
1973 ['OFF','ON'][self.shell.outputcache.Pprint]
1983 ['OFF','ON'][self.shell.outputcache.Pprint]
1974
1984
1975 def magic_Exit(self, parameter_s=''):
1985 def magic_Exit(self, parameter_s=''):
1976 """Exit IPython without confirmation."""
1986 """Exit IPython without confirmation."""
1977
1987
1978 self.shell.exit_now = True
1988 self.shell.exit_now = True
1979
1989
1980 def magic_Quit(self, parameter_s=''):
1990 def magic_Quit(self, parameter_s=''):
1981 """Exit IPython without confirmation (like %Exit)."""
1991 """Exit IPython without confirmation (like %Exit)."""
1982
1992
1983 self.shell.exit_now = True
1993 self.shell.exit_now = True
1984
1994
1985 #......................................................................
1995 #......................................................................
1986 # Functions to implement unix shell-type things
1996 # Functions to implement unix shell-type things
1987
1997
1988 def magic_alias(self, parameter_s = ''):
1998 def magic_alias(self, parameter_s = ''):
1989 """Define an alias for a system command.
1999 """Define an alias for a system command.
1990
2000
1991 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2001 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1992
2002
1993 Then, typing 'alias_name params' will execute the system command 'cmd
2003 Then, typing 'alias_name params' will execute the system command 'cmd
1994 params' (from your underlying operating system).
2004 params' (from your underlying operating system).
1995
2005
1996 Aliases have lower precedence than magic functions and Python normal
2006 Aliases have lower precedence than magic functions and Python normal
1997 variables, so if 'foo' is both a Python variable and an alias, the
2007 variables, so if 'foo' is both a Python variable and an alias, the
1998 alias can not be executed until 'del foo' removes the Python variable.
2008 alias can not be executed until 'del foo' removes the Python variable.
1999
2009
2000 You can use the %l specifier in an alias definition to represent the
2010 You can use the %l specifier in an alias definition to represent the
2001 whole line when the alias is called. For example:
2011 whole line when the alias is called. For example:
2002
2012
2003 In [2]: alias all echo "Input in brackets: <%l>"\\
2013 In [2]: alias all echo "Input in brackets: <%l>"\\
2004 In [3]: all hello world\\
2014 In [3]: all hello world\\
2005 Input in brackets: <hello world>
2015 Input in brackets: <hello world>
2006
2016
2007 You can also define aliases with parameters using %s specifiers (one
2017 You can also define aliases with parameters using %s specifiers (one
2008 per parameter):
2018 per parameter):
2009
2019
2010 In [1]: alias parts echo first %s second %s\\
2020 In [1]: alias parts echo first %s second %s\\
2011 In [2]: %parts A B\\
2021 In [2]: %parts A B\\
2012 first A second B\\
2022 first A second B\\
2013 In [3]: %parts A\\
2023 In [3]: %parts A\\
2014 Incorrect number of arguments: 2 expected.\\
2024 Incorrect number of arguments: 2 expected.\\
2015 parts is an alias to: 'echo first %s second %s'
2025 parts is an alias to: 'echo first %s second %s'
2016
2026
2017 Note that %l and %s are mutually exclusive. You can only use one or
2027 Note that %l and %s are mutually exclusive. You can only use one or
2018 the other in your aliases.
2028 the other in your aliases.
2019
2029
2020 Aliases expand Python variables just like system calls using ! or !!
2030 Aliases expand Python variables just like system calls using ! or !!
2021 do: all expressions prefixed with '$' get expanded. For details of
2031 do: all expressions prefixed with '$' get expanded. For details of
2022 the semantic rules, see PEP-215:
2032 the semantic rules, see PEP-215:
2023 http://www.python.org/peps/pep-0215.html. This is the library used by
2033 http://www.python.org/peps/pep-0215.html. This is the library used by
2024 IPython for variable expansion. If you want to access a true shell
2034 IPython for variable expansion. If you want to access a true shell
2025 variable, an extra $ is necessary to prevent its expansion by IPython:
2035 variable, an extra $ is necessary to prevent its expansion by IPython:
2026
2036
2027 In [6]: alias show echo\\
2037 In [6]: alias show echo\\
2028 In [7]: PATH='A Python string'\\
2038 In [7]: PATH='A Python string'\\
2029 In [8]: show $PATH\\
2039 In [8]: show $PATH\\
2030 A Python string\\
2040 A Python string\\
2031 In [9]: show $$PATH\\
2041 In [9]: show $$PATH\\
2032 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2042 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2033
2043
2034 You can use the alias facility to acess all of $PATH. See the %rehash
2044 You can use the alias facility to acess all of $PATH. See the %rehash
2035 and %rehashx functions, which automatically create aliases for the
2045 and %rehashx functions, which automatically create aliases for the
2036 contents of your $PATH.
2046 contents of your $PATH.
2037
2047
2038 If called with no parameters, %alias prints the current alias table."""
2048 If called with no parameters, %alias prints the current alias table."""
2039
2049
2040 par = parameter_s.strip()
2050 par = parameter_s.strip()
2041 if not par:
2051 if not par:
2042 if self.shell.rc.automagic:
2052 if self.shell.rc.automagic:
2043 prechar = ''
2053 prechar = ''
2044 else:
2054 else:
2045 prechar = self.shell.ESC_MAGIC
2055 prechar = self.shell.ESC_MAGIC
2046 print 'Alias\t\tSystem Command\n'+'-'*30
2056 print 'Alias\t\tSystem Command\n'+'-'*30
2047 atab = self.shell.alias_table
2057 atab = self.shell.alias_table
2048 aliases = atab.keys()
2058 aliases = atab.keys()
2049 aliases.sort()
2059 aliases.sort()
2050 for alias in aliases:
2060 for alias in aliases:
2051 print prechar+alias+'\t\t'+atab[alias][1]
2061 print prechar+alias+'\t\t'+atab[alias][1]
2052 print '-'*30+'\nTotal number of aliases:',len(aliases)
2062 print '-'*30+'\nTotal number of aliases:',len(aliases)
2053 return
2063 return
2054 try:
2064 try:
2055 alias,cmd = par.split(None,1)
2065 alias,cmd = par.split(None,1)
2056 except:
2066 except:
2057 print OInspect.getdoc(self.magic_alias)
2067 print OInspect.getdoc(self.magic_alias)
2058 else:
2068 else:
2059 nargs = cmd.count('%s')
2069 nargs = cmd.count('%s')
2060 if nargs>0 and cmd.find('%l')>=0:
2070 if nargs>0 and cmd.find('%l')>=0:
2061 error('The %s and %l specifiers are mutually exclusive '
2071 error('The %s and %l specifiers are mutually exclusive '
2062 'in alias definitions.')
2072 'in alias definitions.')
2063 else: # all looks OK
2073 else: # all looks OK
2064 self.shell.alias_table[alias] = (nargs,cmd)
2074 self.shell.alias_table[alias] = (nargs,cmd)
2065 self.shell.alias_table_validate(verbose=1)
2075 self.shell.alias_table_validate(verbose=1)
2066 # end magic_alias
2076 # end magic_alias
2067
2077
2068 def magic_unalias(self, parameter_s = ''):
2078 def magic_unalias(self, parameter_s = ''):
2069 """Remove an alias"""
2079 """Remove an alias"""
2070
2080
2071 aname = parameter_s.strip()
2081 aname = parameter_s.strip()
2072 if aname in self.shell.alias_table:
2082 if aname in self.shell.alias_table:
2073 del self.shell.alias_table[aname]
2083 del self.shell.alias_table[aname]
2074
2084
2075 def magic_rehash(self, parameter_s = ''):
2085 def magic_rehash(self, parameter_s = ''):
2076 """Update the alias table with all entries in $PATH.
2086 """Update the alias table with all entries in $PATH.
2077
2087
2078 This version does no checks on execute permissions or whether the
2088 This version does no checks on execute permissions or whether the
2079 contents of $PATH are truly files (instead of directories or something
2089 contents of $PATH are truly files (instead of directories or something
2080 else). For such a safer (but slower) version, use %rehashx."""
2090 else). For such a safer (but slower) version, use %rehashx."""
2081
2091
2082 # This function (and rehashx) manipulate the alias_table directly
2092 # This function (and rehashx) manipulate the alias_table directly
2083 # rather than calling magic_alias, for speed reasons. A rehash on a
2093 # rather than calling magic_alias, for speed reasons. A rehash on a
2084 # typical Linux box involves several thousand entries, so efficiency
2094 # typical Linux box involves several thousand entries, so efficiency
2085 # here is a top concern.
2095 # here is a top concern.
2086
2096
2087 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2097 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2088 alias_table = self.shell.alias_table
2098 alias_table = self.shell.alias_table
2089 for pdir in path:
2099 for pdir in path:
2090 for ff in os.listdir(pdir):
2100 for ff in os.listdir(pdir):
2091 # each entry in the alias table must be (N,name), where
2101 # each entry in the alias table must be (N,name), where
2092 # N is the number of positional arguments of the alias.
2102 # N is the number of positional arguments of the alias.
2093 alias_table[ff] = (0,ff)
2103 alias_table[ff] = (0,ff)
2094 # Make sure the alias table doesn't contain keywords or builtins
2104 # Make sure the alias table doesn't contain keywords or builtins
2095 self.shell.alias_table_validate()
2105 self.shell.alias_table_validate()
2096 # Call again init_auto_alias() so we get 'rm -i' and other modified
2106 # Call again init_auto_alias() so we get 'rm -i' and other modified
2097 # aliases since %rehash will probably clobber them
2107 # aliases since %rehash will probably clobber them
2098 self.shell.init_auto_alias()
2108 self.shell.init_auto_alias()
2099
2109
2100 def magic_rehashx(self, parameter_s = ''):
2110 def magic_rehashx(self, parameter_s = ''):
2101 """Update the alias table with all executable files in $PATH.
2111 """Update the alias table with all executable files in $PATH.
2102
2112
2103 This version explicitly checks that every entry in $PATH is a file
2113 This version explicitly checks that every entry in $PATH is a file
2104 with execute access (os.X_OK), so it is much slower than %rehash.
2114 with execute access (os.X_OK), so it is much slower than %rehash.
2105
2115
2106 Under Windows, it checks executability as a match agains a
2116 Under Windows, it checks executability as a match agains a
2107 '|'-separated string of extensions, stored in the IPython config
2117 '|'-separated string of extensions, stored in the IPython config
2108 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2118 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2109
2119
2110 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2120 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2111 alias_table = self.shell.alias_table
2121 alias_table = self.shell.alias_table
2112
2122
2113 if os.name == 'posix':
2123 if os.name == 'posix':
2114 isexec = lambda fname:os.path.isfile(fname) and \
2124 isexec = lambda fname:os.path.isfile(fname) and \
2115 os.access(fname,os.X_OK)
2125 os.access(fname,os.X_OK)
2116 else:
2126 else:
2117
2127
2118 try:
2128 try:
2119 winext = os.environ['pathext'].replace(';','|').replace('.','')
2129 winext = os.environ['pathext'].replace(';','|').replace('.','')
2120 except KeyError:
2130 except KeyError:
2121 winext = 'exe|com|bat'
2131 winext = 'exe|com|bat'
2122
2132
2123 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2133 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2124 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2134 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2125 savedir = os.getcwd()
2135 savedir = os.getcwd()
2126 try:
2136 try:
2127 # write the whole loop for posix/Windows so we don't have an if in
2137 # write the whole loop for posix/Windows so we don't have an if in
2128 # the innermost part
2138 # the innermost part
2129 if os.name == 'posix':
2139 if os.name == 'posix':
2130 for pdir in path:
2140 for pdir in path:
2131 os.chdir(pdir)
2141 os.chdir(pdir)
2132 for ff in os.listdir(pdir):
2142 for ff in os.listdir(pdir):
2133 if isexec(ff):
2143 if isexec(ff):
2134 # each entry in the alias table must be (N,name),
2144 # each entry in the alias table must be (N,name),
2135 # where N is the number of positional arguments of the
2145 # where N is the number of positional arguments of the
2136 # alias.
2146 # alias.
2137 alias_table[ff] = (0,ff)
2147 alias_table[ff] = (0,ff)
2138 else:
2148 else:
2139 for pdir in path:
2149 for pdir in path:
2140 os.chdir(pdir)
2150 os.chdir(pdir)
2141 for ff in os.listdir(pdir):
2151 for ff in os.listdir(pdir):
2142 if isexec(ff):
2152 if isexec(ff):
2143 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2153 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2144 # Make sure the alias table doesn't contain keywords or builtins
2154 # Make sure the alias table doesn't contain keywords or builtins
2145 self.shell.alias_table_validate()
2155 self.shell.alias_table_validate()
2146 # Call again init_auto_alias() so we get 'rm -i' and other
2156 # Call again init_auto_alias() so we get 'rm -i' and other
2147 # modified aliases since %rehashx will probably clobber them
2157 # modified aliases since %rehashx will probably clobber them
2148 self.shell.init_auto_alias()
2158 self.shell.init_auto_alias()
2149 finally:
2159 finally:
2150 os.chdir(savedir)
2160 os.chdir(savedir)
2151
2161
2152 def magic_pwd(self, parameter_s = ''):
2162 def magic_pwd(self, parameter_s = ''):
2153 """Return the current working directory path."""
2163 """Return the current working directory path."""
2154 return os.getcwd()
2164 return os.getcwd()
2155
2165
2156 def magic_cd(self, parameter_s=''):
2166 def magic_cd(self, parameter_s=''):
2157 """Change the current working directory.
2167 """Change the current working directory.
2158
2168
2159 This command automatically maintains an internal list of directories
2169 This command automatically maintains an internal list of directories
2160 you visit during your IPython session, in the variable _dh. The
2170 you visit during your IPython session, in the variable _dh. The
2161 command %dhist shows this history nicely formatted.
2171 command %dhist shows this history nicely formatted.
2162
2172
2163 Usage:
2173 Usage:
2164
2174
2165 cd 'dir': changes to directory 'dir'.
2175 cd 'dir': changes to directory 'dir'.
2166
2176
2167 cd -: changes to the last visited directory.
2177 cd -: changes to the last visited directory.
2168
2178
2169 cd -<n>: changes to the n-th directory in the directory history.
2179 cd -<n>: changes to the n-th directory in the directory history.
2170
2180
2171 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2181 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2172 (note: cd <bookmark_name> is enough if there is no
2182 (note: cd <bookmark_name> is enough if there is no
2173 directory <bookmark_name>, but a bookmark with the name exists.)
2183 directory <bookmark_name>, but a bookmark with the name exists.)
2174
2184
2175 Options:
2185 Options:
2176
2186
2177 -q: quiet. Do not print the working directory after the cd command is
2187 -q: quiet. Do not print the working directory after the cd command is
2178 executed. By default IPython's cd command does print this directory,
2188 executed. By default IPython's cd command does print this directory,
2179 since the default prompts do not display path information.
2189 since the default prompts do not display path information.
2180
2190
2181 Note that !cd doesn't work for this purpose because the shell where
2191 Note that !cd doesn't work for this purpose because the shell where
2182 !command runs is immediately discarded after executing 'command'."""
2192 !command runs is immediately discarded after executing 'command'."""
2183
2193
2184 parameter_s = parameter_s.strip()
2194 parameter_s = parameter_s.strip()
2185 bkms = self.shell.persist.get("bookmarks",{})
2195 bkms = self.shell.persist.get("bookmarks",{})
2186
2196
2187 numcd = re.match(r'(-)(\d+)$',parameter_s)
2197 numcd = re.match(r'(-)(\d+)$',parameter_s)
2188 # jump in directory history by number
2198 # jump in directory history by number
2189 if numcd:
2199 if numcd:
2190 nn = int(numcd.group(2))
2200 nn = int(numcd.group(2))
2191 try:
2201 try:
2192 ps = self.shell.user_ns['_dh'][nn]
2202 ps = self.shell.user_ns['_dh'][nn]
2193 except IndexError:
2203 except IndexError:
2194 print 'The requested directory does not exist in history.'
2204 print 'The requested directory does not exist in history.'
2195 return
2205 return
2196 else:
2206 else:
2197 opts = {}
2207 opts = {}
2198 else:
2208 else:
2199 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2209 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2200 # jump to previous
2210 # jump to previous
2201 if ps == '-':
2211 if ps == '-':
2202 try:
2212 try:
2203 ps = self.shell.user_ns['_dh'][-2]
2213 ps = self.shell.user_ns['_dh'][-2]
2204 except IndexError:
2214 except IndexError:
2205 print 'No previous directory to change to.'
2215 print 'No previous directory to change to.'
2206 return
2216 return
2207 # jump to bookmark
2217 # jump to bookmark
2208 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2218 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2209 if bkms.has_key(ps):
2219 if bkms.has_key(ps):
2210 target = bkms[ps]
2220 target = bkms[ps]
2211 print '(bookmark:%s) -> %s' % (ps,target)
2221 print '(bookmark:%s) -> %s' % (ps,target)
2212 ps = target
2222 ps = target
2213 else:
2223 else:
2214 if bkms:
2224 if bkms:
2215 error("Bookmark '%s' not found. "
2225 error("Bookmark '%s' not found. "
2216 "Use '%bookmark -l' to see your bookmarks." % ps)
2226 "Use '%bookmark -l' to see your bookmarks." % ps)
2217 else:
2227 else:
2218 print "Bookmarks not set - use %bookmark <bookmarkname>"
2228 print "Bookmarks not set - use %bookmark <bookmarkname>"
2219 return
2229 return
2220
2230
2221 # at this point ps should point to the target dir
2231 # at this point ps should point to the target dir
2222 if ps:
2232 if ps:
2223 try:
2233 try:
2224 os.chdir(os.path.expanduser(ps))
2234 os.chdir(os.path.expanduser(ps))
2225 except OSError:
2235 except OSError:
2226 print sys.exc_info()[1]
2236 print sys.exc_info()[1]
2227 else:
2237 else:
2228 self.shell.user_ns['_dh'].append(os.getcwd())
2238 self.shell.user_ns['_dh'].append(os.getcwd())
2229 else:
2239 else:
2230 os.chdir(self.home_dir)
2240 os.chdir(self.home_dir)
2231 self.shell.user_ns['_dh'].append(os.getcwd())
2241 self.shell.user_ns['_dh'].append(os.getcwd())
2232 if not 'q' in opts:
2242 if not 'q' in opts:
2233 print self.shell.user_ns['_dh'][-1]
2243 print self.shell.user_ns['_dh'][-1]
2234
2244
2235 def magic_dhist(self, parameter_s=''):
2245 def magic_dhist(self, parameter_s=''):
2236 """Print your history of visited directories.
2246 """Print your history of visited directories.
2237
2247
2238 %dhist -> print full history\\
2248 %dhist -> print full history\\
2239 %dhist n -> print last n entries only\\
2249 %dhist n -> print last n entries only\\
2240 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2250 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2241
2251
2242 This history is automatically maintained by the %cd command, and
2252 This history is automatically maintained by the %cd command, and
2243 always available as the global list variable _dh. You can use %cd -<n>
2253 always available as the global list variable _dh. You can use %cd -<n>
2244 to go to directory number <n>."""
2254 to go to directory number <n>."""
2245
2255
2246 dh = self.shell.user_ns['_dh']
2256 dh = self.shell.user_ns['_dh']
2247 if parameter_s:
2257 if parameter_s:
2248 try:
2258 try:
2249 args = map(int,parameter_s.split())
2259 args = map(int,parameter_s.split())
2250 except:
2260 except:
2251 self.arg_err(Magic.magic_dhist)
2261 self.arg_err(Magic.magic_dhist)
2252 return
2262 return
2253 if len(args) == 1:
2263 if len(args) == 1:
2254 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2264 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2255 elif len(args) == 2:
2265 elif len(args) == 2:
2256 ini,fin = args
2266 ini,fin = args
2257 else:
2267 else:
2258 self.arg_err(Magic.magic_dhist)
2268 self.arg_err(Magic.magic_dhist)
2259 return
2269 return
2260 else:
2270 else:
2261 ini,fin = 0,len(dh)
2271 ini,fin = 0,len(dh)
2262 nlprint(dh,
2272 nlprint(dh,
2263 header = 'Directory history (kept in _dh)',
2273 header = 'Directory history (kept in _dh)',
2264 start=ini,stop=fin)
2274 start=ini,stop=fin)
2265
2275
2266 def magic_env(self, parameter_s=''):
2276 def magic_env(self, parameter_s=''):
2267 """List environment variables."""
2277 """List environment variables."""
2268
2278
2269 # environ is an instance of UserDict
2279 # environ is an instance of UserDict
2270 return os.environ.data
2280 return os.environ.data
2271
2281
2272 def magic_pushd(self, parameter_s=''):
2282 def magic_pushd(self, parameter_s=''):
2273 """Place the current dir on stack and change directory.
2283 """Place the current dir on stack and change directory.
2274
2284
2275 Usage:\\
2285 Usage:\\
2276 %pushd ['dirname']
2286 %pushd ['dirname']
2277
2287
2278 %pushd with no arguments does a %pushd to your home directory.
2288 %pushd with no arguments does a %pushd to your home directory.
2279 """
2289 """
2280 if parameter_s == '': parameter_s = '~'
2290 if parameter_s == '': parameter_s = '~'
2281 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2291 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2282 os.path.expanduser(self.dir_stack[0]):
2292 os.path.expanduser(self.dir_stack[0]):
2283 try:
2293 try:
2284 self.magic_cd(parameter_s)
2294 self.magic_cd(parameter_s)
2285 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2295 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2286 self.magic_dirs()
2296 self.magic_dirs()
2287 except:
2297 except:
2288 print 'Invalid directory'
2298 print 'Invalid directory'
2289 else:
2299 else:
2290 print 'You are already there!'
2300 print 'You are already there!'
2291
2301
2292 def magic_popd(self, parameter_s=''):
2302 def magic_popd(self, parameter_s=''):
2293 """Change to directory popped off the top of the stack.
2303 """Change to directory popped off the top of the stack.
2294 """
2304 """
2295 if len (self.dir_stack) > 1:
2305 if len (self.dir_stack) > 1:
2296 self.dir_stack.pop(0)
2306 self.dir_stack.pop(0)
2297 self.magic_cd(self.dir_stack[0])
2307 self.magic_cd(self.dir_stack[0])
2298 print self.dir_stack[0]
2308 print self.dir_stack[0]
2299 else:
2309 else:
2300 print "You can't remove the starting directory from the stack:",\
2310 print "You can't remove the starting directory from the stack:",\
2301 self.dir_stack
2311 self.dir_stack
2302
2312
2303 def magic_dirs(self, parameter_s=''):
2313 def magic_dirs(self, parameter_s=''):
2304 """Return the current directory stack."""
2314 """Return the current directory stack."""
2305
2315
2306 return self.dir_stack[:]
2316 return self.dir_stack[:]
2307
2317
2308 def magic_sc(self, parameter_s=''):
2318 def magic_sc(self, parameter_s=''):
2309 """Shell capture - execute a shell command and capture its output.
2319 """Shell capture - execute a shell command and capture its output.
2310
2320
2311 %sc [options] varname=command
2321 %sc [options] varname=command
2312
2322
2313 IPython will run the given command using commands.getoutput(), and
2323 IPython will run the given command using commands.getoutput(), and
2314 will then update the user's interactive namespace with a variable
2324 will then update the user's interactive namespace with a variable
2315 called varname, containing the value of the call. Your command can
2325 called varname, containing the value of the call. Your command can
2316 contain shell wildcards, pipes, etc.
2326 contain shell wildcards, pipes, etc.
2317
2327
2318 The '=' sign in the syntax is mandatory, and the variable name you
2328 The '=' sign in the syntax is mandatory, and the variable name you
2319 supply must follow Python's standard conventions for valid names.
2329 supply must follow Python's standard conventions for valid names.
2320
2330
2321 Options:
2331 Options:
2322
2332
2323 -l: list output. Split the output on newlines into a list before
2333 -l: list output. Split the output on newlines into a list before
2324 assigning it to the given variable. By default the output is stored
2334 assigning it to the given variable. By default the output is stored
2325 as a single string.
2335 as a single string.
2326
2336
2327 -v: verbose. Print the contents of the variable.
2337 -v: verbose. Print the contents of the variable.
2328
2338
2329 In most cases you should not need to split as a list, because the
2339 In most cases you should not need to split as a list, because the
2330 returned value is a special type of string which can automatically
2340 returned value is a special type of string which can automatically
2331 provide its contents either as a list (split on newlines) or as a
2341 provide its contents either as a list (split on newlines) or as a
2332 space-separated string. These are convenient, respectively, either
2342 space-separated string. These are convenient, respectively, either
2333 for sequential processing or to be passed to a shell command.
2343 for sequential processing or to be passed to a shell command.
2334
2344
2335 For example:
2345 For example:
2336
2346
2337 # Capture into variable a
2347 # Capture into variable a
2338 In [9]: sc a=ls *py
2348 In [9]: sc a=ls *py
2339
2349
2340 # a is a string with embedded newlines
2350 # a is a string with embedded newlines
2341 In [10]: a
2351 In [10]: a
2342 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2352 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2343
2353
2344 # which can be seen as a list:
2354 # which can be seen as a list:
2345 In [11]: a.l
2355 In [11]: a.l
2346 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2356 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2347
2357
2348 # or as a whitespace-separated string:
2358 # or as a whitespace-separated string:
2349 In [12]: a.s
2359 In [12]: a.s
2350 Out[12]: 'setup.py win32_manual_post_install.py'
2360 Out[12]: 'setup.py win32_manual_post_install.py'
2351
2361
2352 # a.s is useful to pass as a single command line:
2362 # a.s is useful to pass as a single command line:
2353 In [13]: !wc -l $a.s
2363 In [13]: !wc -l $a.s
2354 146 setup.py
2364 146 setup.py
2355 130 win32_manual_post_install.py
2365 130 win32_manual_post_install.py
2356 276 total
2366 276 total
2357
2367
2358 # while the list form is useful to loop over:
2368 # while the list form is useful to loop over:
2359 In [14]: for f in a.l:
2369 In [14]: for f in a.l:
2360 ....: !wc -l $f
2370 ....: !wc -l $f
2361 ....:
2371 ....:
2362 146 setup.py
2372 146 setup.py
2363 130 win32_manual_post_install.py
2373 130 win32_manual_post_install.py
2364
2374
2365 Similiarly, the lists returned by the -l option are also special, in
2375 Similiarly, the lists returned by the -l option are also special, in
2366 the sense that you can equally invoke the .s attribute on them to
2376 the sense that you can equally invoke the .s attribute on them to
2367 automatically get a whitespace-separated string from their contents:
2377 automatically get a whitespace-separated string from their contents:
2368
2378
2369 In [1]: sc -l b=ls *py
2379 In [1]: sc -l b=ls *py
2370
2380
2371 In [2]: b
2381 In [2]: b
2372 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2382 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2373
2383
2374 In [3]: b.s
2384 In [3]: b.s
2375 Out[3]: 'setup.py win32_manual_post_install.py'
2385 Out[3]: 'setup.py win32_manual_post_install.py'
2376
2386
2377 In summary, both the lists and strings used for ouptut capture have
2387 In summary, both the lists and strings used for ouptut capture have
2378 the following special attributes:
2388 the following special attributes:
2379
2389
2380 .l (or .list) : value as list.
2390 .l (or .list) : value as list.
2381 .n (or .nlstr): value as newline-separated string.
2391 .n (or .nlstr): value as newline-separated string.
2382 .s (or .spstr): value as space-separated string.
2392 .s (or .spstr): value as space-separated string.
2383 """
2393 """
2384
2394
2385 opts,args = self.parse_options(parameter_s,'lv')
2395 opts,args = self.parse_options(parameter_s,'lv')
2386 # Try to get a variable name and command to run
2396 # Try to get a variable name and command to run
2387 try:
2397 try:
2388 # the variable name must be obtained from the parse_options
2398 # the variable name must be obtained from the parse_options
2389 # output, which uses shlex.split to strip options out.
2399 # output, which uses shlex.split to strip options out.
2390 var,_ = args.split('=',1)
2400 var,_ = args.split('=',1)
2391 var = var.strip()
2401 var = var.strip()
2392 # But the the command has to be extracted from the original input
2402 # But the the command has to be extracted from the original input
2393 # parameter_s, not on what parse_options returns, to avoid the
2403 # parameter_s, not on what parse_options returns, to avoid the
2394 # quote stripping which shlex.split performs on it.
2404 # quote stripping which shlex.split performs on it.
2395 _,cmd = parameter_s.split('=',1)
2405 _,cmd = parameter_s.split('=',1)
2396 except ValueError:
2406 except ValueError:
2397 var,cmd = '',''
2407 var,cmd = '',''
2398 if not var:
2408 if not var:
2399 error('you must specify a variable to assign the command to.')
2409 error('you must specify a variable to assign the command to.')
2400 return
2410 return
2401 # If all looks ok, proceed
2411 # If all looks ok, proceed
2402 out,err = self.shell.getoutputerror(cmd)
2412 out,err = self.shell.getoutputerror(cmd)
2403 if err:
2413 if err:
2404 print >> Term.cerr,err
2414 print >> Term.cerr,err
2405 if opts.has_key('l'):
2415 if opts.has_key('l'):
2406 out = SList(out.split('\n'))
2416 out = SList(out.split('\n'))
2407 else:
2417 else:
2408 out = LSString(out)
2418 out = LSString(out)
2409 if opts.has_key('v'):
2419 if opts.has_key('v'):
2410 print '%s ==\n%s' % (var,pformat(out))
2420 print '%s ==\n%s' % (var,pformat(out))
2411 self.shell.user_ns.update({var:out})
2421 self.shell.user_ns.update({var:out})
2412
2422
2413 def magic_sx(self, parameter_s=''):
2423 def magic_sx(self, parameter_s=''):
2414 """Shell execute - run a shell command and capture its output.
2424 """Shell execute - run a shell command and capture its output.
2415
2425
2416 %sx command
2426 %sx command
2417
2427
2418 IPython will run the given command using commands.getoutput(), and
2428 IPython will run the given command using commands.getoutput(), and
2419 return the result formatted as a list (split on '\\n'). Since the
2429 return the result formatted as a list (split on '\\n'). Since the
2420 output is _returned_, it will be stored in ipython's regular output
2430 output is _returned_, it will be stored in ipython's regular output
2421 cache Out[N] and in the '_N' automatic variables.
2431 cache Out[N] and in the '_N' automatic variables.
2422
2432
2423 Notes:
2433 Notes:
2424
2434
2425 1) If an input line begins with '!!', then %sx is automatically
2435 1) If an input line begins with '!!', then %sx is automatically
2426 invoked. That is, while:
2436 invoked. That is, while:
2427 !ls
2437 !ls
2428 causes ipython to simply issue system('ls'), typing
2438 causes ipython to simply issue system('ls'), typing
2429 !!ls
2439 !!ls
2430 is a shorthand equivalent to:
2440 is a shorthand equivalent to:
2431 %sx ls
2441 %sx ls
2432
2442
2433 2) %sx differs from %sc in that %sx automatically splits into a list,
2443 2) %sx differs from %sc in that %sx automatically splits into a list,
2434 like '%sc -l'. The reason for this is to make it as easy as possible
2444 like '%sc -l'. The reason for this is to make it as easy as possible
2435 to process line-oriented shell output via further python commands.
2445 to process line-oriented shell output via further python commands.
2436 %sc is meant to provide much finer control, but requires more
2446 %sc is meant to provide much finer control, but requires more
2437 typing.
2447 typing.
2438
2448
2439 3) Just like %sc -l, this is a list with special attributes:
2449 3) Just like %sc -l, this is a list with special attributes:
2440
2450
2441 .l (or .list) : value as list.
2451 .l (or .list) : value as list.
2442 .n (or .nlstr): value as newline-separated string.
2452 .n (or .nlstr): value as newline-separated string.
2443 .s (or .spstr): value as whitespace-separated string.
2453 .s (or .spstr): value as whitespace-separated string.
2444
2454
2445 This is very useful when trying to use such lists as arguments to
2455 This is very useful when trying to use such lists as arguments to
2446 system commands."""
2456 system commands."""
2447
2457
2448 if parameter_s:
2458 if parameter_s:
2449 out,err = self.shell.getoutputerror(parameter_s)
2459 out,err = self.shell.getoutputerror(parameter_s)
2450 if err:
2460 if err:
2451 print >> Term.cerr,err
2461 print >> Term.cerr,err
2452 return SList(out.split('\n'))
2462 return SList(out.split('\n'))
2453
2463
2454 def magic_bg(self, parameter_s=''):
2464 def magic_bg(self, parameter_s=''):
2455 """Run a job in the background, in a separate thread.
2465 """Run a job in the background, in a separate thread.
2456
2466
2457 For example,
2467 For example,
2458
2468
2459 %bg myfunc(x,y,z=1)
2469 %bg myfunc(x,y,z=1)
2460
2470
2461 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2471 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2462 execution starts, a message will be printed indicating the job
2472 execution starts, a message will be printed indicating the job
2463 number. If your job number is 5, you can use
2473 number. If your job number is 5, you can use
2464
2474
2465 myvar = jobs.result(5) or myvar = jobs[5].result
2475 myvar = jobs.result(5) or myvar = jobs[5].result
2466
2476
2467 to assign this result to variable 'myvar'.
2477 to assign this result to variable 'myvar'.
2468
2478
2469 IPython has a job manager, accessible via the 'jobs' object. You can
2479 IPython has a job manager, accessible via the 'jobs' object. You can
2470 type jobs? to get more information about it, and use jobs.<TAB> to see
2480 type jobs? to get more information about it, and use jobs.<TAB> to see
2471 its attributes. All attributes not starting with an underscore are
2481 its attributes. All attributes not starting with an underscore are
2472 meant for public use.
2482 meant for public use.
2473
2483
2474 In particular, look at the jobs.new() method, which is used to create
2484 In particular, look at the jobs.new() method, which is used to create
2475 new jobs. This magic %bg function is just a convenience wrapper
2485 new jobs. This magic %bg function is just a convenience wrapper
2476 around jobs.new(), for expression-based jobs. If you want to create a
2486 around jobs.new(), for expression-based jobs. If you want to create a
2477 new job with an explicit function object and arguments, you must call
2487 new job with an explicit function object and arguments, you must call
2478 jobs.new() directly.
2488 jobs.new() directly.
2479
2489
2480 The jobs.new docstring also describes in detail several important
2490 The jobs.new docstring also describes in detail several important
2481 caveats associated with a thread-based model for background job
2491 caveats associated with a thread-based model for background job
2482 execution. Type jobs.new? for details.
2492 execution. Type jobs.new? for details.
2483
2493
2484 You can check the status of all jobs with jobs.status().
2494 You can check the status of all jobs with jobs.status().
2485
2495
2486 The jobs variable is set by IPython into the Python builtin namespace.
2496 The jobs variable is set by IPython into the Python builtin namespace.
2487 If you ever declare a variable named 'jobs', you will shadow this
2497 If you ever declare a variable named 'jobs', you will shadow this
2488 name. You can either delete your global jobs variable to regain
2498 name. You can either delete your global jobs variable to regain
2489 access to the job manager, or make a new name and assign it manually
2499 access to the job manager, or make a new name and assign it manually
2490 to the manager (stored in IPython's namespace). For example, to
2500 to the manager (stored in IPython's namespace). For example, to
2491 assign the job manager to the Jobs name, use:
2501 assign the job manager to the Jobs name, use:
2492
2502
2493 Jobs = __builtins__.jobs"""
2503 Jobs = __builtins__.jobs"""
2494
2504
2495 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2505 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2496
2506
2497 def magic_bookmark(self, parameter_s=''):
2507 def magic_bookmark(self, parameter_s=''):
2498 """Manage IPython's bookmark system.
2508 """Manage IPython's bookmark system.
2499
2509
2500 %bookmark <name> - set bookmark to current dir
2510 %bookmark <name> - set bookmark to current dir
2501 %bookmark <name> <dir> - set bookmark to <dir>
2511 %bookmark <name> <dir> - set bookmark to <dir>
2502 %bookmark -l - list all bookmarks
2512 %bookmark -l - list all bookmarks
2503 %bookmark -d <name> - remove bookmark
2513 %bookmark -d <name> - remove bookmark
2504 %bookmark -r - remove all bookmarks
2514 %bookmark -r - remove all bookmarks
2505
2515
2506 You can later on access a bookmarked folder with:
2516 You can later on access a bookmarked folder with:
2507 %cd -b <name>
2517 %cd -b <name>
2508 or simply '%cd <name>' if there is no directory called <name> AND
2518 or simply '%cd <name>' if there is no directory called <name> AND
2509 there is such a bookmark defined.
2519 there is such a bookmark defined.
2510
2520
2511 Your bookmarks persist through IPython sessions, but they are
2521 Your bookmarks persist through IPython sessions, but they are
2512 associated with each profile."""
2522 associated with each profile."""
2513
2523
2514 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2524 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2515 if len(args) > 2:
2525 if len(args) > 2:
2516 error('You can only give at most two arguments')
2526 error('You can only give at most two arguments')
2517 return
2527 return
2518
2528
2519 bkms = self.shell.persist.get('bookmarks',{})
2529 bkms = self.shell.persist.get('bookmarks',{})
2520
2530
2521 if opts.has_key('d'):
2531 if opts.has_key('d'):
2522 try:
2532 try:
2523 todel = args[0]
2533 todel = args[0]
2524 except IndexError:
2534 except IndexError:
2525 error('You must provide a bookmark to delete')
2535 error('You must provide a bookmark to delete')
2526 else:
2536 else:
2527 try:
2537 try:
2528 del bkms[todel]
2538 del bkms[todel]
2529 except:
2539 except:
2530 error("Can't delete bookmark '%s'" % todel)
2540 error("Can't delete bookmark '%s'" % todel)
2531 elif opts.has_key('r'):
2541 elif opts.has_key('r'):
2532 bkms = {}
2542 bkms = {}
2533 elif opts.has_key('l'):
2543 elif opts.has_key('l'):
2534 bks = bkms.keys()
2544 bks = bkms.keys()
2535 bks.sort()
2545 bks.sort()
2536 if bks:
2546 if bks:
2537 size = max(map(len,bks))
2547 size = max(map(len,bks))
2538 else:
2548 else:
2539 size = 0
2549 size = 0
2540 fmt = '%-'+str(size)+'s -> %s'
2550 fmt = '%-'+str(size)+'s -> %s'
2541 print 'Current bookmarks:'
2551 print 'Current bookmarks:'
2542 for bk in bks:
2552 for bk in bks:
2543 print fmt % (bk,bkms[bk])
2553 print fmt % (bk,bkms[bk])
2544 else:
2554 else:
2545 if not args:
2555 if not args:
2546 error("You must specify the bookmark name")
2556 error("You must specify the bookmark name")
2547 elif len(args)==1:
2557 elif len(args)==1:
2548 bkms[args[0]] = os.getcwd()
2558 bkms[args[0]] = os.getcwd()
2549 elif len(args)==2:
2559 elif len(args)==2:
2550 bkms[args[0]] = args[1]
2560 bkms[args[0]] = args[1]
2551 self.persist['bookmarks'] = bkms
2561 self.persist['bookmarks'] = bkms
2552
2562
2553 def magic_pycat(self, parameter_s=''):
2563 def magic_pycat(self, parameter_s=''):
2554 """Show a syntax-highlighted file through a pager.
2564 """Show a syntax-highlighted file through a pager.
2555
2565
2556 This magic is similar to the cat utility, but it will assume the file
2566 This magic is similar to the cat utility, but it will assume the file
2557 to be Python source and will show it with syntax highlighting. """
2567 to be Python source and will show it with syntax highlighting. """
2558
2568
2559 filename = get_py_filename(parameter_s)
2569 filename = get_py_filename(parameter_s)
2560 page(self.shell.colorize(file_read(filename)),
2570 page(self.shell.colorize(file_read(filename)),
2561 screen_lines=self.shell.rc.screen_length)
2571 screen_lines=self.shell.rc.screen_length)
2562
2572
2563 # end Magic
2573 # end Magic
@@ -1,572 +1,574 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 638 2005-07-18 03:01:41Z fperez $"""
5 $Id: Prompts.py 951 2005-12-25 00:57:24Z fperez $"""
6
6
7 #*****************************************************************************
7 #*****************************************************************************
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 from IPython import Release
14 from IPython import Release
15 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 __license__ = Release.license
16 __license__ = Release.license
17 __version__ = Release.version
17 __version__ = Release.version
18
18
19 #****************************************************************************
19 #****************************************************************************
20 # Required modules
20 # Required modules
21 import __builtin__
21 import __builtin__
22 import os,sys,socket
22 import os,sys,socket
23 import time
23 import time
24 from pprint import pprint,pformat
24 from pprint import pprint,pformat
25
25
26 # IPython's own
26 # IPython's own
27 from IPython.genutils import *
27 from IPython.genutils import *
28 from IPython.Struct import Struct
28 from IPython.Struct import Struct
29 from IPython.Magic import Macro
29 from IPython.Magic import Macro
30 from IPython.Itpl import ItplNS
30 from IPython.Itpl import ItplNS
31 from IPython import ColorANSI
31 from IPython import ColorANSI
32
32
33 #****************************************************************************
33 #****************************************************************************
34 #Color schemes for Prompts.
34 #Color schemes for Prompts.
35
35
36 PromptColors = ColorANSI.ColorSchemeTable()
36 PromptColors = ColorANSI.ColorSchemeTable()
37 InputColors = ColorANSI.InputTermColors # just a shorthand
37 InputColors = ColorANSI.InputTermColors # just a shorthand
38 Colors = ColorANSI.TermColors # just a shorthand
38 Colors = ColorANSI.TermColors # just a shorthand
39
39
40 PromptColors.add_scheme(ColorANSI.ColorScheme(
40 PromptColors.add_scheme(ColorANSI.ColorScheme(
41 'NoColor',
41 'NoColor',
42 in_prompt = InputColors.NoColor, # Input prompt
42 in_prompt = InputColors.NoColor, # Input prompt
43 in_number = InputColors.NoColor, # Input prompt number
43 in_number = InputColors.NoColor, # Input prompt number
44 in_prompt2 = InputColors.NoColor, # Continuation prompt
44 in_prompt2 = InputColors.NoColor, # Continuation prompt
45 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
45 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
46
46
47 out_prompt = Colors.NoColor, # Output prompt
47 out_prompt = Colors.NoColor, # Output prompt
48 out_number = Colors.NoColor, # Output prompt number
48 out_number = Colors.NoColor, # Output prompt number
49
49
50 normal = Colors.NoColor # color off (usu. Colors.Normal)
50 normal = Colors.NoColor # color off (usu. Colors.Normal)
51 ))
51 ))
52
52 # make some schemes as instances so we can copy them for modification easily:
53 # make some schemes as instances so we can copy them for modification easily:
53 __PColLinux = ColorANSI.ColorScheme(
54 __PColLinux = ColorANSI.ColorScheme(
54 'Linux',
55 'Linux',
55 in_prompt = InputColors.Green,
56 in_prompt = InputColors.Green,
56 in_number = InputColors.LightGreen,
57 in_number = InputColors.LightGreen,
57 in_prompt2 = InputColors.Green,
58 in_prompt2 = InputColors.Green,
58 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
59 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
59
60
60 out_prompt = Colors.Red,
61 out_prompt = Colors.Red,
61 out_number = Colors.LightRed,
62 out_number = Colors.LightRed,
62
63
63 normal = Colors.Normal
64 normal = Colors.Normal
64 )
65 )
65 # Don't forget to enter it into the table!
66 # Don't forget to enter it into the table!
66 PromptColors.add_scheme(__PColLinux)
67 PromptColors.add_scheme(__PColLinux)
68
67 # Slightly modified Linux for light backgrounds
69 # Slightly modified Linux for light backgrounds
68 __PColLightBG = ColorANSI.ColorScheme('LightBG',**__PColLinux.colors.dict().copy())
70 __PColLightBG = __PColLinux.copy('LightBG')
69
71
70 __PColLightBG.colors.update(
72 __PColLightBG.colors.update(
71 in_prompt = InputColors.Blue,
73 in_prompt = InputColors.Blue,
72 in_number = InputColors.LightBlue,
74 in_number = InputColors.LightBlue,
73 in_prompt2 = InputColors.Blue
75 in_prompt2 = InputColors.Blue
74 )
76 )
75 PromptColors.add_scheme(__PColLightBG)
77 PromptColors.add_scheme(__PColLightBG)
76
78
77 del Colors,InputColors
79 del Colors,InputColors
78
80
79 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
80 def multiple_replace(dict, text):
82 def multiple_replace(dict, text):
81 """ Replace in 'text' all occurences of any key in the given
83 """ Replace in 'text' all occurences of any key in the given
82 dictionary by its corresponding value. Returns the new string."""
84 dictionary by its corresponding value. Returns the new string."""
83
85
84 # Function by Xavier Defrang, originally found at:
86 # Function by Xavier Defrang, originally found at:
85 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
87 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
86
88
87 # Create a regular expression from the dictionary keys
89 # Create a regular expression from the dictionary keys
88 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
90 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
89 # For each match, look-up corresponding value in dictionary
91 # For each match, look-up corresponding value in dictionary
90 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
92 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
91
93
92 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
93 # Special characters that can be used in prompt templates, mainly bash-like
95 # Special characters that can be used in prompt templates, mainly bash-like
94
96
95 # If $HOME isn't defined (Windows), make it an absurd string so that it can
97 # If $HOME isn't defined (Windows), make it an absurd string so that it can
96 # never be expanded out into '~'. Basically anything which can never be a
98 # never be expanded out into '~'. Basically anything which can never be a
97 # reasonable directory name will do, we just want the $HOME -> '~' operation
99 # reasonable directory name will do, we just want the $HOME -> '~' operation
98 # to become a no-op. We pre-compute $HOME here so it's not done on every
100 # to become a no-op. We pre-compute $HOME here so it's not done on every
99 # prompt call.
101 # prompt call.
100
102
101 # FIXME:
103 # FIXME:
102
104
103 # - This should be turned into a class which does proper namespace management,
105 # - This should be turned into a class which does proper namespace management,
104 # since the prompt specials need to be evaluated in a certain namespace.
106 # since the prompt specials need to be evaluated in a certain namespace.
105 # Currently it's just globals, which need to be managed manually by code
107 # Currently it's just globals, which need to be managed manually by code
106 # below.
108 # below.
107
109
108 # - I also need to split up the color schemes from the prompt specials
110 # - I also need to split up the color schemes from the prompt specials
109 # somehow. I don't have a clean design for that quite yet.
111 # somehow. I don't have a clean design for that quite yet.
110
112
111 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
113 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
112
114
113 # We precompute a few more strings here for the prompt_specials, which are
115 # We precompute a few more strings here for the prompt_specials, which are
114 # fixed once ipython starts. This reduces the runtime overhead of computing
116 # fixed once ipython starts. This reduces the runtime overhead of computing
115 # prompt strings.
117 # prompt strings.
116 USER = os.environ.get("USER")
118 USER = os.environ.get("USER")
117 HOSTNAME = socket.gethostname()
119 HOSTNAME = socket.gethostname()
118 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
120 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
119 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
121 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
120
122
121 prompt_specials_color = {
123 prompt_specials_color = {
122 # Prompt/history count
124 # Prompt/history count
123 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
125 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
124 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
126 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
125 # Prompt/history count, with the actual digits replaced by dots. Used
127 # Prompt/history count, with the actual digits replaced by dots. Used
126 # mainly in continuation prompts (prompt_in2)
128 # mainly in continuation prompts (prompt_in2)
127 '\\D': '${"."*len(str(self.cache.prompt_count))}',
129 '\\D': '${"."*len(str(self.cache.prompt_count))}',
128 # Current working directory
130 # Current working directory
129 '\\w': '${os.getcwd()}',
131 '\\w': '${os.getcwd()}',
130 # Current time
132 # Current time
131 '\\t' : '${time.strftime("%H:%M:%S")}',
133 '\\t' : '${time.strftime("%H:%M:%S")}',
132 # Basename of current working directory.
134 # Basename of current working directory.
133 # (use os.sep to make this portable across OSes)
135 # (use os.sep to make this portable across OSes)
134 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
136 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
135 # These X<N> are an extension to the normal bash prompts. They return
137 # These X<N> are an extension to the normal bash prompts. They return
136 # N terms of the path, after replacing $HOME with '~'
138 # N terms of the path, after replacing $HOME with '~'
137 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
139 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
138 '\\X1': '${self.cwd_filt(1)}',
140 '\\X1': '${self.cwd_filt(1)}',
139 '\\X2': '${self.cwd_filt(2)}',
141 '\\X2': '${self.cwd_filt(2)}',
140 '\\X3': '${self.cwd_filt(3)}',
142 '\\X3': '${self.cwd_filt(3)}',
141 '\\X4': '${self.cwd_filt(4)}',
143 '\\X4': '${self.cwd_filt(4)}',
142 '\\X5': '${self.cwd_filt(5)}',
144 '\\X5': '${self.cwd_filt(5)}',
143 # Y<N> are similar to X<N>, but they show '~' if it's the directory
145 # Y<N> are similar to X<N>, but they show '~' if it's the directory
144 # N+1 in the list. Somewhat like %cN in tcsh.
146 # N+1 in the list. Somewhat like %cN in tcsh.
145 '\\Y0': '${self.cwd_filt2(0)}',
147 '\\Y0': '${self.cwd_filt2(0)}',
146 '\\Y1': '${self.cwd_filt2(1)}',
148 '\\Y1': '${self.cwd_filt2(1)}',
147 '\\Y2': '${self.cwd_filt2(2)}',
149 '\\Y2': '${self.cwd_filt2(2)}',
148 '\\Y3': '${self.cwd_filt2(3)}',
150 '\\Y3': '${self.cwd_filt2(3)}',
149 '\\Y4': '${self.cwd_filt2(4)}',
151 '\\Y4': '${self.cwd_filt2(4)}',
150 '\\Y5': '${self.cwd_filt2(5)}',
152 '\\Y5': '${self.cwd_filt2(5)}',
151 # Hostname up to first .
153 # Hostname up to first .
152 '\\h': HOSTNAME_SHORT,
154 '\\h': HOSTNAME_SHORT,
153 # Full hostname
155 # Full hostname
154 '\\H': HOSTNAME,
156 '\\H': HOSTNAME,
155 # Username of current user
157 # Username of current user
156 '\\u': USER,
158 '\\u': USER,
157 # Escaped '\'
159 # Escaped '\'
158 '\\\\': '\\',
160 '\\\\': '\\',
159 # Newline
161 # Newline
160 '\\n': '\n',
162 '\\n': '\n',
161 # Carriage return
163 # Carriage return
162 '\\r': '\r',
164 '\\r': '\r',
163 # Release version
165 # Release version
164 '\\v': __version__,
166 '\\v': __version__,
165 # Root symbol ($ or #)
167 # Root symbol ($ or #)
166 '\\$': ROOT_SYMBOL,
168 '\\$': ROOT_SYMBOL,
167 }
169 }
168
170
169 # A copy of the prompt_specials dictionary but with all color escapes removed,
171 # A copy of the prompt_specials dictionary but with all color escapes removed,
170 # so we can correctly compute the prompt length for the auto_rewrite method.
172 # so we can correctly compute the prompt length for the auto_rewrite method.
171 prompt_specials_nocolor = prompt_specials_color.copy()
173 prompt_specials_nocolor = prompt_specials_color.copy()
172 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
174 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
173 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
175 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
174
176
175 # Add in all the InputTermColors color escapes as valid prompt characters.
177 # Add in all the InputTermColors color escapes as valid prompt characters.
176 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
178 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
177 # with a color name which may begin with a letter used by any other of the
179 # with a color name which may begin with a letter used by any other of the
178 # allowed specials. This of course means that \\C will never be allowed for
180 # allowed specials. This of course means that \\C will never be allowed for
179 # anything else.
181 # anything else.
180 input_colors = ColorANSI.InputTermColors
182 input_colors = ColorANSI.InputTermColors
181 for _color in dir(input_colors):
183 for _color in dir(input_colors):
182 if _color[0] != '_':
184 if _color[0] != '_':
183 c_name = '\\C_'+_color
185 c_name = '\\C_'+_color
184 prompt_specials_color[c_name] = getattr(input_colors,_color)
186 prompt_specials_color[c_name] = getattr(input_colors,_color)
185 prompt_specials_nocolor[c_name] = ''
187 prompt_specials_nocolor[c_name] = ''
186
188
187 # we default to no color for safety. Note that prompt_specials is a global
189 # we default to no color for safety. Note that prompt_specials is a global
188 # variable used by all prompt objects.
190 # variable used by all prompt objects.
189 prompt_specials = prompt_specials_nocolor
191 prompt_specials = prompt_specials_nocolor
190
192
191 #-----------------------------------------------------------------------------
193 #-----------------------------------------------------------------------------
192 def str_safe(arg):
194 def str_safe(arg):
193 """Convert to a string, without ever raising an exception.
195 """Convert to a string, without ever raising an exception.
194
196
195 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
197 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
196 error message."""
198 error message."""
197
199
198 try:
200 try:
199 out = str(arg)
201 out = str(arg)
200 except UnicodeError:
202 except UnicodeError:
201 try:
203 try:
202 out = arg.encode('utf_8','replace')
204 out = arg.encode('utf_8','replace')
203 except Exception,msg:
205 except Exception,msg:
204 # let's keep this little duplication here, so that the most common
206 # let's keep this little duplication here, so that the most common
205 # case doesn't suffer from a double try wrapping.
207 # case doesn't suffer from a double try wrapping.
206 out = '<ERROR: %s>' % msg
208 out = '<ERROR: %s>' % msg
207 except Exception,msg:
209 except Exception,msg:
208 out = '<ERROR: %s>' % msg
210 out = '<ERROR: %s>' % msg
209 return out
211 return out
210
212
211 class BasePrompt:
213 class BasePrompt:
212 """Interactive prompt similar to Mathematica's."""
214 """Interactive prompt similar to Mathematica's."""
213 def __init__(self,cache,sep,prompt,pad_left=False):
215 def __init__(self,cache,sep,prompt,pad_left=False):
214
216
215 # Hack: we access information about the primary prompt through the
217 # Hack: we access information about the primary prompt through the
216 # cache argument. We need this, because we want the secondary prompt
218 # cache argument. We need this, because we want the secondary prompt
217 # to be aligned with the primary one. Color table info is also shared
219 # to be aligned with the primary one. Color table info is also shared
218 # by all prompt classes through the cache. Nice OO spaghetti code!
220 # by all prompt classes through the cache. Nice OO spaghetti code!
219 self.cache = cache
221 self.cache = cache
220 self.sep = sep
222 self.sep = sep
221
223
222 # regexp to count the number of spaces at the end of a prompt
224 # regexp to count the number of spaces at the end of a prompt
223 # expression, useful for prompt auto-rewriting
225 # expression, useful for prompt auto-rewriting
224 self.rspace = re.compile(r'(\s*)$')
226 self.rspace = re.compile(r'(\s*)$')
225 # Flag to left-pad prompt strings to match the length of the primary
227 # Flag to left-pad prompt strings to match the length of the primary
226 # prompt
228 # prompt
227 self.pad_left = pad_left
229 self.pad_left = pad_left
228 # Set template to create each actual prompt (where numbers change)
230 # Set template to create each actual prompt (where numbers change)
229 self.p_template = prompt
231 self.p_template = prompt
230 self.set_p_str()
232 self.set_p_str()
231
233
232 def set_p_str(self):
234 def set_p_str(self):
233 """ Set the interpolating prompt strings.
235 """ Set the interpolating prompt strings.
234
236
235 This must be called every time the color settings change, because the
237 This must be called every time the color settings change, because the
236 prompt_specials global may have changed."""
238 prompt_specials global may have changed."""
237
239
238 import os,time # needed in locals for prompt string handling
240 import os,time # needed in locals for prompt string handling
239 loc = locals()
241 loc = locals()
240 self.p_str = ItplNS('%s%s%s' %
242 self.p_str = ItplNS('%s%s%s' %
241 ('${self.sep}${self.col_p}',
243 ('${self.sep}${self.col_p}',
242 multiple_replace(prompt_specials, self.p_template),
244 multiple_replace(prompt_specials, self.p_template),
243 '${self.col_norm}'),self.cache.user_ns,loc)
245 '${self.col_norm}'),self.cache.user_ns,loc)
244
246
245 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
247 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
246 self.p_template),
248 self.p_template),
247 self.cache.user_ns,loc)
249 self.cache.user_ns,loc)
248
250
249 def write(self,msg): # dbg
251 def write(self,msg): # dbg
250 sys.stdout.write(msg)
252 sys.stdout.write(msg)
251 return ''
253 return ''
252
254
253 def __str__(self):
255 def __str__(self):
254 """Return a string form of the prompt.
256 """Return a string form of the prompt.
255
257
256 This for is useful for continuation and output prompts, since it is
258 This for is useful for continuation and output prompts, since it is
257 left-padded to match lengths with the primary one (if the
259 left-padded to match lengths with the primary one (if the
258 self.pad_left attribute is set)."""
260 self.pad_left attribute is set)."""
259
261
260 out_str = str_safe(self.p_str)
262 out_str = str_safe(self.p_str)
261 if self.pad_left:
263 if self.pad_left:
262 # We must find the amount of padding required to match lengths,
264 # We must find the amount of padding required to match lengths,
263 # taking the color escapes (which are invisible on-screen) into
265 # taking the color escapes (which are invisible on-screen) into
264 # account.
266 # account.
265 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
267 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
266 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
268 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
267 return format % out_str
269 return format % out_str
268 else:
270 else:
269 return out_str
271 return out_str
270
272
271 # these path filters are put in as methods so that we can control the
273 # these path filters are put in as methods so that we can control the
272 # namespace where the prompt strings get evaluated
274 # namespace where the prompt strings get evaluated
273 def cwd_filt(self,depth):
275 def cwd_filt(self,depth):
274 """Return the last depth elements of the current working directory.
276 """Return the last depth elements of the current working directory.
275
277
276 $HOME is always replaced with '~'.
278 $HOME is always replaced with '~'.
277 If depth==0, the full path is returned."""
279 If depth==0, the full path is returned."""
278
280
279 cwd = os.getcwd().replace(HOME,"~")
281 cwd = os.getcwd().replace(HOME,"~")
280 out = os.sep.join(cwd.split(os.sep)[-depth:])
282 out = os.sep.join(cwd.split(os.sep)[-depth:])
281 if out:
283 if out:
282 return out
284 return out
283 else:
285 else:
284 return os.sep
286 return os.sep
285
287
286 def cwd_filt2(self,depth):
288 def cwd_filt2(self,depth):
287 """Return the last depth elements of the current working directory.
289 """Return the last depth elements of the current working directory.
288
290
289 $HOME is always replaced with '~'.
291 $HOME is always replaced with '~'.
290 If depth==0, the full path is returned."""
292 If depth==0, the full path is returned."""
291
293
292 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
294 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
293 if '~' in cwd and len(cwd) == depth+1:
295 if '~' in cwd and len(cwd) == depth+1:
294 depth += 1
296 depth += 1
295 out = os.sep.join(cwd[-depth:])
297 out = os.sep.join(cwd[-depth:])
296 if out:
298 if out:
297 return out
299 return out
298 else:
300 else:
299 return os.sep
301 return os.sep
300
302
301 class Prompt1(BasePrompt):
303 class Prompt1(BasePrompt):
302 """Input interactive prompt similar to Mathematica's."""
304 """Input interactive prompt similar to Mathematica's."""
303
305
304 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
306 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
305 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
307 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
306
308
307 def set_colors(self):
309 def set_colors(self):
308 self.set_p_str()
310 self.set_p_str()
309 Colors = self.cache.color_table.active_colors # shorthand
311 Colors = self.cache.color_table.active_colors # shorthand
310 self.col_p = Colors.in_prompt
312 self.col_p = Colors.in_prompt
311 self.col_num = Colors.in_number
313 self.col_num = Colors.in_number
312 self.col_norm = Colors.in_normal
314 self.col_norm = Colors.in_normal
313 # We need a non-input version of these escapes for the '--->'
315 # We need a non-input version of these escapes for the '--->'
314 # auto-call prompts used in the auto_rewrite() method.
316 # auto-call prompts used in the auto_rewrite() method.
315 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
317 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
316 self.col_norm_ni = Colors.normal
318 self.col_norm_ni = Colors.normal
317
319
318 def __str__(self):
320 def __str__(self):
319 self.cache.prompt_count += 1
321 self.cache.prompt_count += 1
320 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
322 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
321 return str_safe(self.p_str)
323 return str_safe(self.p_str)
322
324
323 def auto_rewrite(self):
325 def auto_rewrite(self):
324 """Print a string of the form '--->' which lines up with the previous
326 """Print a string of the form '--->' which lines up with the previous
325 input string. Useful for systems which re-write the user input when
327 input string. Useful for systems which re-write the user input when
326 handling automatically special syntaxes."""
328 handling automatically special syntaxes."""
327
329
328 curr = str(self.cache.last_prompt)
330 curr = str(self.cache.last_prompt)
329 nrspaces = len(self.rspace.search(curr).group())
331 nrspaces = len(self.rspace.search(curr).group())
330 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
332 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
331 ' '*nrspaces,self.col_norm_ni)
333 ' '*nrspaces,self.col_norm_ni)
332
334
333 class PromptOut(BasePrompt):
335 class PromptOut(BasePrompt):
334 """Output interactive prompt similar to Mathematica's."""
336 """Output interactive prompt similar to Mathematica's."""
335
337
336 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
338 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
337 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
339 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
338 if not self.p_template:
340 if not self.p_template:
339 self.__str__ = lambda: ''
341 self.__str__ = lambda: ''
340
342
341 def set_colors(self):
343 def set_colors(self):
342 self.set_p_str()
344 self.set_p_str()
343 Colors = self.cache.color_table.active_colors # shorthand
345 Colors = self.cache.color_table.active_colors # shorthand
344 self.col_p = Colors.out_prompt
346 self.col_p = Colors.out_prompt
345 self.col_num = Colors.out_number
347 self.col_num = Colors.out_number
346 self.col_norm = Colors.normal
348 self.col_norm = Colors.normal
347
349
348 class Prompt2(BasePrompt):
350 class Prompt2(BasePrompt):
349 """Interactive continuation prompt."""
351 """Interactive continuation prompt."""
350
352
351 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
353 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
352 self.cache = cache
354 self.cache = cache
353 self.p_template = prompt
355 self.p_template = prompt
354 self.pad_left = pad_left
356 self.pad_left = pad_left
355 self.set_p_str()
357 self.set_p_str()
356
358
357 def set_p_str(self):
359 def set_p_str(self):
358 import os,time # needed in locals for prompt string handling
360 import os,time # needed in locals for prompt string handling
359 loc = locals()
361 loc = locals()
360 self.p_str = ItplNS('%s%s%s' %
362 self.p_str = ItplNS('%s%s%s' %
361 ('${self.col_p2}',
363 ('${self.col_p2}',
362 multiple_replace(prompt_specials, self.p_template),
364 multiple_replace(prompt_specials, self.p_template),
363 '$self.col_norm'),
365 '$self.col_norm'),
364 self.cache.user_ns,loc)
366 self.cache.user_ns,loc)
365 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
367 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
366 self.p_template),
368 self.p_template),
367 self.cache.user_ns,loc)
369 self.cache.user_ns,loc)
368
370
369 def set_colors(self):
371 def set_colors(self):
370 self.set_p_str()
372 self.set_p_str()
371 Colors = self.cache.color_table.active_colors
373 Colors = self.cache.color_table.active_colors
372 self.col_p2 = Colors.in_prompt2
374 self.col_p2 = Colors.in_prompt2
373 self.col_norm = Colors.in_normal
375 self.col_norm = Colors.in_normal
374 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
376 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
375 # updated their prompt_in2 definitions. Remove eventually.
377 # updated their prompt_in2 definitions. Remove eventually.
376 self.col_p = Colors.out_prompt
378 self.col_p = Colors.out_prompt
377 self.col_num = Colors.out_number
379 self.col_num = Colors.out_number
378
380
379 #-----------------------------------------------------------------------------
381 #-----------------------------------------------------------------------------
380 class CachedOutput:
382 class CachedOutput:
381 """Class for printing output from calculations while keeping a cache of
383 """Class for printing output from calculations while keeping a cache of
382 reults. It dynamically creates global variables prefixed with _ which
384 reults. It dynamically creates global variables prefixed with _ which
383 contain these results.
385 contain these results.
384
386
385 Meant to be used as a sys.displayhook replacement, providing numbered
387 Meant to be used as a sys.displayhook replacement, providing numbered
386 prompts and cache services.
388 prompts and cache services.
387
389
388 Initialize with initial and final values for cache counter (this defines
390 Initialize with initial and final values for cache counter (this defines
389 the maximum size of the cache."""
391 the maximum size of the cache."""
390
392
391 def __init__(self,cache_size,Pprint,colors='NoColor',input_sep='\n',
393 def __init__(self,cache_size,Pprint,colors='NoColor',input_sep='\n',
392 output_sep='\n',output_sep2='',user_ns={},
394 output_sep='\n',output_sep2='',user_ns={},
393 ps1 = None, ps2 = None,ps_out = None,
395 ps1 = None, ps2 = None,ps_out = None,
394 input_hist = None,pad_left=True):
396 input_hist = None,pad_left=True):
395
397
396 cache_size_min = 20
398 cache_size_min = 20
397 if cache_size <= 0:
399 if cache_size <= 0:
398 self.do_full_cache = 0
400 self.do_full_cache = 0
399 cache_size = 0
401 cache_size = 0
400 elif cache_size < cache_size_min:
402 elif cache_size < cache_size_min:
401 self.do_full_cache = 0
403 self.do_full_cache = 0
402 cache_size = 0
404 cache_size = 0
403 warn('caching was disabled (min value for cache size is %s).' %
405 warn('caching was disabled (min value for cache size is %s).' %
404 cache_size_min,level=3)
406 cache_size_min,level=3)
405 else:
407 else:
406 self.do_full_cache = 1
408 self.do_full_cache = 1
407
409
408 self.cache_size = cache_size
410 self.cache_size = cache_size
409 self.input_sep = input_sep
411 self.input_sep = input_sep
410
412
411 # we need a reference to the user-level namespace
413 # we need a reference to the user-level namespace
412 self.user_ns = user_ns
414 self.user_ns = user_ns
413 # and to the user's input
415 # and to the user's input
414 self.input_hist = input_hist
416 self.input_hist = input_hist
415
417
416 # Set input prompt strings and colors
418 # Set input prompt strings and colors
417 if cache_size == 0:
419 if cache_size == 0:
418 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
420 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
419 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
421 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
420 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
422 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
421 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
423 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
422 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
424 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
423
425
424 self.color_table = PromptColors
426 self.color_table = PromptColors
425 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
427 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
426 pad_left=pad_left)
428 pad_left=pad_left)
427 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
429 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
428 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
430 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
429 pad_left=pad_left)
431 pad_left=pad_left)
430 self.set_colors(colors)
432 self.set_colors(colors)
431
433
432 # other more normal stuff
434 # other more normal stuff
433 # b/c each call to the In[] prompt raises it by 1, even the first.
435 # b/c each call to the In[] prompt raises it by 1, even the first.
434 self.prompt_count = 0
436 self.prompt_count = 0
435 self.cache_count = 1
437 self.cache_count = 1
436 # Store the last prompt string each time, we need it for aligning
438 # Store the last prompt string each time, we need it for aligning
437 # continuation and auto-rewrite prompts
439 # continuation and auto-rewrite prompts
438 self.last_prompt = ''
440 self.last_prompt = ''
439 self.entries = [None] # output counter starts at 1 for the user
441 self.entries = [None] # output counter starts at 1 for the user
440 self.Pprint = Pprint
442 self.Pprint = Pprint
441 self.output_sep = output_sep
443 self.output_sep = output_sep
442 self.output_sep2 = output_sep2
444 self.output_sep2 = output_sep2
443 self._,self.__,self.___ = '','',''
445 self._,self.__,self.___ = '','',''
444 self.pprint_types = map(type,[(),[],{}])
446 self.pprint_types = map(type,[(),[],{}])
445
447
446 # these are deliberately global:
448 # these are deliberately global:
447 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
449 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
448 self.user_ns.update(to_user_ns)
450 self.user_ns.update(to_user_ns)
449
451
450 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
452 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
451 if p_str is None:
453 if p_str is None:
452 if self.do_full_cache:
454 if self.do_full_cache:
453 return cache_def
455 return cache_def
454 else:
456 else:
455 return no_cache_def
457 return no_cache_def
456 else:
458 else:
457 return p_str
459 return p_str
458
460
459 def set_colors(self,colors):
461 def set_colors(self,colors):
460 """Set the active color scheme and configure colors for the three
462 """Set the active color scheme and configure colors for the three
461 prompt subsystems."""
463 prompt subsystems."""
462
464
463 # FIXME: the prompt_specials global should be gobbled inside this
465 # FIXME: the prompt_specials global should be gobbled inside this
464 # class instead. Do it when cleaning up the whole 3-prompt system.
466 # class instead. Do it when cleaning up the whole 3-prompt system.
465 global prompt_specials
467 global prompt_specials
466 if colors.lower()=='nocolor':
468 if colors.lower()=='nocolor':
467 prompt_specials = prompt_specials_nocolor
469 prompt_specials = prompt_specials_nocolor
468 else:
470 else:
469 prompt_specials = prompt_specials_color
471 prompt_specials = prompt_specials_color
470
472
471 self.color_table.set_active_scheme(colors)
473 self.color_table.set_active_scheme(colors)
472 self.prompt1.set_colors()
474 self.prompt1.set_colors()
473 self.prompt2.set_colors()
475 self.prompt2.set_colors()
474 self.prompt_out.set_colors()
476 self.prompt_out.set_colors()
475
477
476 def __call__(self,arg=None):
478 def __call__(self,arg=None):
477 """Printing with history cache management.
479 """Printing with history cache management.
478
480
479 This is invoked everytime the interpreter needs to print, and is
481 This is invoked everytime the interpreter needs to print, and is
480 activated by setting the variable sys.displayhook to it."""
482 activated by setting the variable sys.displayhook to it."""
481
483
482 # If something injected a '_' variable in __builtin__, delete
484 # If something injected a '_' variable in __builtin__, delete
483 # ipython's automatic one so we don't clobber that. gettext() in
485 # ipython's automatic one so we don't clobber that. gettext() in
484 # particular uses _, so we need to stay away from it.
486 # particular uses _, so we need to stay away from it.
485 if '_' in __builtin__.__dict__:
487 if '_' in __builtin__.__dict__:
486 try:
488 try:
487 del self.user_ns['_']
489 del self.user_ns['_']
488 except KeyError:
490 except KeyError:
489 pass
491 pass
490 if arg is not None:
492 if arg is not None:
491 cout_write = Term.cout.write # fast lookup
493 cout_write = Term.cout.write # fast lookup
492 # first handle the cache and counters
494 # first handle the cache and counters
493 self.update(arg)
495 self.update(arg)
494 # do not print output if input ends in ';'
496 # do not print output if input ends in ';'
495 if self.input_hist[self.prompt_count].endswith(';\n'):
497 if self.input_hist[self.prompt_count].endswith(';\n'):
496 return
498 return
497 # don't use print, puts an extra space
499 # don't use print, puts an extra space
498 cout_write(self.output_sep)
500 cout_write(self.output_sep)
499 if self.do_full_cache:
501 if self.do_full_cache:
500 cout_write(str(self.prompt_out))
502 cout_write(str(self.prompt_out))
501
503
502 if isinstance(arg,Macro):
504 if isinstance(arg,Macro):
503 print 'Executing Macro...'
505 print 'Executing Macro...'
504 # in case the macro takes a long time to execute
506 # in case the macro takes a long time to execute
505 Term.cout.flush()
507 Term.cout.flush()
506 exec arg.value in self.user_ns
508 exec arg.value in self.user_ns
507 return None
509 return None
508
510
509 # and now call a possibly user-defined print mechanism
511 # and now call a possibly user-defined print mechanism
510 self.display(arg)
512 self.display(arg)
511 cout_write(self.output_sep2)
513 cout_write(self.output_sep2)
512 Term.cout.flush()
514 Term.cout.flush()
513
515
514 def _display(self,arg):
516 def _display(self,arg):
515 """Default printer method, uses pprint.
517 """Default printer method, uses pprint.
516
518
517 This can be over-ridden by the users to implement special formatting
519 This can be over-ridden by the users to implement special formatting
518 of certain types of output."""
520 of certain types of output."""
519
521
520 if self.Pprint:
522 if self.Pprint:
521 out = pformat(arg)
523 out = pformat(arg)
522 if '\n' in out:
524 if '\n' in out:
523 # So that multi-line strings line up with the left column of
525 # So that multi-line strings line up with the left column of
524 # the screen, instead of having the output prompt mess up
526 # the screen, instead of having the output prompt mess up
525 # their first line.
527 # their first line.
526 Term.cout.write('\n')
528 Term.cout.write('\n')
527 print >>Term.cout, out
529 print >>Term.cout, out
528 else:
530 else:
529 print >>Term.cout, arg
531 print >>Term.cout, arg
530
532
531 # Assign the default display method:
533 # Assign the default display method:
532 display = _display
534 display = _display
533
535
534 def update(self,arg):
536 def update(self,arg):
535 #print '***cache_count', self.cache_count # dbg
537 #print '***cache_count', self.cache_count # dbg
536 if self.cache_count >= self.cache_size and self.do_full_cache:
538 if self.cache_count >= self.cache_size and self.do_full_cache:
537 self.flush()
539 self.flush()
538 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
540 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
539 # we cause buggy behavior for things like gettext).
541 # we cause buggy behavior for things like gettext).
540 if '_' not in __builtin__.__dict__:
542 if '_' not in __builtin__.__dict__:
541 self.___ = self.__
543 self.___ = self.__
542 self.__ = self._
544 self.__ = self._
543 self._ = arg
545 self._ = arg
544 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
546 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
545
547
546 # hackish access to top-level namespace to create _1,_2... dynamically
548 # hackish access to top-level namespace to create _1,_2... dynamically
547 to_main = {}
549 to_main = {}
548 if self.do_full_cache:
550 if self.do_full_cache:
549 self.cache_count += 1
551 self.cache_count += 1
550 self.entries.append(arg)
552 self.entries.append(arg)
551 new_result = '_'+`self.prompt_count`
553 new_result = '_'+`self.prompt_count`
552 to_main[new_result] = self.entries[-1]
554 to_main[new_result] = self.entries[-1]
553 self.user_ns.update(to_main)
555 self.user_ns.update(to_main)
554 self.user_ns['_oh'][self.prompt_count] = arg
556 self.user_ns['_oh'][self.prompt_count] = arg
555
557
556 def flush(self):
558 def flush(self):
557 if not self.do_full_cache:
559 if not self.do_full_cache:
558 raise ValueError,"You shouldn't have reached the cache flush "\
560 raise ValueError,"You shouldn't have reached the cache flush "\
559 "if full caching is not enabled!"
561 "if full caching is not enabled!"
560 warn('Output cache limit (currently '+\
562 warn('Output cache limit (currently '+\
561 `self.cache_count`+' entries) hit.\n'
563 `self.cache_count`+' entries) hit.\n'
562 'Flushing cache and resetting history counter...\n'
564 'Flushing cache and resetting history counter...\n'
563 'The only history variables available will be _,__,___ and _1\n'
565 'The only history variables available will be _,__,___ and _1\n'
564 'with the current result.')
566 'with the current result.')
565 # delete auto-generated vars from global namespace
567 # delete auto-generated vars from global namespace
566 for n in range(1,self.prompt_count + 1):
568 for n in range(1,self.prompt_count + 1):
567 key = '_'+`n`
569 key = '_'+`n`
568 try:
570 try:
569 del self.user_ns[key]
571 del self.user_ns[key]
570 except: pass
572 except: pass
571 self.prompt_count = 1
573 self.prompt_count = 1
572 self.cache_count = 1
574 self.cache_count = 1
@@ -1,74 +1,76 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Release data for the IPython project.
2 """Release data for the IPython project.
3
3
4 $Id: Release.py 775 2005-09-01 20:24:59Z fperez $"""
4 $Id: Release.py 951 2005-12-25 00:57:24Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
10 # <n8gray@caltech.edu>
10 # <n8gray@caltech.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 # Name of the package for release purposes. This is the name which labels
16 # Name of the package for release purposes. This is the name which labels
17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
18 name = 'ipython'
18 name = 'ipython'
19
19
20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
21 # the new substring. We have to avoid using either dashes or underscores,
21 # the new substring. We have to avoid using either dashes or underscores,
22 # because bdist_rpm does not accept dashes (an RPM) convention, and
22 # because bdist_rpm does not accept dashes (an RPM) convention, and
23 # bdist_deb does not accept underscores (a Debian convention).
23 # bdist_deb does not accept underscores (a Debian convention).
24
24
25 version = '0.6.16.svn'
25 version = '0.6.16.svn'
26
26
27 revision = '$Revision: 775 $'
27 revision = '$Revision: 951 $'
28
28
29 description = "An enhanced interactive Python shell."
29 description = "An enhanced interactive Python shell."
30
30
31 long_description = \
31 long_description = \
32 """
32 """
33 IPython provides a replacement for the interactive Python interpreter with
33 IPython provides a replacement for the interactive Python interpreter with
34 extra functionality.
34 extra functionality.
35
35
36 Main features:
36 Main features:
37
37
38 * Comprehensive object introspection.
38 * Comprehensive object introspection.
39
39
40 * Input history, persistent across sessions.
40 * Input history, persistent across sessions.
41
41
42 * Caching of output results during a session with automatically generated
42 * Caching of output results during a session with automatically generated
43 references.
43 references.
44
44
45 * Readline based name completion.
45 * Readline based name completion.
46
46
47 * Extensible system of 'magic' commands for controlling the environment and
47 * Extensible system of 'magic' commands for controlling the environment and
48 performing many tasks related either to IPython or the operating system.
48 performing many tasks related either to IPython or the operating system.
49
49
50 * Configuration system with easy switching between different setups (simpler
50 * Configuration system with easy switching between different setups (simpler
51 than changing $PYTHONSTARTUP environment variables every time).
51 than changing $PYTHONSTARTUP environment variables every time).
52
52
53 * Session logging and reloading.
53 * Session logging and reloading.
54
54
55 * Extensible syntax processing for special purpose situations.
55 * Extensible syntax processing for special purpose situations.
56
56
57 * Access to the system shell with user-extensible alias system.
57 * Access to the system shell with user-extensible alias system.
58
58
59 * Easily embeddable in other Python programs.
59 * Easily embeddable in other Python programs.
60
60
61 * Integrated access to the pdb debugger and the Python profiler. """
61 * Integrated access to the pdb debugger and the Python profiler. """
62
62
63 license = 'BSD'
63 license = 'BSD'
64
64
65 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
65 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
66 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
66 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
67 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu')
67 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu')
68 }
68 }
69
69
70 url = 'http://ipython.scipy.org'
70 url = 'http://ipython.scipy.org'
71
71
72 download_url = 'http://ipython.scipy.org/dist'
73
72 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
74 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
73
75
74 keywords = ['Interactive','Interpreter','Shell']
76 keywords = ['Interactive','Interpreter','Shell']
@@ -1,2104 +1,2112 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 924 2005-11-15 20:24:31Z fperez $
9 $Id: iplib.py 951 2005-12-25 00:57:24Z 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-2004 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2004 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, much of that class has been copied
20 # Python standard library. Over time, much 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. The Python License (sec. 2) allows for this, but it's always
22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 # nice to acknowledge credit where credit is due.
23 # nice to acknowledge credit where credit is due.
24 #*****************************************************************************
24 #*****************************************************************************
25
25
26 #****************************************************************************
26 #****************************************************************************
27 # Modules and globals
27 # Modules and globals
28
28
29 from __future__ import generators # for 2.2 backwards-compatibility
29 from __future__ import generators # for 2.2 backwards-compatibility
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import exceptions
40 import exceptions
41 import keyword
41 import keyword
42 import new
42 import new
43 import os, sys, shutil
43 import os, sys, shutil
44 import code, glob, types, re
44 import code, glob, types, re
45 import string, StringIO
45 import string, StringIO
46 import inspect, pydoc
46 import inspect, pydoc
47 import bdb, pdb
47 import bdb, pdb
48 import UserList # don't subclass list so this works with Python2.1
48 import UserList # don't subclass list so this works with Python2.1
49 from pprint import pprint, pformat
49 from pprint import pprint, pformat
50 import cPickle as pickle
50 import cPickle as pickle
51 import traceback
51 import traceback
52 from codeop import CommandCompiler
52 from codeop import CommandCompiler
53
53
54 # IPython's own modules
54 # IPython's own modules
55 import IPython
55 import IPython
56 from IPython import OInspect,PyColorize,ultraTB
56 from IPython import OInspect,PyColorize,ultraTB
57 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
57 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
58 from IPython.Logger import Logger
58 from IPython.Logger import Logger
59 from IPython.Magic import Magic,magic2python,shlex_split
59 from IPython.Magic import Magic,magic2python,shlex_split
60 from IPython.usage import cmd_line_usage,interactive_usage
60 from IPython.usage import cmd_line_usage,interactive_usage
61 from IPython.Struct import Struct
61 from IPython.Struct import Struct
62 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
63 from IPython.FakeModule import FakeModule
63 from IPython.FakeModule import FakeModule
64 from IPython.background_jobs import BackgroundJobManager
64 from IPython.background_jobs import BackgroundJobManager
65 from IPython.PyColorize import Parser
65 from IPython.PyColorize import Parser
66 from IPython.genutils import *
66 from IPython.genutils import *
67
67
68 # Global pointer to the running
68 # Global pointer to the running
69
69
70 # store the builtin raw_input globally, and use this always, in case user code
70 # store the builtin raw_input globally, and use this always, in case user code
71 # overwrites it (like wx.py.PyShell does)
71 # overwrites it (like wx.py.PyShell does)
72 raw_input_original = raw_input
72 raw_input_original = raw_input
73
73
74 #****************************************************************************
74 #****************************************************************************
75 # Some utility function definitions
75 # Some utility function definitions
76
76
77 class Bunch: pass
77 class Bunch: pass
78
78
79 def esc_quotes(strng):
79 def esc_quotes(strng):
80 """Return the input string with single and double quotes escaped out"""
80 """Return the input string with single and double quotes escaped out"""
81
81
82 return strng.replace('"','\\"').replace("'","\\'")
82 return strng.replace('"','\\"').replace("'","\\'")
83
83
84 def import_fail_info(mod_name,fns=None):
84 def import_fail_info(mod_name,fns=None):
85 """Inform load failure for a module."""
85 """Inform load failure for a module."""
86
86
87 if fns == None:
87 if fns == None:
88 warn("Loading of %s failed.\n" % (mod_name,))
88 warn("Loading of %s failed.\n" % (mod_name,))
89 else:
89 else:
90 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
90 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
91
91
92 def qw_lol(indata):
92 def qw_lol(indata):
93 """qw_lol('a b') -> [['a','b']],
93 """qw_lol('a b') -> [['a','b']],
94 otherwise it's just a call to qw().
94 otherwise it's just a call to qw().
95
95
96 We need this to make sure the modules_some keys *always* end up as a
96 We need this to make sure the modules_some keys *always* end up as a
97 list of lists."""
97 list of lists."""
98
98
99 if type(indata) in StringTypes:
99 if type(indata) in StringTypes:
100 return [qw(indata)]
100 return [qw(indata)]
101 else:
101 else:
102 return qw(indata)
102 return qw(indata)
103
103
104 def ipmagic(arg_s):
104 def ipmagic(arg_s):
105 """Call a magic function by name.
105 """Call a magic function by name.
106
106
107 Input: a string containing the name of the magic function to call and any
107 Input: a string containing the name of the magic function to call and any
108 additional arguments to be passed to the magic.
108 additional arguments to be passed to the magic.
109
109
110 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
110 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
111 prompt:
111 prompt:
112
112
113 In[1]: %name -opt foo bar
113 In[1]: %name -opt foo bar
114
114
115 To call a magic without arguments, simply use ipmagic('name').
115 To call a magic without arguments, simply use ipmagic('name').
116
116
117 This provides a proper Python function to call IPython's magics in any
117 This provides a proper Python function to call IPython's magics in any
118 valid Python code you can type at the interpreter, including loops and
118 valid Python code you can type at the interpreter, including loops and
119 compound statements. It is added by IPython to the Python builtin
119 compound statements. It is added by IPython to the Python builtin
120 namespace upon initialization."""
120 namespace upon initialization."""
121
121
122 args = arg_s.split(' ',1)
122 args = arg_s.split(' ',1)
123 magic_name = args[0]
123 magic_name = args[0]
124 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
124 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
125 magic_name = magic_name[1:]
125 magic_name = magic_name[1:]
126 try:
126 try:
127 magic_args = args[1]
127 magic_args = args[1]
128 except IndexError:
128 except IndexError:
129 magic_args = ''
129 magic_args = ''
130 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
130 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
131 if fn is None:
131 if fn is None:
132 error("Magic function `%s` not found." % magic_name)
132 error("Magic function `%s` not found." % magic_name)
133 else:
133 else:
134 magic_args = __IPYTHON__.var_expand(magic_args)
134 magic_args = __IPYTHON__.var_expand(magic_args)
135 return fn(magic_args)
135 return fn(magic_args)
136
136
137 def ipalias(arg_s):
137 def ipalias(arg_s):
138 """Call an alias by name.
138 """Call an alias by name.
139
139
140 Input: a string containing the name of the alias to call and any
140 Input: a string containing the name of the alias to call and any
141 additional arguments to be passed to the magic.
141 additional arguments to be passed to the magic.
142
142
143 ipalias('name -opt foo bar') is equivalent to typing at the ipython
143 ipalias('name -opt foo bar') is equivalent to typing at the ipython
144 prompt:
144 prompt:
145
145
146 In[1]: name -opt foo bar
146 In[1]: name -opt foo bar
147
147
148 To call an alias without arguments, simply use ipalias('name').
148 To call an alias without arguments, simply use ipalias('name').
149
149
150 This provides a proper Python function to call IPython's aliases in any
150 This provides a proper Python function to call IPython's aliases in any
151 valid Python code you can type at the interpreter, including loops and
151 valid Python code you can type at the interpreter, including loops and
152 compound statements. It is added by IPython to the Python builtin
152 compound statements. It is added by IPython to the Python builtin
153 namespace upon initialization."""
153 namespace upon initialization."""
154
154
155 args = arg_s.split(' ',1)
155 args = arg_s.split(' ',1)
156 alias_name = args[0]
156 alias_name = args[0]
157 try:
157 try:
158 alias_args = args[1]
158 alias_args = args[1]
159 except IndexError:
159 except IndexError:
160 alias_args = ''
160 alias_args = ''
161 if alias_name in __IPYTHON__.alias_table:
161 if alias_name in __IPYTHON__.alias_table:
162 __IPYTHON__.call_alias(alias_name,alias_args)
162 __IPYTHON__.call_alias(alias_name,alias_args)
163 else:
163 else:
164 error("Alias `%s` not found." % alias_name)
164 error("Alias `%s` not found." % alias_name)
165
165
166 #-----------------------------------------------------------------------------
166 #-----------------------------------------------------------------------------
167 # Local use classes
167 # Local use classes
168 try:
168 try:
169 from IPython import FlexCompleter
169 from IPython import FlexCompleter
170
170
171 class MagicCompleter(FlexCompleter.Completer):
171 class MagicCompleter(FlexCompleter.Completer):
172 """Extension of the completer class to work on %-prefixed lines."""
172 """Extension of the completer class to work on %-prefixed lines."""
173
173
174 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
174 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
175 """MagicCompleter() -> completer
175 """MagicCompleter() -> completer
176
176
177 Return a completer object suitable for use by the readline library
177 Return a completer object suitable for use by the readline library
178 via readline.set_completer().
178 via readline.set_completer().
179
179
180 Inputs:
180 Inputs:
181
181
182 - shell: a pointer to the ipython shell itself. This is needed
182 - shell: a pointer to the ipython shell itself. This is needed
183 because this completer knows about magic functions, and those can
183 because this completer knows about magic functions, and those can
184 only be accessed via the ipython instance.
184 only be accessed via the ipython instance.
185
185
186 - namespace: an optional dict where completions are performed.
186 - namespace: an optional dict where completions are performed.
187
187
188 - The optional omit__names parameter sets the completer to omit the
188 - The optional omit__names parameter sets the completer to omit the
189 'magic' names (__magicname__) for python objects unless the text
189 'magic' names (__magicname__) for python objects unless the text
190 to be completed explicitly starts with one or more underscores.
190 to be completed explicitly starts with one or more underscores.
191
191
192 - If alias_table is supplied, it should be a dictionary of aliases
192 - If alias_table is supplied, it should be a dictionary of aliases
193 to complete. """
193 to complete. """
194
194
195 FlexCompleter.Completer.__init__(self,namespace)
195 FlexCompleter.Completer.__init__(self,namespace)
196 self.magic_prefix = shell.name+'.magic_'
196 self.magic_prefix = shell.name+'.magic_'
197 self.magic_escape = shell.ESC_MAGIC
197 self.magic_escape = shell.ESC_MAGIC
198 self.readline = FlexCompleter.readline
198 self.readline = FlexCompleter.readline
199 delims = self.readline.get_completer_delims()
199 delims = self.readline.get_completer_delims()
200 delims = delims.replace(self.magic_escape,'')
200 delims = delims.replace(self.magic_escape,'')
201 self.readline.set_completer_delims(delims)
201 self.readline.set_completer_delims(delims)
202 self.get_line_buffer = self.readline.get_line_buffer
202 self.get_line_buffer = self.readline.get_line_buffer
203 self.omit__names = omit__names
203 self.omit__names = omit__names
204 self.merge_completions = shell.rc.readline_merge_completions
204 self.merge_completions = shell.rc.readline_merge_completions
205
205
206 if alias_table is None:
206 if alias_table is None:
207 alias_table = {}
207 alias_table = {}
208 self.alias_table = alias_table
208 self.alias_table = alias_table
209 # Regexp to split filenames with spaces in them
209 # Regexp to split filenames with spaces in them
210 self.space_name_re = re.compile(r'([^\\] )')
210 self.space_name_re = re.compile(r'([^\\] )')
211 # Hold a local ref. to glob.glob for speed
211 # Hold a local ref. to glob.glob for speed
212 self.glob = glob.glob
212 self.glob = glob.glob
213 # Special handling of backslashes needed in win32 platforms
213 # Special handling of backslashes needed in win32 platforms
214 if sys.platform == "win32":
214 if sys.platform == "win32":
215 self.clean_glob = self._clean_glob_win32
215 self.clean_glob = self._clean_glob_win32
216 else:
216 else:
217 self.clean_glob = self._clean_glob
217 self.clean_glob = self._clean_glob
218 self.matchers = [self.python_matches,
218 self.matchers = [self.python_matches,
219 self.file_matches,
219 self.file_matches,
220 self.alias_matches,
220 self.alias_matches,
221 self.python_func_kw_matches]
221 self.python_func_kw_matches]
222
222
223 # Code contributed by Alex Schmolck, for ipython/emacs integration
223 # Code contributed by Alex Schmolck, for ipython/emacs integration
224 def all_completions(self, text):
224 def all_completions(self, text):
225 """Return all possible completions for the benefit of emacs."""
225 """Return all possible completions for the benefit of emacs."""
226
226
227 completions = []
227 completions = []
228 try:
228 try:
229 for i in xrange(sys.maxint):
229 for i in xrange(sys.maxint):
230 res = self.complete(text, i)
230 res = self.complete(text, i)
231
231
232 if not res: break
232 if not res: break
233
233
234 completions.append(res)
234 completions.append(res)
235 #XXX workaround for ``notDefined.<tab>``
235 #XXX workaround for ``notDefined.<tab>``
236 except NameError:
236 except NameError:
237 pass
237 pass
238 return completions
238 return completions
239 # /end Alex Schmolck code.
239 # /end Alex Schmolck code.
240
240
241 def _clean_glob(self,text):
241 def _clean_glob(self,text):
242 return self.glob("%s*" % text)
242 return self.glob("%s*" % text)
243
243
244 def _clean_glob_win32(self,text):
244 def _clean_glob_win32(self,text):
245 return [f.replace("\\","/")
245 return [f.replace("\\","/")
246 for f in self.glob("%s*" % text)]
246 for f in self.glob("%s*" % text)]
247
247
248 def file_matches(self, text):
248 def file_matches(self, text):
249 """Match filneames, expanding ~USER type strings.
249 """Match filneames, expanding ~USER type strings.
250
250
251 Most of the seemingly convoluted logic in this completer is an
251 Most of the seemingly convoluted logic in this completer is an
252 attempt to handle filenames with spaces in them. And yet it's not
252 attempt to handle filenames with spaces in them. And yet it's not
253 quite perfect, because Python's readline doesn't expose all of the
253 quite perfect, because Python's readline doesn't expose all of the
254 GNU readline details needed for this to be done correctly.
254 GNU readline details needed for this to be done correctly.
255
255
256 For a filename with a space in it, the printed completions will be
256 For a filename with a space in it, the printed completions will be
257 only the parts after what's already been typed (instead of the
257 only the parts after what's already been typed (instead of the
258 full completions, as is normally done). I don't think with the
258 full completions, as is normally done). I don't think with the
259 current (as of Python 2.3) Python readline it's possible to do
259 current (as of Python 2.3) Python readline it's possible to do
260 better."""
260 better."""
261
261
262 #print 'Completer->file_matches: <%s>' % text # dbg
262 #print 'Completer->file_matches: <%s>' % text # dbg
263
263
264 # chars that require escaping with backslash - i.e. chars
264 # chars that require escaping with backslash - i.e. chars
265 # that readline treats incorrectly as delimiters, but we
265 # that readline treats incorrectly as delimiters, but we
266 # don't want to treat as delimiters in filename matching
266 # don't want to treat as delimiters in filename matching
267 # when escaped with backslash
267 # when escaped with backslash
268
268
269 protectables = ' ()[]{}'
269 protectables = ' ()[]{}'
270
270
271 def protect_filename(s):
271 def protect_filename(s):
272 return "".join([(ch in protectables and '\\' + ch or ch)
272 return "".join([(ch in protectables and '\\' + ch or ch)
273 for ch in s])
273 for ch in s])
274
274
275 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
275 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
276 open_quotes = 0 # track strings with open quotes
276 open_quotes = 0 # track strings with open quotes
277 try:
277 try:
278 lsplit = shlex_split(lbuf)[-1]
278 lsplit = shlex_split(lbuf)[-1]
279 except ValueError:
279 except ValueError:
280 # typically an unmatched ", or backslash without escaped char.
280 # typically an unmatched ", or backslash without escaped char.
281 if lbuf.count('"')==1:
281 if lbuf.count('"')==1:
282 open_quotes = 1
282 open_quotes = 1
283 lsplit = lbuf.split('"')[-1]
283 lsplit = lbuf.split('"')[-1]
284 elif lbuf.count("'")==1:
284 elif lbuf.count("'")==1:
285 open_quotes = 1
285 open_quotes = 1
286 lsplit = lbuf.split("'")[-1]
286 lsplit = lbuf.split("'")[-1]
287 else:
287 else:
288 return None
288 return None
289 except IndexError:
289 except IndexError:
290 # tab pressed on empty line
290 # tab pressed on empty line
291 lsplit = ""
291 lsplit = ""
292
292
293 if lsplit != protect_filename(lsplit):
293 if lsplit != protect_filename(lsplit):
294 # if protectables are found, do matching on the whole escaped
294 # if protectables are found, do matching on the whole escaped
295 # name
295 # name
296 has_protectables = 1
296 has_protectables = 1
297 text0,text = text,lsplit
297 text0,text = text,lsplit
298 else:
298 else:
299 has_protectables = 0
299 has_protectables = 0
300 text = os.path.expanduser(text)
300 text = os.path.expanduser(text)
301
301
302 if text == "":
302 if text == "":
303 return [protect_filename(f) for f in self.glob("*")]
303 return [protect_filename(f) for f in self.glob("*")]
304
304
305 m0 = self.clean_glob(text.replace('\\',''))
305 m0 = self.clean_glob(text.replace('\\',''))
306 if has_protectables:
306 if has_protectables:
307 # If we had protectables, we need to revert our changes to the
307 # If we had protectables, we need to revert our changes to the
308 # beginning of filename so that we don't double-write the part
308 # beginning of filename so that we don't double-write the part
309 # of the filename we have so far
309 # of the filename we have so far
310 len_lsplit = len(lsplit)
310 len_lsplit = len(lsplit)
311 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
311 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
312 else:
312 else:
313 if open_quotes:
313 if open_quotes:
314 # if we have a string with an open quote, we don't need to
314 # if we have a string with an open quote, we don't need to
315 # protect the names at all (and we _shouldn't_, as it
315 # protect the names at all (and we _shouldn't_, as it
316 # would cause bugs when the filesystem call is made).
316 # would cause bugs when the filesystem call is made).
317 matches = m0
317 matches = m0
318 else:
318 else:
319 matches = [protect_filename(f) for f in m0]
319 matches = [protect_filename(f) for f in m0]
320 if len(matches) == 1 and os.path.isdir(matches[0]):
320 if len(matches) == 1 and os.path.isdir(matches[0]):
321 # Takes care of links to directories also. Use '/'
321 # Takes care of links to directories also. Use '/'
322 # explicitly, even under Windows, so that name completions
322 # explicitly, even under Windows, so that name completions
323 # don't end up escaped.
323 # don't end up escaped.
324 matches[0] += '/'
324 matches[0] += '/'
325 return matches
325 return matches
326
326
327 def alias_matches(self, text):
327 def alias_matches(self, text):
328 """Match internal system aliases"""
328 """Match internal system aliases"""
329 #print 'Completer->alias_matches:',text # dbg
329 #print 'Completer->alias_matches:',text # dbg
330 text = os.path.expanduser(text)
330 text = os.path.expanduser(text)
331 aliases = self.alias_table.keys()
331 aliases = self.alias_table.keys()
332 if text == "":
332 if text == "":
333 return aliases
333 return aliases
334 else:
334 else:
335 return [alias for alias in aliases if alias.startswith(text)]
335 return [alias for alias in aliases if alias.startswith(text)]
336
336
337 def python_matches(self,text):
337 def python_matches(self,text):
338 """Match attributes or global python names"""
338 """Match attributes or global python names"""
339 #print 'Completer->python_matches' # dbg
339 #print 'Completer->python_matches' # dbg
340 if "." in text:
340 if "." in text:
341 try:
341 try:
342 matches = self.attr_matches(text)
342 matches = self.attr_matches(text)
343 if text.endswith('.') and self.omit__names:
343 if text.endswith('.') and self.omit__names:
344 if self.omit__names == 1:
344 if self.omit__names == 1:
345 # true if txt is _not_ a __ name, false otherwise:
345 # true if txt is _not_ a __ name, false otherwise:
346 no__name = (lambda txt:
346 no__name = (lambda txt:
347 re.match(r'.*\.__.*?__',txt) is None)
347 re.match(r'.*\.__.*?__',txt) is None)
348 else:
348 else:
349 # true if txt is _not_ a _ name, false otherwise:
349 # true if txt is _not_ a _ name, false otherwise:
350 no__name = (lambda txt:
350 no__name = (lambda txt:
351 re.match(r'.*\._.*?',txt) is None)
351 re.match(r'.*\._.*?',txt) is None)
352 matches = filter(no__name, matches)
352 matches = filter(no__name, matches)
353 except NameError:
353 except NameError:
354 # catches <undefined attributes>.<tab>
354 # catches <undefined attributes>.<tab>
355 matches = []
355 matches = []
356 else:
356 else:
357 matches = self.global_matches(text)
357 matches = self.global_matches(text)
358 # this is so completion finds magics when automagic is on:
358 # this is so completion finds magics when automagic is on:
359 if matches == [] and not text.startswith(os.sep):
359 if matches == [] and not text.startswith(os.sep):
360 matches = self.attr_matches(self.magic_prefix+text)
360 matches = self.attr_matches(self.magic_prefix+text)
361 return matches
361 return matches
362
362
363 def _default_arguments(self, obj):
363 def _default_arguments(self, obj):
364 """Return the list of default arguments of obj if it is callable,
364 """Return the list of default arguments of obj if it is callable,
365 or empty list otherwise."""
365 or empty list otherwise."""
366
366
367 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
367 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
368 # for classes, check for __init__,__new__
368 # for classes, check for __init__,__new__
369 if inspect.isclass(obj):
369 if inspect.isclass(obj):
370 obj = (getattr(obj,'__init__',None) or
370 obj = (getattr(obj,'__init__',None) or
371 getattr(obj,'__new__',None))
371 getattr(obj,'__new__',None))
372 # for all others, check if they are __call__able
372 # for all others, check if they are __call__able
373 elif hasattr(obj, '__call__'):
373 elif hasattr(obj, '__call__'):
374 obj = obj.__call__
374 obj = obj.__call__
375 # XXX: is there a way to handle the builtins ?
375 # XXX: is there a way to handle the builtins ?
376 try:
376 try:
377 args,_,_1,defaults = inspect.getargspec(obj)
377 args,_,_1,defaults = inspect.getargspec(obj)
378 if defaults:
378 if defaults:
379 return args[-len(defaults):]
379 return args[-len(defaults):]
380 except TypeError: pass
380 except TypeError: pass
381 return []
381 return []
382
382
383 def python_func_kw_matches(self,text):
383 def python_func_kw_matches(self,text):
384 """Match named parameters (kwargs) of the last open function"""
384 """Match named parameters (kwargs) of the last open function"""
385
385
386 if "." in text: # a parameter cannot be dotted
386 if "." in text: # a parameter cannot be dotted
387 return []
387 return []
388 try: regexp = self.__funcParamsRegex
388 try: regexp = self.__funcParamsRegex
389 except AttributeError:
389 except AttributeError:
390 regexp = self.__funcParamsRegex = re.compile(r'''
390 regexp = self.__funcParamsRegex = re.compile(r'''
391 '.*?' | # single quoted strings or
391 '.*?' | # single quoted strings or
392 ".*?" | # double quoted strings or
392 ".*?" | # double quoted strings or
393 \w+ | # identifier
393 \w+ | # identifier
394 \S # other characters
394 \S # other characters
395 ''', re.VERBOSE | re.DOTALL)
395 ''', re.VERBOSE | re.DOTALL)
396 # 1. find the nearest identifier that comes before an unclosed
396 # 1. find the nearest identifier that comes before an unclosed
397 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
397 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
398 tokens = regexp.findall(self.get_line_buffer())
398 tokens = regexp.findall(self.get_line_buffer())
399 tokens.reverse()
399 tokens.reverse()
400 iterTokens = iter(tokens); openPar = 0
400 iterTokens = iter(tokens); openPar = 0
401 for token in iterTokens:
401 for token in iterTokens:
402 if token == ')':
402 if token == ')':
403 openPar -= 1
403 openPar -= 1
404 elif token == '(':
404 elif token == '(':
405 openPar += 1
405 openPar += 1
406 if openPar > 0:
406 if openPar > 0:
407 # found the last unclosed parenthesis
407 # found the last unclosed parenthesis
408 break
408 break
409 else:
409 else:
410 return []
410 return []
411 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
411 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
412 ids = []
412 ids = []
413 isId = re.compile(r'\w+$').match
413 isId = re.compile(r'\w+$').match
414 while True:
414 while True:
415 try:
415 try:
416 ids.append(iterTokens.next())
416 ids.append(iterTokens.next())
417 if not isId(ids[-1]):
417 if not isId(ids[-1]):
418 ids.pop(); break
418 ids.pop(); break
419 if not iterTokens.next() == '.':
419 if not iterTokens.next() == '.':
420 break
420 break
421 except StopIteration:
421 except StopIteration:
422 break
422 break
423 # lookup the candidate callable matches either using global_matches
423 # lookup the candidate callable matches either using global_matches
424 # or attr_matches for dotted names
424 # or attr_matches for dotted names
425 if len(ids) == 1:
425 if len(ids) == 1:
426 callableMatches = self.global_matches(ids[0])
426 callableMatches = self.global_matches(ids[0])
427 else:
427 else:
428 callableMatches = self.attr_matches('.'.join(ids[::-1]))
428 callableMatches = self.attr_matches('.'.join(ids[::-1]))
429 argMatches = []
429 argMatches = []
430 for callableMatch in callableMatches:
430 for callableMatch in callableMatches:
431 try: namedArgs = self._default_arguments(eval(callableMatch,
431 try: namedArgs = self._default_arguments(eval(callableMatch,
432 self.namespace))
432 self.namespace))
433 except: continue
433 except: continue
434 for namedArg in namedArgs:
434 for namedArg in namedArgs:
435 if namedArg.startswith(text):
435 if namedArg.startswith(text):
436 argMatches.append("%s=" %namedArg)
436 argMatches.append("%s=" %namedArg)
437 return argMatches
437 return argMatches
438
438
439 def complete(self, text, state):
439 def complete(self, text, state):
440 """Return the next possible completion for 'text'.
440 """Return the next possible completion for 'text'.
441
441
442 This is called successively with state == 0, 1, 2, ... until it
442 This is called successively with state == 0, 1, 2, ... until it
443 returns None. The completion should begin with 'text'. """
443 returns None. The completion should begin with 'text'. """
444
444
445 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
445 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
446 magic_escape = self.magic_escape
446 magic_escape = self.magic_escape
447 magic_prefix = self.magic_prefix
447 magic_prefix = self.magic_prefix
448
448
449 try:
449 try:
450 if text.startswith(magic_escape):
450 if text.startswith(magic_escape):
451 text = text.replace(magic_escape,magic_prefix)
451 text = text.replace(magic_escape,magic_prefix)
452 elif text.startswith('~'):
452 elif text.startswith('~'):
453 text = os.path.expanduser(text)
453 text = os.path.expanduser(text)
454 if state == 0:
454 if state == 0:
455 # Extend the list of completions with the results of each
455 # Extend the list of completions with the results of each
456 # matcher, so we return results to the user from all
456 # matcher, so we return results to the user from all
457 # namespaces.
457 # namespaces.
458 if self.merge_completions:
458 if self.merge_completions:
459 self.matches = []
459 self.matches = []
460 for matcher in self.matchers:
460 for matcher in self.matchers:
461 self.matches.extend(matcher(text))
461 self.matches.extend(matcher(text))
462 else:
462 else:
463 for matcher in self.matchers:
463 for matcher in self.matchers:
464 self.matches = matcher(text)
464 self.matches = matcher(text)
465 if self.matches:
465 if self.matches:
466 break
466 break
467
467
468 try:
468 try:
469 return self.matches[state].replace(magic_prefix,magic_escape)
469 return self.matches[state].replace(magic_prefix,magic_escape)
470 except IndexError:
470 except IndexError:
471 return None
471 return None
472 except:
472 except:
473 # If completion fails, don't annoy the user.
473 # If completion fails, don't annoy the user.
474 pass
474 pass
475
475
476 except ImportError:
476 except ImportError:
477 pass # no readline support
477 pass # no readline support
478
478
479 except KeyError:
479 except KeyError:
480 pass # Windows doesn't set TERM, it doesn't matter
480 pass # Windows doesn't set TERM, it doesn't matter
481
481
482
482
483 class InputList(UserList.UserList):
483 class InputList(UserList.UserList):
484 """Class to store user input.
484 """Class to store user input.
485
485
486 It's basically a list, but slices return a string instead of a list, thus
486 It's basically a list, but slices return a string instead of a list, thus
487 allowing things like (assuming 'In' is an instance):
487 allowing things like (assuming 'In' is an instance):
488
488
489 exec In[4:7]
489 exec In[4:7]
490
490
491 or
491 or
492
492
493 exec In[5:9] + In[14] + In[21:25]"""
493 exec In[5:9] + In[14] + In[21:25]"""
494
494
495 def __getslice__(self,i,j):
495 def __getslice__(self,i,j):
496 return ''.join(UserList.UserList.__getslice__(self,i,j))
496 return ''.join(UserList.UserList.__getslice__(self,i,j))
497
497
498 #****************************************************************************
498 #****************************************************************************
499 # Local use exceptions
499 # Local use exceptions
500 class SpaceInInput(exceptions.Exception):
500 class SpaceInInput(exceptions.Exception):
501 pass
501 pass
502
502
503 #****************************************************************************
503 #****************************************************************************
504 # Main IPython class
504 # Main IPython class
505
505
506 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
506 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
507 """An enhanced console for Python."""
507 """An enhanced console for Python."""
508
508
509 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
509 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
510 user_ns = None,user_global_ns=None,banner2='',
510 user_ns = None,user_global_ns=None,banner2='',
511 custom_exceptions=((),None),embedded=False):
511 custom_exceptions=((),None),embedded=False):
512
512
513 # Put a reference to self in builtins so that any form of embedded or
513 # Put a reference to self in builtins so that any form of embedded or
514 # imported code can test for being inside IPython.
514 # imported code can test for being inside IPython.
515 __builtin__.__IPYTHON__ = self
515 __builtin__.__IPYTHON__ = self
516
516
517 # And load into builtins ipmagic/ipalias as well
517 # And load into builtins ipmagic/ipalias as well
518 __builtin__.ipmagic = ipmagic
518 __builtin__.ipmagic = ipmagic
519 __builtin__.ipalias = ipalias
519 __builtin__.ipalias = ipalias
520
520
521 # Add to __builtin__ other parts of IPython's public API
521 # Add to __builtin__ other parts of IPython's public API
522 __builtin__.ip_set_hook = self.set_hook
522 __builtin__.ip_set_hook = self.set_hook
523
523
524 # Keep in the builtins a flag for when IPython is active. We set it
524 # Keep in the builtins a flag for when IPython is active. We set it
525 # with setdefault so that multiple nested IPythons don't clobber one
525 # with setdefault so that multiple nested IPythons don't clobber one
526 # another. Each will increase its value by one upon being activated,
526 # another. Each will increase its value by one upon being activated,
527 # which also gives us a way to determine the nesting level.
527 # which also gives us a way to determine the nesting level.
528 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
528 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
529
529
530 # Inform the user of ipython's fast exit magics.
530 # Inform the user of ipython's fast exit magics.
531 _exit = ' Use %Exit or %Quit to exit without confirmation.'
531 _exit = ' Use %Exit or %Quit to exit without confirmation.'
532 __builtin__.exit += _exit
532 __builtin__.exit += _exit
533 __builtin__.quit += _exit
533 __builtin__.quit += _exit
534
534
535 # We need to know whether the instance is meant for embedding, since
535 # We need to know whether the instance is meant for embedding, since
536 # global/local namespaces need to be handled differently in that case
536 # global/local namespaces need to be handled differently in that case
537 self.embedded = embedded
537 self.embedded = embedded
538
538
539 # compiler command
539 # compiler command
540 self.compile = CommandCompiler()
540 self.compile = CommandCompiler()
541
541
542 # User input buffer
542 # User input buffer
543 self.buffer = []
543 self.buffer = []
544
544
545 # Default name given in compilation of code
545 # Default name given in compilation of code
546 self.filename = '<ipython console>'
546 self.filename = '<ipython console>'
547
547
548 # Create the namespace where the user will operate. user_ns is
548 # Create the namespace where the user will operate. user_ns is
549 # normally the only one used, and it is passed to the exec calls as
549 # normally the only one used, and it is passed to the exec calls as
550 # the locals argument. But we do carry a user_global_ns namespace
550 # the locals argument. But we do carry a user_global_ns namespace
551 # given as the exec 'globals' argument, This is useful in embedding
551 # given as the exec 'globals' argument, This is useful in embedding
552 # situations where the ipython shell opens in a context where the
552 # situations where the ipython shell opens in a context where the
553 # distinction between locals and globals is meaningful.
553 # distinction between locals and globals is meaningful.
554
554
555 # FIXME. For some strange reason, __builtins__ is showing up at user
555 # FIXME. For some strange reason, __builtins__ is showing up at user
556 # level as a dict instead of a module. This is a manual fix, but I
556 # level as a dict instead of a module. This is a manual fix, but I
557 # should really track down where the problem is coming from. Alex
557 # should really track down where the problem is coming from. Alex
558 # Schmolck reported this problem first.
558 # Schmolck reported this problem first.
559
559
560 # A useful post by Alex Martelli on this topic:
560 # A useful post by Alex Martelli on this topic:
561 # Re: inconsistent value from __builtins__
561 # Re: inconsistent value from __builtins__
562 # Von: Alex Martelli <aleaxit@yahoo.com>
562 # Von: Alex Martelli <aleaxit@yahoo.com>
563 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
563 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
564 # Gruppen: comp.lang.python
564 # Gruppen: comp.lang.python
565 # Referenzen: 1
565 # Referenzen: 1
566
566
567 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
567 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
568 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
568 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
569 # > <type 'dict'>
569 # > <type 'dict'>
570 # > >>> print type(__builtins__)
570 # > >>> print type(__builtins__)
571 # > <type 'module'>
571 # > <type 'module'>
572 # > Is this difference in return value intentional?
572 # > Is this difference in return value intentional?
573
573
574 # Well, it's documented that '__builtins__' can be either a dictionary
574 # Well, it's documented that '__builtins__' can be either a dictionary
575 # or a module, and it's been that way for a long time. Whether it's
575 # or a module, and it's been that way for a long time. Whether it's
576 # intentional (or sensible), I don't know. In any case, the idea is that
576 # intentional (or sensible), I don't know. In any case, the idea is that
577 # if you need to access the built-in namespace directly, you should start
577 # if you need to access the built-in namespace directly, you should start
578 # with "import __builtin__" (note, no 's') which will definitely give you
578 # with "import __builtin__" (note, no 's') which will definitely give you
579 # a module. Yeah, it's somewhatΒ confusing:-(.
579 # a module. Yeah, it's somewhatΒ confusing:-(.
580
580
581 if user_ns is None:
581 if user_ns is None:
582 # Set __name__ to __main__ to better match the behavior of the
582 # Set __name__ to __main__ to better match the behavior of the
583 # normal interpreter.
583 # normal interpreter.
584 user_ns = {'__name__' :'__main__',
584 user_ns = {'__name__' :'__main__',
585 '__builtins__' : __builtin__,
585 '__builtins__' : __builtin__,
586 }
586 }
587
587
588 if user_global_ns is None:
588 if user_global_ns is None:
589 user_global_ns = {}
589 user_global_ns = {}
590
590
591 # Assign namespaces
591 # Assign namespaces
592 # This is the namespace where all normal user variables live
592 # This is the namespace where all normal user variables live
593 self.user_ns = user_ns
593 self.user_ns = user_ns
594 # Embedded instances require a separate namespace for globals.
594 # Embedded instances require a separate namespace for globals.
595 # Normally this one is unused by non-embedded instances.
595 # Normally this one is unused by non-embedded instances.
596 self.user_global_ns = user_global_ns
596 self.user_global_ns = user_global_ns
597 # A namespace to keep track of internal data structures to prevent
597 # A namespace to keep track of internal data structures to prevent
598 # them from cluttering user-visible stuff. Will be updated later
598 # them from cluttering user-visible stuff. Will be updated later
599 self.internal_ns = {}
599 self.internal_ns = {}
600
600
601 # Namespace of system aliases. Each entry in the alias
601 # Namespace of system aliases. Each entry in the alias
602 # table must be a 2-tuple of the form (N,name), where N is the number
602 # table must be a 2-tuple of the form (N,name), where N is the number
603 # of positional arguments of the alias.
603 # of positional arguments of the alias.
604 self.alias_table = {}
604 self.alias_table = {}
605
605
606 # A table holding all the namespaces IPython deals with, so that
606 # A table holding all the namespaces IPython deals with, so that
607 # introspection facilities can search easily.
607 # introspection facilities can search easily.
608 self.ns_table = {'user':user_ns,
608 self.ns_table = {'user':user_ns,
609 'user_global':user_global_ns,
609 'user_global':user_global_ns,
610 'alias':self.alias_table,
610 'alias':self.alias_table,
611 'internal':self.internal_ns,
611 'internal':self.internal_ns,
612 'builtin':__builtin__.__dict__
612 'builtin':__builtin__.__dict__
613 }
613 }
614
614
615 # The user namespace MUST have a pointer to the shell itself.
615 # The user namespace MUST have a pointer to the shell itself.
616 self.user_ns[name] = self
616 self.user_ns[name] = self
617
617
618 # We need to insert into sys.modules something that looks like a
618 # We need to insert into sys.modules something that looks like a
619 # module but which accesses the IPython namespace, for shelve and
619 # module but which accesses the IPython namespace, for shelve and
620 # pickle to work interactively. Normally they rely on getting
620 # pickle to work interactively. Normally they rely on getting
621 # everything out of __main__, but for embedding purposes each IPython
621 # everything out of __main__, but for embedding purposes each IPython
622 # instance has its own private namespace, so we can't go shoving
622 # instance has its own private namespace, so we can't go shoving
623 # everything into __main__.
623 # everything into __main__.
624
624
625 try:
625 try:
626 main_name = self.user_ns['__name__']
626 main_name = self.user_ns['__name__']
627 except KeyError:
627 except KeyError:
628 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
628 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
629 else:
629 else:
630 #print "pickle hack in place" # dbg
630 #print "pickle hack in place" # dbg
631 sys.modules[main_name] = FakeModule(self.user_ns)
631 sys.modules[main_name] = FakeModule(self.user_ns)
632
632
633 # List of input with multi-line handling.
633 # List of input with multi-line handling.
634 # Fill its zero entry, user counter starts at 1
634 # Fill its zero entry, user counter starts at 1
635 self.input_hist = InputList(['\n'])
635 self.input_hist = InputList(['\n'])
636
636
637 # list of visited directories
637 # list of visited directories
638 try:
638 try:
639 self.dir_hist = [os.getcwd()]
639 self.dir_hist = [os.getcwd()]
640 except IOError, e:
640 except IOError, e:
641 self.dir_hist = []
641 self.dir_hist = []
642
642
643 # dict of output history
643 # dict of output history
644 self.output_hist = {}
644 self.output_hist = {}
645
645
646 # dict of things NOT to alias (keywords, builtins and some special magics)
646 # dict of things NOT to alias (keywords, builtins and some special magics)
647 no_alias = {}
647 no_alias = {}
648 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
648 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
649 for key in keyword.kwlist + no_alias_magics:
649 for key in keyword.kwlist + no_alias_magics:
650 no_alias[key] = 1
650 no_alias[key] = 1
651 no_alias.update(__builtin__.__dict__)
651 no_alias.update(__builtin__.__dict__)
652 self.no_alias = no_alias
652 self.no_alias = no_alias
653
653
654 # make global variables for user access to these
654 # make global variables for user access to these
655 self.user_ns['_ih'] = self.input_hist
655 self.user_ns['_ih'] = self.input_hist
656 self.user_ns['_oh'] = self.output_hist
656 self.user_ns['_oh'] = self.output_hist
657 self.user_ns['_dh'] = self.dir_hist
657 self.user_ns['_dh'] = self.dir_hist
658
658
659 # user aliases to input and output histories
659 # user aliases to input and output histories
660 self.user_ns['In'] = self.input_hist
660 self.user_ns['In'] = self.input_hist
661 self.user_ns['Out'] = self.output_hist
661 self.user_ns['Out'] = self.output_hist
662
662
663 # Store the actual shell's name
663 # Store the actual shell's name
664 self.name = name
664 self.name = name
665
665
666 # Object variable to store code object waiting execution. This is
666 # Object variable to store code object waiting execution. This is
667 # used mainly by the multithreaded shells, but it can come in handy in
667 # used mainly by the multithreaded shells, but it can come in handy in
668 # other situations. No need to use a Queue here, since it's a single
668 # other situations. No need to use a Queue here, since it's a single
669 # item which gets cleared once run.
669 # item which gets cleared once run.
670 self.code_to_run = None
670 self.code_to_run = None
671
671
672 # Job manager (for jobs run as background threads)
672 # Job manager (for jobs run as background threads)
673 self.jobs = BackgroundJobManager()
673 self.jobs = BackgroundJobManager()
674 # Put the job manager into builtins so it's always there.
674 # Put the job manager into builtins so it's always there.
675 __builtin__.jobs = self.jobs
675 __builtin__.jobs = self.jobs
676
676
677 # escapes for automatic behavior on the command line
677 # escapes for automatic behavior on the command line
678 self.ESC_SHELL = '!'
678 self.ESC_SHELL = '!'
679 self.ESC_HELP = '?'
679 self.ESC_HELP = '?'
680 self.ESC_MAGIC = '%'
680 self.ESC_MAGIC = '%'
681 self.ESC_QUOTE = ','
681 self.ESC_QUOTE = ','
682 self.ESC_QUOTE2 = ';'
682 self.ESC_QUOTE2 = ';'
683 self.ESC_PAREN = '/'
683 self.ESC_PAREN = '/'
684
684
685 # And their associated handlers
685 # And their associated handlers
686 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
686 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
687 self.ESC_QUOTE:self.handle_auto,
687 self.ESC_QUOTE:self.handle_auto,
688 self.ESC_QUOTE2:self.handle_auto,
688 self.ESC_QUOTE2:self.handle_auto,
689 self.ESC_MAGIC:self.handle_magic,
689 self.ESC_MAGIC:self.handle_magic,
690 self.ESC_HELP:self.handle_help,
690 self.ESC_HELP:self.handle_help,
691 self.ESC_SHELL:self.handle_shell_escape,
691 self.ESC_SHELL:self.handle_shell_escape,
692 }
692 }
693
693
694 # class initializations
694 # class initializations
695 Logger.__init__(self,log_ns = self.user_ns)
695 Logger.__init__(self,log_ns = self.user_ns)
696 Magic.__init__(self,self)
696 Magic.__init__(self,self)
697
697
698 # an ugly hack to get a pointer to the shell, so I can start writing
698 # an ugly hack to get a pointer to the shell, so I can start writing
699 # magic code via this pointer instead of the current mixin salad.
699 # magic code via this pointer instead of the current mixin salad.
700 Magic.set_shell(self,self)
700 Magic.set_shell(self,self)
701
701
702 # Python source parser/formatter for syntax highlighting
702 # Python source parser/formatter for syntax highlighting
703 pyformat = Parser().format
703 pyformat = Parser().format
704 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
704 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
705
705
706 # hooks holds pointers used for user-side customizations
706 # hooks holds pointers used for user-side customizations
707 self.hooks = Struct()
707 self.hooks = Struct()
708
708
709 # Set all default hooks, defined in the IPython.hooks module.
709 # Set all default hooks, defined in the IPython.hooks module.
710 hooks = IPython.hooks
710 hooks = IPython.hooks
711 for hook_name in hooks.__all__:
711 for hook_name in hooks.__all__:
712 self.set_hook(hook_name,getattr(hooks,hook_name))
712 self.set_hook(hook_name,getattr(hooks,hook_name))
713
713
714 # Flag to mark unconditional exit
714 # Flag to mark unconditional exit
715 self.exit_now = False
715 self.exit_now = False
716
716
717 self.usage_min = """\
717 self.usage_min = """\
718 An enhanced console for Python.
718 An enhanced console for Python.
719 Some of its features are:
719 Some of its features are:
720 - Readline support if the readline library is present.
720 - Readline support if the readline library is present.
721 - Tab completion in the local namespace.
721 - Tab completion in the local namespace.
722 - Logging of input, see command-line options.
722 - Logging of input, see command-line options.
723 - System shell escape via ! , eg !ls.
723 - System shell escape via ! , eg !ls.
724 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
724 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
725 - Keeps track of locally defined variables via %who, %whos.
725 - Keeps track of locally defined variables via %who, %whos.
726 - Show object information with a ? eg ?x or x? (use ?? for more info).
726 - Show object information with a ? eg ?x or x? (use ?? for more info).
727 """
727 """
728 if usage: self.usage = usage
728 if usage: self.usage = usage
729 else: self.usage = self.usage_min
729 else: self.usage = self.usage_min
730
730
731 # Storage
731 # Storage
732 self.rc = rc # This will hold all configuration information
732 self.rc = rc # This will hold all configuration information
733 self.inputcache = []
733 self.inputcache = []
734 self._boundcache = []
734 self._boundcache = []
735 self.pager = 'less'
735 self.pager = 'less'
736 # temporary files used for various purposes. Deleted at exit.
736 # temporary files used for various purposes. Deleted at exit.
737 self.tempfiles = []
737 self.tempfiles = []
738
738
739 # Keep track of readline usage (later set by init_readline)
739 # Keep track of readline usage (later set by init_readline)
740 self.has_readline = 0
740 self.has_readline = 0
741
741
742 # for pushd/popd management
742 # for pushd/popd management
743 try:
743 try:
744 self.home_dir = get_home_dir()
744 self.home_dir = get_home_dir()
745 except HomeDirError,msg:
745 except HomeDirError,msg:
746 fatal(msg)
746 fatal(msg)
747
747
748 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
748 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
749
749
750 # Functions to call the underlying shell.
750 # Functions to call the underlying shell.
751
751
752 # utility to expand user variables via Itpl
752 # utility to expand user variables via Itpl
753 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
753 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
754 self.user_ns))
754 self.user_ns))
755 # The first is similar to os.system, but it doesn't return a value,
755 # The first is similar to os.system, but it doesn't return a value,
756 # and it allows interpolation of variables in the user's namespace.
756 # and it allows interpolation of variables in the user's namespace.
757 self.system = lambda cmd: shell(self.var_expand(cmd),
757 self.system = lambda cmd: shell(self.var_expand(cmd),
758 header='IPython system call: ',
758 header='IPython system call: ',
759 verbose=self.rc.system_verbose)
759 verbose=self.rc.system_verbose)
760 # These are for getoutput and getoutputerror:
760 # These are for getoutput and getoutputerror:
761 self.getoutput = lambda cmd: \
761 self.getoutput = lambda cmd: \
762 getoutput(self.var_expand(cmd),
762 getoutput(self.var_expand(cmd),
763 header='IPython system call: ',
763 header='IPython system call: ',
764 verbose=self.rc.system_verbose)
764 verbose=self.rc.system_verbose)
765 self.getoutputerror = lambda cmd: \
765 self.getoutputerror = lambda cmd: \
766 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
766 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
767 self.user_ns)),
767 self.user_ns)),
768 header='IPython system call: ',
768 header='IPython system call: ',
769 verbose=self.rc.system_verbose)
769 verbose=self.rc.system_verbose)
770
770
771 # RegExp for splitting line contents into pre-char//first
771 # RegExp for splitting line contents into pre-char//first
772 # word-method//rest. For clarity, each group in on one line.
772 # word-method//rest. For clarity, each group in on one line.
773
773
774 # WARNING: update the regexp if the above escapes are changed, as they
774 # WARNING: update the regexp if the above escapes are changed, as they
775 # are hardwired in.
775 # are hardwired in.
776
776
777 # Don't get carried away with trying to make the autocalling catch too
777 # Don't get carried away with trying to make the autocalling catch too
778 # much: it's better to be conservative rather than to trigger hidden
778 # much: it's better to be conservative rather than to trigger hidden
779 # evals() somewhere and end up causing side effects.
779 # evals() somewhere and end up causing side effects.
780
780
781 self.line_split = re.compile(r'^([\s*,;/])'
781 self.line_split = re.compile(r'^([\s*,;/])'
782 r'([\?\w\.]+\w*\s*)'
782 r'([\?\w\.]+\w*\s*)'
783 r'(\(?.*$)')
783 r'(\(?.*$)')
784
784
785 # Original re, keep around for a while in case changes break something
785 # Original re, keep around for a while in case changes break something
786 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
786 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
787 # r'(\s*[\?\w\.]+\w*\s*)'
787 # r'(\s*[\?\w\.]+\w*\s*)'
788 # r'(\(?.*$)')
788 # r'(\(?.*$)')
789
789
790 # RegExp to identify potential function names
790 # RegExp to identify potential function names
791 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
791 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
792 # RegExp to exclude strings with this start from autocalling
792 # RegExp to exclude strings with this start from autocalling
793 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
793 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
794 # try to catch also methods for stuff in lists/tuples/dicts: off
794 # try to catch also methods for stuff in lists/tuples/dicts: off
795 # (experimental). For this to work, the line_split regexp would need
795 # (experimental). For this to work, the line_split regexp would need
796 # to be modified so it wouldn't break things at '['. That line is
796 # to be modified so it wouldn't break things at '['. That line is
797 # nasty enough that I shouldn't change it until I can test it _well_.
797 # nasty enough that I shouldn't change it until I can test it _well_.
798 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
798 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
799
799
800 # keep track of where we started running (mainly for crash post-mortem)
800 # keep track of where we started running (mainly for crash post-mortem)
801 self.starting_dir = os.getcwd()
801 self.starting_dir = os.getcwd()
802
802
803 # Attributes for Logger mixin class, make defaults here
803 # Attributes for Logger mixin class, make defaults here
804 self._dolog = 0
804 self._dolog = 0
805 self.LOG = ''
805 self.LOG = ''
806 self.LOGDEF = '.InteractiveShell.log'
806 self.LOGDEF = '.InteractiveShell.log'
807 self.LOGMODE = 'over'
807 self.LOGMODE = 'over'
808 self.LOGHEAD = Itpl(
808 self.LOGHEAD = Itpl(
809 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
809 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
810 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
810 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
811 #log# opts = $self.rc.opts
811 #log# opts = $self.rc.opts
812 #log# args = $self.rc.args
812 #log# args = $self.rc.args
813 #log# It is safe to make manual edits below here.
813 #log# It is safe to make manual edits below here.
814 #log#-----------------------------------------------------------------------
814 #log#-----------------------------------------------------------------------
815 """)
815 """)
816 # Various switches which can be set
816 # Various switches which can be set
817 self.CACHELENGTH = 5000 # this is cheap, it's just text
817 self.CACHELENGTH = 5000 # this is cheap, it's just text
818 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
818 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
819 self.banner2 = banner2
819 self.banner2 = banner2
820
820
821 # TraceBack handlers:
821 # TraceBack handlers:
822 # Need two, one for syntax errors and one for other exceptions.
822 # Need two, one for syntax errors and one for other exceptions.
823 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
823 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
824 # This one is initialized with an offset, meaning we always want to
824 # This one is initialized with an offset, meaning we always want to
825 # remove the topmost item in the traceback, which is our own internal
825 # remove the topmost item in the traceback, which is our own internal
826 # code. Valid modes: ['Plain','Context','Verbose']
826 # code. Valid modes: ['Plain','Context','Verbose']
827 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
827 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
828 color_scheme='NoColor',
828 color_scheme='NoColor',
829 tb_offset = 1)
829 tb_offset = 1)
830 # and add any custom exception handlers the user may have specified
830 # and add any custom exception handlers the user may have specified
831 self.set_custom_exc(*custom_exceptions)
831 self.set_custom_exc(*custom_exceptions)
832
832
833 # Object inspector
833 # Object inspector
834 ins_colors = OInspect.InspectColors
834 ins_colors = OInspect.InspectColors
835 code_colors = PyColorize.ANSICodeColors
835 code_colors = PyColorize.ANSICodeColors
836 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
836 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
837 self.autoindent = 0
837 self.autoindent = 0
838
838
839 # Make some aliases automatically
839 # Make some aliases automatically
840 # Prepare list of shell aliases to auto-define
840 # Prepare list of shell aliases to auto-define
841 if os.name == 'posix':
841 if os.name == 'posix':
842 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
842 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
843 'mv mv -i','rm rm -i','cp cp -i',
843 'mv mv -i','rm rm -i','cp cp -i',
844 'cat cat','less less','clear clear',
844 'cat cat','less less','clear clear',
845 # a better ls
845 # a better ls
846 'ls ls -F',
846 'ls ls -F',
847 # long ls
847 # long ls
848 'll ls -lF',
848 'll ls -lF',
849 # color ls
849 # color ls
850 'lc ls -F -o --color',
850 'lc ls -F -o --color',
851 # ls normal files only
851 # ls normal files only
852 'lf ls -F -o --color %l | grep ^-',
852 'lf ls -F -o --color %l | grep ^-',
853 # ls symbolic links
853 # ls symbolic links
854 'lk ls -F -o --color %l | grep ^l',
854 'lk ls -F -o --color %l | grep ^l',
855 # directories or links to directories,
855 # directories or links to directories,
856 'ldir ls -F -o --color %l | grep /$',
856 'ldir ls -F -o --color %l | grep /$',
857 # things which are executable
857 # things which are executable
858 'lx ls -F -o --color %l | grep ^-..x',
858 'lx ls -F -o --color %l | grep ^-..x',
859 )
859 )
860 elif os.name in ['nt','dos']:
860 elif os.name in ['nt','dos']:
861 auto_alias = ('dir dir /on', 'ls dir /on',
861 auto_alias = ('dir dir /on', 'ls dir /on',
862 'ddir dir /ad /on', 'ldir dir /ad /on',
862 'ddir dir /ad /on', 'ldir dir /ad /on',
863 'mkdir mkdir','rmdir rmdir','echo echo',
863 'mkdir mkdir','rmdir rmdir','echo echo',
864 'ren ren','cls cls','copy copy')
864 'ren ren','cls cls','copy copy')
865 else:
865 else:
866 auto_alias = ()
866 auto_alias = ()
867 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
867 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
868 # Call the actual (public) initializer
868 # Call the actual (public) initializer
869 self.init_auto_alias()
869 self.init_auto_alias()
870 # end __init__
870 # end __init__
871
871
872 def set_hook(self,name,hook):
872 def set_hook(self,name,hook):
873 """set_hook(name,hook) -> sets an internal IPython hook.
873 """set_hook(name,hook) -> sets an internal IPython hook.
874
874
875 IPython exposes some of its internal API as user-modifiable hooks. By
875 IPython exposes some of its internal API as user-modifiable hooks. By
876 resetting one of these hooks, you can modify IPython's behavior to
876 resetting one of these hooks, you can modify IPython's behavior to
877 call at runtime your own routines."""
877 call at runtime your own routines."""
878
878
879 # At some point in the future, this should validate the hook before it
879 # At some point in the future, this should validate the hook before it
880 # accepts it. Probably at least check that the hook takes the number
880 # accepts it. Probably at least check that the hook takes the number
881 # of args it's supposed to.
881 # of args it's supposed to.
882 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
882 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
883
883
884 def set_custom_exc(self,exc_tuple,handler):
884 def set_custom_exc(self,exc_tuple,handler):
885 """set_custom_exc(exc_tuple,handler)
885 """set_custom_exc(exc_tuple,handler)
886
886
887 Set a custom exception handler, which will be called if any of the
887 Set a custom exception handler, which will be called if any of the
888 exceptions in exc_tuple occur in the mainloop (specifically, in the
888 exceptions in exc_tuple occur in the mainloop (specifically, in the
889 runcode() method.
889 runcode() method.
890
890
891 Inputs:
891 Inputs:
892
892
893 - exc_tuple: a *tuple* of valid exceptions to call the defined
893 - exc_tuple: a *tuple* of valid exceptions to call the defined
894 handler for. It is very important that you use a tuple, and NOT A
894 handler for. It is very important that you use a tuple, and NOT A
895 LIST here, because of the way Python's except statement works. If
895 LIST here, because of the way Python's except statement works. If
896 you only want to trap a single exception, use a singleton tuple:
896 you only want to trap a single exception, use a singleton tuple:
897
897
898 exc_tuple == (MyCustomException,)
898 exc_tuple == (MyCustomException,)
899
899
900 - handler: this must be defined as a function with the following
900 - handler: this must be defined as a function with the following
901 basic interface: def my_handler(self,etype,value,tb).
901 basic interface: def my_handler(self,etype,value,tb).
902
902
903 This will be made into an instance method (via new.instancemethod)
903 This will be made into an instance method (via new.instancemethod)
904 of IPython itself, and it will be called if any of the exceptions
904 of IPython itself, and it will be called if any of the exceptions
905 listed in the exc_tuple are caught. If the handler is None, an
905 listed in the exc_tuple are caught. If the handler is None, an
906 internal basic one is used, which just prints basic info.
906 internal basic one is used, which just prints basic info.
907
907
908 WARNING: by putting in your own exception handler into IPython's main
908 WARNING: by putting in your own exception handler into IPython's main
909 execution loop, you run a very good chance of nasty crashes. This
909 execution loop, you run a very good chance of nasty crashes. This
910 facility should only be used if you really know what you are doing."""
910 facility should only be used if you really know what you are doing."""
911
911
912 assert type(exc_tuple)==type(()) , \
912 assert type(exc_tuple)==type(()) , \
913 "The custom exceptions must be given AS A TUPLE."
913 "The custom exceptions must be given AS A TUPLE."
914
914
915 def dummy_handler(self,etype,value,tb):
915 def dummy_handler(self,etype,value,tb):
916 print '*** Simple custom exception handler ***'
916 print '*** Simple custom exception handler ***'
917 print 'Exception type :',etype
917 print 'Exception type :',etype
918 print 'Exception value:',value
918 print 'Exception value:',value
919 print 'Traceback :',tb
919 print 'Traceback :',tb
920 print 'Source code :','\n'.join(self.buffer)
920 print 'Source code :','\n'.join(self.buffer)
921
921
922 if handler is None: handler = dummy_handler
922 if handler is None: handler = dummy_handler
923
923
924 self.CustomTB = new.instancemethod(handler,self,self.__class__)
924 self.CustomTB = new.instancemethod(handler,self,self.__class__)
925 self.custom_exceptions = exc_tuple
925 self.custom_exceptions = exc_tuple
926
926
927 def set_custom_completer(self,completer,pos=0):
927 def set_custom_completer(self,completer,pos=0):
928 """set_custom_completer(completer,pos=0)
928 """set_custom_completer(completer,pos=0)
929
929
930 Adds a new custom completer function.
930 Adds a new custom completer function.
931
931
932 The position argument (defaults to 0) is the index in the completers
932 The position argument (defaults to 0) is the index in the completers
933 list where you want the completer to be inserted."""
933 list where you want the completer to be inserted."""
934
934
935 newcomp = new.instancemethod(completer,self.Completer,
935 newcomp = new.instancemethod(completer,self.Completer,
936 self.Completer.__class__)
936 self.Completer.__class__)
937 self.Completer.matchers.insert(pos,newcomp)
937 self.Completer.matchers.insert(pos,newcomp)
938
938
939 def complete(self,text):
939 def complete(self,text):
940 """Return a sorted list of all possible completions on text.
940 """Return a sorted list of all possible completions on text.
941
941
942 Inputs:
942 Inputs:
943
943
944 - text: a string of text to be completed on.
944 - text: a string of text to be completed on.
945
945
946 This is a wrapper around the completion mechanism, similar to what
946 This is a wrapper around the completion mechanism, similar to what
947 readline does at the command line when the TAB key is hit. By
947 readline does at the command line when the TAB key is hit. By
948 exposing it as a method, it can be used by other non-readline
948 exposing it as a method, it can be used by other non-readline
949 environments (such as GUIs) for text completion.
949 environments (such as GUIs) for text completion.
950
950
951 Simple usage example:
951 Simple usage example:
952
952
953 In [1]: x = 'hello'
953 In [1]: x = 'hello'
954
954
955 In [2]: __IP.complete('x.l')
955 In [2]: __IP.complete('x.l')
956 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
956 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
957
957
958 complete = self.Completer.complete
958 complete = self.Completer.complete
959 state = 0
959 state = 0
960 # use a dict so we get unique keys, since ipyhton's multiple
960 # use a dict so we get unique keys, since ipyhton's multiple
961 # completers can return duplicates.
961 # completers can return duplicates.
962 comps = {}
962 comps = {}
963 while True:
963 while True:
964 newcomp = complete(text,state)
964 newcomp = complete(text,state)
965 if newcomp is None:
965 if newcomp is None:
966 break
966 break
967 comps[newcomp] = 1
967 comps[newcomp] = 1
968 state += 1
968 state += 1
969 outcomps = comps.keys()
969 outcomps = comps.keys()
970 outcomps.sort()
970 outcomps.sort()
971 return outcomps
971 return outcomps
972
972
973 def set_completer_frame(self, frame):
974 if frame:
975 ns = frame.f_globals.copy()
976 ns.update(frame.f_locals)
977 self.Completer.namespace = ns
978 else:
979 self.Completer.namespace = self.user_ns
980
973 def post_config_initialization(self):
981 def post_config_initialization(self):
974 """Post configuration init method
982 """Post configuration init method
975
983
976 This is called after the configuration files have been processed to
984 This is called after the configuration files have been processed to
977 'finalize' the initialization."""
985 'finalize' the initialization."""
978
986
979 rc = self.rc
987 rc = self.rc
980
988
981 # Load readline proper
989 # Load readline proper
982 if rc.readline:
990 if rc.readline:
983 self.init_readline()
991 self.init_readline()
984
992
985 # Set user colors (don't do it in the constructor above so that it doesn't
993 # Set user colors (don't do it in the constructor above so that it doesn't
986 # crash if colors option is invalid)
994 # crash if colors option is invalid)
987 self.magic_colors(rc.colors)
995 self.magic_colors(rc.colors)
988
996
989 # Load user aliases
997 # Load user aliases
990 for alias in rc.alias:
998 for alias in rc.alias:
991 self.magic_alias(alias)
999 self.magic_alias(alias)
992
1000
993 # dynamic data that survives through sessions
1001 # dynamic data that survives through sessions
994 # XXX make the filename a config option?
1002 # XXX make the filename a config option?
995 persist_base = 'persist'
1003 persist_base = 'persist'
996 if rc.profile:
1004 if rc.profile:
997 persist_base += '_%s' % rc.profile
1005 persist_base += '_%s' % rc.profile
998 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
1006 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
999
1007
1000 try:
1008 try:
1001 self.persist = pickle.load(file(self.persist_fname))
1009 self.persist = pickle.load(file(self.persist_fname))
1002 except:
1010 except:
1003 self.persist = {}
1011 self.persist = {}
1004
1012
1005 def init_auto_alias(self):
1013 def init_auto_alias(self):
1006 """Define some aliases automatically.
1014 """Define some aliases automatically.
1007
1015
1008 These are ALL parameter-less aliases"""
1016 These are ALL parameter-less aliases"""
1009 for alias,cmd in self.auto_alias:
1017 for alias,cmd in self.auto_alias:
1010 self.alias_table[alias] = (0,cmd)
1018 self.alias_table[alias] = (0,cmd)
1011
1019
1012 def alias_table_validate(self,verbose=0):
1020 def alias_table_validate(self,verbose=0):
1013 """Update information about the alias table.
1021 """Update information about the alias table.
1014
1022
1015 In particular, make sure no Python keywords/builtins are in it."""
1023 In particular, make sure no Python keywords/builtins are in it."""
1016
1024
1017 no_alias = self.no_alias
1025 no_alias = self.no_alias
1018 for k in self.alias_table.keys():
1026 for k in self.alias_table.keys():
1019 if k in no_alias:
1027 if k in no_alias:
1020 del self.alias_table[k]
1028 del self.alias_table[k]
1021 if verbose:
1029 if verbose:
1022 print ("Deleting alias <%s>, it's a Python "
1030 print ("Deleting alias <%s>, it's a Python "
1023 "keyword or builtin." % k)
1031 "keyword or builtin." % k)
1024
1032
1025 def set_autoindent(self,value=None):
1033 def set_autoindent(self,value=None):
1026 """Set the autoindent flag, checking for readline support.
1034 """Set the autoindent flag, checking for readline support.
1027
1035
1028 If called with no arguments, it acts as a toggle."""
1036 If called with no arguments, it acts as a toggle."""
1029
1037
1030 if not self.has_readline:
1038 if not self.has_readline:
1031 if os.name == 'posix':
1039 if os.name == 'posix':
1032 warn("The auto-indent feature requires the readline library")
1040 warn("The auto-indent feature requires the readline library")
1033 self.autoindent = 0
1041 self.autoindent = 0
1034 return
1042 return
1035 if value is None:
1043 if value is None:
1036 self.autoindent = not self.autoindent
1044 self.autoindent = not self.autoindent
1037 else:
1045 else:
1038 self.autoindent = value
1046 self.autoindent = value
1039
1047
1040 def rc_set_toggle(self,rc_field,value=None):
1048 def rc_set_toggle(self,rc_field,value=None):
1041 """Set or toggle a field in IPython's rc config. structure.
1049 """Set or toggle a field in IPython's rc config. structure.
1042
1050
1043 If called with no arguments, it acts as a toggle.
1051 If called with no arguments, it acts as a toggle.
1044
1052
1045 If called with a non-existent field, the resulting AttributeError
1053 If called with a non-existent field, the resulting AttributeError
1046 exception will propagate out."""
1054 exception will propagate out."""
1047
1055
1048 rc_val = getattr(self.rc,rc_field)
1056 rc_val = getattr(self.rc,rc_field)
1049 if value is None:
1057 if value is None:
1050 value = not rc_val
1058 value = not rc_val
1051 setattr(self.rc,rc_field,value)
1059 setattr(self.rc,rc_field,value)
1052
1060
1053 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1061 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1054 """Install the user configuration directory.
1062 """Install the user configuration directory.
1055
1063
1056 Can be called when running for the first time or to upgrade the user's
1064 Can be called when running for the first time or to upgrade the user's
1057 .ipython/ directory with the mode parameter. Valid modes are 'install'
1065 .ipython/ directory with the mode parameter. Valid modes are 'install'
1058 and 'upgrade'."""
1066 and 'upgrade'."""
1059
1067
1060 def wait():
1068 def wait():
1061 try:
1069 try:
1062 raw_input("Please press <RETURN> to start IPython.")
1070 raw_input("Please press <RETURN> to start IPython.")
1063 except EOFError:
1071 except EOFError:
1064 print >> Term.cout
1072 print >> Term.cout
1065 print '*'*70
1073 print '*'*70
1066
1074
1067 cwd = os.getcwd() # remember where we started
1075 cwd = os.getcwd() # remember where we started
1068 glb = glob.glob
1076 glb = glob.glob
1069 print '*'*70
1077 print '*'*70
1070 if mode == 'install':
1078 if mode == 'install':
1071 print \
1079 print \
1072 """Welcome to IPython. I will try to create a personal configuration directory
1080 """Welcome to IPython. I will try to create a personal configuration directory
1073 where you can customize many aspects of IPython's functionality in:\n"""
1081 where you can customize many aspects of IPython's functionality in:\n"""
1074 else:
1082 else:
1075 print 'I am going to upgrade your configuration in:'
1083 print 'I am going to upgrade your configuration in:'
1076
1084
1077 print ipythondir
1085 print ipythondir
1078
1086
1079 rcdirend = os.path.join('IPython','UserConfig')
1087 rcdirend = os.path.join('IPython','UserConfig')
1080 cfg = lambda d: os.path.join(d,rcdirend)
1088 cfg = lambda d: os.path.join(d,rcdirend)
1081 try:
1089 try:
1082 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1090 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1083 except IOError:
1091 except IOError:
1084 warning = """
1092 warning = """
1085 Installation error. IPython's directory was not found.
1093 Installation error. IPython's directory was not found.
1086
1094
1087 Check the following:
1095 Check the following:
1088
1096
1089 The ipython/IPython directory should be in a directory belonging to your
1097 The ipython/IPython directory should be in a directory belonging to your
1090 PYTHONPATH environment variable (that is, it should be in a directory
1098 PYTHONPATH environment variable (that is, it should be in a directory
1091 belonging to sys.path). You can copy it explicitly there or just link to it.
1099 belonging to sys.path). You can copy it explicitly there or just link to it.
1092
1100
1093 IPython will proceed with builtin defaults.
1101 IPython will proceed with builtin defaults.
1094 """
1102 """
1095 warn(warning)
1103 warn(warning)
1096 wait()
1104 wait()
1097 return
1105 return
1098
1106
1099 if mode == 'install':
1107 if mode == 'install':
1100 try:
1108 try:
1101 shutil.copytree(rcdir,ipythondir)
1109 shutil.copytree(rcdir,ipythondir)
1102 os.chdir(ipythondir)
1110 os.chdir(ipythondir)
1103 rc_files = glb("ipythonrc*")
1111 rc_files = glb("ipythonrc*")
1104 for rc_file in rc_files:
1112 for rc_file in rc_files:
1105 os.rename(rc_file,rc_file+rc_suffix)
1113 os.rename(rc_file,rc_file+rc_suffix)
1106 except:
1114 except:
1107 warning = """
1115 warning = """
1108
1116
1109 There was a problem with the installation:
1117 There was a problem with the installation:
1110 %s
1118 %s
1111 Try to correct it or contact the developers if you think it's a bug.
1119 Try to correct it or contact the developers if you think it's a bug.
1112 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1120 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1113 warn(warning)
1121 warn(warning)
1114 wait()
1122 wait()
1115 return
1123 return
1116
1124
1117 elif mode == 'upgrade':
1125 elif mode == 'upgrade':
1118 try:
1126 try:
1119 os.chdir(ipythondir)
1127 os.chdir(ipythondir)
1120 except:
1128 except:
1121 print """
1129 print """
1122 Can not upgrade: changing to directory %s failed. Details:
1130 Can not upgrade: changing to directory %s failed. Details:
1123 %s
1131 %s
1124 """ % (ipythondir,sys.exc_info()[1])
1132 """ % (ipythondir,sys.exc_info()[1])
1125 wait()
1133 wait()
1126 return
1134 return
1127 else:
1135 else:
1128 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1136 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1129 for new_full_path in sources:
1137 for new_full_path in sources:
1130 new_filename = os.path.basename(new_full_path)
1138 new_filename = os.path.basename(new_full_path)
1131 if new_filename.startswith('ipythonrc'):
1139 if new_filename.startswith('ipythonrc'):
1132 new_filename = new_filename + rc_suffix
1140 new_filename = new_filename + rc_suffix
1133 # The config directory should only contain files, skip any
1141 # The config directory should only contain files, skip any
1134 # directories which may be there (like CVS)
1142 # directories which may be there (like CVS)
1135 if os.path.isdir(new_full_path):
1143 if os.path.isdir(new_full_path):
1136 continue
1144 continue
1137 if os.path.exists(new_filename):
1145 if os.path.exists(new_filename):
1138 old_file = new_filename+'.old'
1146 old_file = new_filename+'.old'
1139 if os.path.exists(old_file):
1147 if os.path.exists(old_file):
1140 os.remove(old_file)
1148 os.remove(old_file)
1141 os.rename(new_filename,old_file)
1149 os.rename(new_filename,old_file)
1142 shutil.copy(new_full_path,new_filename)
1150 shutil.copy(new_full_path,new_filename)
1143 else:
1151 else:
1144 raise ValueError,'unrecognized mode for install:',`mode`
1152 raise ValueError,'unrecognized mode for install:',`mode`
1145
1153
1146 # Fix line-endings to those native to each platform in the config
1154 # Fix line-endings to those native to each platform in the config
1147 # directory.
1155 # directory.
1148 try:
1156 try:
1149 os.chdir(ipythondir)
1157 os.chdir(ipythondir)
1150 except:
1158 except:
1151 print """
1159 print """
1152 Problem: changing to directory %s failed.
1160 Problem: changing to directory %s failed.
1153 Details:
1161 Details:
1154 %s
1162 %s
1155
1163
1156 Some configuration files may have incorrect line endings. This should not
1164 Some configuration files may have incorrect line endings. This should not
1157 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1165 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1158 wait()
1166 wait()
1159 else:
1167 else:
1160 for fname in glb('ipythonrc*'):
1168 for fname in glb('ipythonrc*'):
1161 try:
1169 try:
1162 native_line_ends(fname,backup=0)
1170 native_line_ends(fname,backup=0)
1163 except IOError:
1171 except IOError:
1164 pass
1172 pass
1165
1173
1166 if mode == 'install':
1174 if mode == 'install':
1167 print """
1175 print """
1168 Successful installation!
1176 Successful installation!
1169
1177
1170 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1178 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1171 IPython manual (there are both HTML and PDF versions supplied with the
1179 IPython manual (there are both HTML and PDF versions supplied with the
1172 distribution) to make sure that your system environment is properly configured
1180 distribution) to make sure that your system environment is properly configured
1173 to take advantage of IPython's features."""
1181 to take advantage of IPython's features."""
1174 else:
1182 else:
1175 print """
1183 print """
1176 Successful upgrade!
1184 Successful upgrade!
1177
1185
1178 All files in your directory:
1186 All files in your directory:
1179 %(ipythondir)s
1187 %(ipythondir)s
1180 which would have been overwritten by the upgrade were backed up with a .old
1188 which would have been overwritten by the upgrade were backed up with a .old
1181 extension. If you had made particular customizations in those files you may
1189 extension. If you had made particular customizations in those files you may
1182 want to merge them back into the new files.""" % locals()
1190 want to merge them back into the new files.""" % locals()
1183 wait()
1191 wait()
1184 os.chdir(cwd)
1192 os.chdir(cwd)
1185 # end user_setup()
1193 # end user_setup()
1186
1194
1187 def atexit_operations(self):
1195 def atexit_operations(self):
1188 """This will be executed at the time of exit.
1196 """This will be executed at the time of exit.
1189
1197
1190 Saving of persistent data should be performed here. """
1198 Saving of persistent data should be performed here. """
1191
1199
1192 # input history
1200 # input history
1193 self.savehist()
1201 self.savehist()
1194
1202
1195 # Cleanup all tempfiles left around
1203 # Cleanup all tempfiles left around
1196 for tfile in self.tempfiles:
1204 for tfile in self.tempfiles:
1197 try:
1205 try:
1198 os.unlink(tfile)
1206 os.unlink(tfile)
1199 except OSError:
1207 except OSError:
1200 pass
1208 pass
1201
1209
1202 # save the "persistent data" catch-all dictionary
1210 # save the "persistent data" catch-all dictionary
1203 try:
1211 try:
1204 pickle.dump(self.persist, open(self.persist_fname,"w"))
1212 pickle.dump(self.persist, open(self.persist_fname,"w"))
1205 except:
1213 except:
1206 print "*** ERROR *** persistent data saving failed."
1214 print "*** ERROR *** persistent data saving failed."
1207
1215
1208 def savehist(self):
1216 def savehist(self):
1209 """Save input history to a file (via readline library)."""
1217 """Save input history to a file (via readline library)."""
1210 try:
1218 try:
1211 self.readline.write_history_file(self.histfile)
1219 self.readline.write_history_file(self.histfile)
1212 except:
1220 except:
1213 print 'Unable to save IPython command history to file: ' + \
1221 print 'Unable to save IPython command history to file: ' + \
1214 `self.histfile`
1222 `self.histfile`
1215
1223
1216 def pre_readline(self):
1224 def pre_readline(self):
1217 """readline hook to be used at the start of each line.
1225 """readline hook to be used at the start of each line.
1218
1226
1219 Currently it handles auto-indent only."""
1227 Currently it handles auto-indent only."""
1220
1228
1221 self.readline.insert_text(' '* self.readline_indent)
1229 self.readline.insert_text(' '* self.readline_indent)
1222
1230
1223 def init_readline(self):
1231 def init_readline(self):
1224 """Command history completion/saving/reloading."""
1232 """Command history completion/saving/reloading."""
1225 try:
1233 try:
1226 import readline
1234 import readline
1227 self.Completer = MagicCompleter(self,
1235 self.Completer = MagicCompleter(self,
1228 self.user_ns,
1236 self.user_ns,
1229 self.rc.readline_omit__names,
1237 self.rc.readline_omit__names,
1230 self.alias_table)
1238 self.alias_table)
1231 except ImportError,NameError:
1239 except ImportError,NameError:
1232 # If FlexCompleter failed to import, MagicCompleter won't be
1240 # If FlexCompleter failed to import, MagicCompleter won't be
1233 # defined. This can happen because of a problem with readline
1241 # defined. This can happen because of a problem with readline
1234 self.has_readline = 0
1242 self.has_readline = 0
1235 # no point in bugging windows users with this every time:
1243 # no point in bugging windows users with this every time:
1236 if os.name == 'posix':
1244 if os.name == 'posix':
1237 warn('Readline services not available on this platform.')
1245 warn('Readline services not available on this platform.')
1238 else:
1246 else:
1239 import atexit
1247 import atexit
1240
1248
1241 # Platform-specific configuration
1249 # Platform-specific configuration
1242 if os.name == 'nt':
1250 if os.name == 'nt':
1243 # readline under Windows modifies the default exit behavior
1251 # readline under Windows modifies the default exit behavior
1244 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1252 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1245 __builtin__.exit = __builtin__.quit = \
1253 __builtin__.exit = __builtin__.quit = \
1246 ('Use Ctrl-D (i.e. EOF) to exit. '
1254 ('Use Ctrl-D (i.e. EOF) to exit. '
1247 'Use %Exit or %Quit to exit without confirmation.')
1255 'Use %Exit or %Quit to exit without confirmation.')
1248 self.readline_startup_hook = readline.set_pre_input_hook
1256 self.readline_startup_hook = readline.set_pre_input_hook
1249 else:
1257 else:
1250 self.readline_startup_hook = readline.set_startup_hook
1258 self.readline_startup_hook = readline.set_startup_hook
1251
1259
1252 # Load user's initrc file (readline config)
1260 # Load user's initrc file (readline config)
1253 inputrc_name = os.environ.get('INPUTRC')
1261 inputrc_name = os.environ.get('INPUTRC')
1254 if inputrc_name is None:
1262 if inputrc_name is None:
1255 home_dir = get_home_dir()
1263 home_dir = get_home_dir()
1256 if home_dir is not None:
1264 if home_dir is not None:
1257 inputrc_name = os.path.join(home_dir,'.inputrc')
1265 inputrc_name = os.path.join(home_dir,'.inputrc')
1258 if os.path.isfile(inputrc_name):
1266 if os.path.isfile(inputrc_name):
1259 try:
1267 try:
1260 readline.read_init_file(inputrc_name)
1268 readline.read_init_file(inputrc_name)
1261 except:
1269 except:
1262 warn('Problems reading readline initialization file <%s>'
1270 warn('Problems reading readline initialization file <%s>'
1263 % inputrc_name)
1271 % inputrc_name)
1264
1272
1265 self.has_readline = 1
1273 self.has_readline = 1
1266 self.readline = readline
1274 self.readline = readline
1267 self.readline_indent = 0 # for auto-indenting via readline
1275 self.readline_indent = 0 # for auto-indenting via readline
1268 # save this in sys so embedded copies can restore it properly
1276 # save this in sys so embedded copies can restore it properly
1269 sys.ipcompleter = self.Completer.complete
1277 sys.ipcompleter = self.Completer.complete
1270 readline.set_completer(self.Completer.complete)
1278 readline.set_completer(self.Completer.complete)
1271
1279
1272 # Configure readline according to user's prefs
1280 # Configure readline according to user's prefs
1273 for rlcommand in self.rc.readline_parse_and_bind:
1281 for rlcommand in self.rc.readline_parse_and_bind:
1274 readline.parse_and_bind(rlcommand)
1282 readline.parse_and_bind(rlcommand)
1275
1283
1276 # remove some chars from the delimiters list
1284 # remove some chars from the delimiters list
1277 delims = readline.get_completer_delims()
1285 delims = readline.get_completer_delims()
1278 delims = delims.translate(string._idmap,
1286 delims = delims.translate(string._idmap,
1279 self.rc.readline_remove_delims)
1287 self.rc.readline_remove_delims)
1280 readline.set_completer_delims(delims)
1288 readline.set_completer_delims(delims)
1281 # otherwise we end up with a monster history after a while:
1289 # otherwise we end up with a monster history after a while:
1282 readline.set_history_length(1000)
1290 readline.set_history_length(1000)
1283 try:
1291 try:
1284 #print '*** Reading readline history' # dbg
1292 #print '*** Reading readline history' # dbg
1285 readline.read_history_file(self.histfile)
1293 readline.read_history_file(self.histfile)
1286 except IOError:
1294 except IOError:
1287 pass # It doesn't exist yet.
1295 pass # It doesn't exist yet.
1288
1296
1289 atexit.register(self.atexit_operations)
1297 atexit.register(self.atexit_operations)
1290 del atexit
1298 del atexit
1291
1299
1292 # Configure auto-indent for all platforms
1300 # Configure auto-indent for all platforms
1293 self.set_autoindent(self.rc.autoindent)
1301 self.set_autoindent(self.rc.autoindent)
1294
1302
1295 def showsyntaxerror(self, filename=None):
1303 def showsyntaxerror(self, filename=None):
1296 """Display the syntax error that just occurred.
1304 """Display the syntax error that just occurred.
1297
1305
1298 This doesn't display a stack trace because there isn't one.
1306 This doesn't display a stack trace because there isn't one.
1299
1307
1300 If a filename is given, it is stuffed in the exception instead
1308 If a filename is given, it is stuffed in the exception instead
1301 of what was there before (because Python's parser always uses
1309 of what was there before (because Python's parser always uses
1302 "<string>" when reading from a string).
1310 "<string>" when reading from a string).
1303 """
1311 """
1304 type, value, sys.last_traceback = sys.exc_info()
1312 type, value, sys.last_traceback = sys.exc_info()
1305 sys.last_type = type
1313 sys.last_type = type
1306 sys.last_value = value
1314 sys.last_value = value
1307 if filename and type is SyntaxError:
1315 if filename and type is SyntaxError:
1308 # Work hard to stuff the correct filename in the exception
1316 # Work hard to stuff the correct filename in the exception
1309 try:
1317 try:
1310 msg, (dummy_filename, lineno, offset, line) = value
1318 msg, (dummy_filename, lineno, offset, line) = value
1311 except:
1319 except:
1312 # Not the format we expect; leave it alone
1320 # Not the format we expect; leave it alone
1313 pass
1321 pass
1314 else:
1322 else:
1315 # Stuff in the right filename
1323 # Stuff in the right filename
1316 try:
1324 try:
1317 # Assume SyntaxError is a class exception
1325 # Assume SyntaxError is a class exception
1318 value = SyntaxError(msg, (filename, lineno, offset, line))
1326 value = SyntaxError(msg, (filename, lineno, offset, line))
1319 except:
1327 except:
1320 # If that failed, assume SyntaxError is a string
1328 # If that failed, assume SyntaxError is a string
1321 value = msg, (filename, lineno, offset, line)
1329 value = msg, (filename, lineno, offset, line)
1322 self.SyntaxTB(type,value,[])
1330 self.SyntaxTB(type,value,[])
1323
1331
1324 def debugger(self):
1332 def debugger(self):
1325 """Call the pdb debugger."""
1333 """Call the pdb debugger."""
1326
1334
1327 if not self.rc.pdb:
1335 if not self.rc.pdb:
1328 return
1336 return
1329 pdb.pm()
1337 pdb.pm()
1330
1338
1331 def showtraceback(self,exc_tuple = None,filename=None):
1339 def showtraceback(self,exc_tuple = None,filename=None):
1332 """Display the exception that just occurred."""
1340 """Display the exception that just occurred."""
1333
1341
1334 # Though this won't be called by syntax errors in the input line,
1342 # Though this won't be called by syntax errors in the input line,
1335 # there may be SyntaxError cases whith imported code.
1343 # there may be SyntaxError cases whith imported code.
1336 if exc_tuple is None:
1344 if exc_tuple is None:
1337 type, value, tb = sys.exc_info()
1345 type, value, tb = sys.exc_info()
1338 else:
1346 else:
1339 type, value, tb = exc_tuple
1347 type, value, tb = exc_tuple
1340 if type is SyntaxError:
1348 if type is SyntaxError:
1341 self.showsyntaxerror(filename)
1349 self.showsyntaxerror(filename)
1342 else:
1350 else:
1343 sys.last_type = type
1351 sys.last_type = type
1344 sys.last_value = value
1352 sys.last_value = value
1345 sys.last_traceback = tb
1353 sys.last_traceback = tb
1346 self.InteractiveTB()
1354 self.InteractiveTB()
1347 if self.InteractiveTB.call_pdb and self.has_readline:
1355 if self.InteractiveTB.call_pdb and self.has_readline:
1348 # pdb mucks up readline, fix it back
1356 # pdb mucks up readline, fix it back
1349 self.readline.set_completer(self.Completer.complete)
1357 self.readline.set_completer(self.Completer.complete)
1350
1358
1351 def update_cache(self, line):
1359 def update_cache(self, line):
1352 """puts line into cache"""
1360 """puts line into cache"""
1353 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1361 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1354 if len(self.inputcache) >= self.CACHELENGTH:
1362 if len(self.inputcache) >= self.CACHELENGTH:
1355 self.inputcache.pop() # This not :-)
1363 self.inputcache.pop() # This not :-)
1356
1364
1357 def mainloop(self,banner=None):
1365 def mainloop(self,banner=None):
1358 """Creates the local namespace and starts the mainloop.
1366 """Creates the local namespace and starts the mainloop.
1359
1367
1360 If an optional banner argument is given, it will override the
1368 If an optional banner argument is given, it will override the
1361 internally created default banner."""
1369 internally created default banner."""
1362
1370
1363 if self.rc.c: # Emulate Python's -c option
1371 if self.rc.c: # Emulate Python's -c option
1364 self.exec_init_cmd()
1372 self.exec_init_cmd()
1365 if banner is None:
1373 if banner is None:
1366 if self.rc.banner:
1374 if self.rc.banner:
1367 banner = self.BANNER+self.banner2
1375 banner = self.BANNER+self.banner2
1368 else:
1376 else:
1369 banner = ''
1377 banner = ''
1370 self.interact(banner)
1378 self.interact(banner)
1371
1379
1372 def exec_init_cmd(self):
1380 def exec_init_cmd(self):
1373 """Execute a command given at the command line.
1381 """Execute a command given at the command line.
1374
1382
1375 This emulates Python's -c option."""
1383 This emulates Python's -c option."""
1376
1384
1377 sys.argv = ['-c']
1385 sys.argv = ['-c']
1378 self.push(self.rc.c)
1386 self.push(self.rc.c)
1379
1387
1380 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1388 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1381 """Embeds IPython into a running python program.
1389 """Embeds IPython into a running python program.
1382
1390
1383 Input:
1391 Input:
1384
1392
1385 - header: An optional header message can be specified.
1393 - header: An optional header message can be specified.
1386
1394
1387 - local_ns, global_ns: working namespaces. If given as None, the
1395 - local_ns, global_ns: working namespaces. If given as None, the
1388 IPython-initialized one is updated with __main__.__dict__, so that
1396 IPython-initialized one is updated with __main__.__dict__, so that
1389 program variables become visible but user-specific configuration
1397 program variables become visible but user-specific configuration
1390 remains possible.
1398 remains possible.
1391
1399
1392 - stack_depth: specifies how many levels in the stack to go to
1400 - stack_depth: specifies how many levels in the stack to go to
1393 looking for namespaces (when local_ns and global_ns are None). This
1401 looking for namespaces (when local_ns and global_ns are None). This
1394 allows an intermediate caller to make sure that this function gets
1402 allows an intermediate caller to make sure that this function gets
1395 the namespace from the intended level in the stack. By default (0)
1403 the namespace from the intended level in the stack. By default (0)
1396 it will get its locals and globals from the immediate caller.
1404 it will get its locals and globals from the immediate caller.
1397
1405
1398 Warning: it's possible to use this in a program which is being run by
1406 Warning: it's possible to use this in a program which is being run by
1399 IPython itself (via %run), but some funny things will happen (a few
1407 IPython itself (via %run), but some funny things will happen (a few
1400 globals get overwritten). In the future this will be cleaned up, as
1408 globals get overwritten). In the future this will be cleaned up, as
1401 there is no fundamental reason why it can't work perfectly."""
1409 there is no fundamental reason why it can't work perfectly."""
1402
1410
1403 # Get locals and globals from caller
1411 # Get locals and globals from caller
1404 if local_ns is None or global_ns is None:
1412 if local_ns is None or global_ns is None:
1405 call_frame = sys._getframe(stack_depth).f_back
1413 call_frame = sys._getframe(stack_depth).f_back
1406
1414
1407 if local_ns is None:
1415 if local_ns is None:
1408 local_ns = call_frame.f_locals
1416 local_ns = call_frame.f_locals
1409 if global_ns is None:
1417 if global_ns is None:
1410 global_ns = call_frame.f_globals
1418 global_ns = call_frame.f_globals
1411
1419
1412 # Update namespaces and fire up interpreter
1420 # Update namespaces and fire up interpreter
1413 self.user_ns = local_ns
1421 self.user_ns = local_ns
1414 self.user_global_ns = global_ns
1422 self.user_global_ns = global_ns
1415
1423
1416 # Patch for global embedding to make sure that things don't overwrite
1424 # Patch for global embedding to make sure that things don't overwrite
1417 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1425 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1418 # FIXME. Test this a bit more carefully (the if.. is new)
1426 # FIXME. Test this a bit more carefully (the if.. is new)
1419 if local_ns is None and global_ns is None:
1427 if local_ns is None and global_ns is None:
1420 self.user_global_ns.update(__main__.__dict__)
1428 self.user_global_ns.update(__main__.__dict__)
1421
1429
1422 self.interact(header)
1430 self.interact(header)
1423
1431
1424 def interact(self, banner=None):
1432 def interact(self, banner=None):
1425 """Closely emulate the interactive Python console.
1433 """Closely emulate the interactive Python console.
1426
1434
1427 The optional banner argument specify the banner to print
1435 The optional banner argument specify the banner to print
1428 before the first interaction; by default it prints a banner
1436 before the first interaction; by default it prints a banner
1429 similar to the one printed by the real Python interpreter,
1437 similar to the one printed by the real Python interpreter,
1430 followed by the current class name in parentheses (so as not
1438 followed by the current class name in parentheses (so as not
1431 to confuse this with the real interpreter -- since it's so
1439 to confuse this with the real interpreter -- since it's so
1432 close!).
1440 close!).
1433
1441
1434 """
1442 """
1435 cprt = 'Type "copyright", "credits" or "license" for more information.'
1443 cprt = 'Type "copyright", "credits" or "license" for more information.'
1436 if banner is None:
1444 if banner is None:
1437 self.write("Python %s on %s\n%s\n(%s)\n" %
1445 self.write("Python %s on %s\n%s\n(%s)\n" %
1438 (sys.version, sys.platform, cprt,
1446 (sys.version, sys.platform, cprt,
1439 self.__class__.__name__))
1447 self.__class__.__name__))
1440 else:
1448 else:
1441 self.write(banner)
1449 self.write(banner)
1442
1450
1443 more = 0
1451 more = 0
1444
1452
1445 # Mark activity in the builtins
1453 # Mark activity in the builtins
1446 __builtin__.__dict__['__IPYTHON__active'] += 1
1454 __builtin__.__dict__['__IPYTHON__active'] += 1
1447
1455
1448 # exit_now is set by a call to %Exit or %Quit
1456 # exit_now is set by a call to %Exit or %Quit
1449 while not self.exit_now:
1457 while not self.exit_now:
1450 try:
1458 try:
1451 if more:
1459 if more:
1452 prompt = self.outputcache.prompt2
1460 prompt = self.outputcache.prompt2
1453 if self.autoindent:
1461 if self.autoindent:
1454 self.readline_startup_hook(self.pre_readline)
1462 self.readline_startup_hook(self.pre_readline)
1455 else:
1463 else:
1456 prompt = self.outputcache.prompt1
1464 prompt = self.outputcache.prompt1
1457 try:
1465 try:
1458 line = self.raw_input(prompt)
1466 line = self.raw_input(prompt)
1459 if self.autoindent:
1467 if self.autoindent:
1460 self.readline_startup_hook(None)
1468 self.readline_startup_hook(None)
1461 except EOFError:
1469 except EOFError:
1462 if self.autoindent:
1470 if self.autoindent:
1463 self.readline_startup_hook(None)
1471 self.readline_startup_hook(None)
1464 self.write("\n")
1472 self.write("\n")
1465 if self.rc.confirm_exit:
1473 if self.rc.confirm_exit:
1466 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1474 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1467 break
1475 break
1468 else:
1476 else:
1469 break
1477 break
1470 else:
1478 else:
1471 more = self.push(line)
1479 more = self.push(line)
1472 # Auto-indent management
1480 # Auto-indent management
1473 if self.autoindent:
1481 if self.autoindent:
1474 if line:
1482 if line:
1475 ini_spaces = re.match('^(\s+)',line)
1483 ini_spaces = re.match('^(\s+)',line)
1476 if ini_spaces:
1484 if ini_spaces:
1477 nspaces = ini_spaces.end()
1485 nspaces = ini_spaces.end()
1478 else:
1486 else:
1479 nspaces = 0
1487 nspaces = 0
1480 self.readline_indent = nspaces
1488 self.readline_indent = nspaces
1481
1489
1482 if line[-1] == ':':
1490 if line[-1] == ':':
1483 self.readline_indent += 4
1491 self.readline_indent += 4
1484 elif re.match(r'^\s+raise|^\s+return',line):
1492 elif re.match(r'^\s+raise|^\s+return',line):
1485 self.readline_indent -= 4
1493 self.readline_indent -= 4
1486 else:
1494 else:
1487 self.readline_indent = 0
1495 self.readline_indent = 0
1488
1496
1489 except KeyboardInterrupt:
1497 except KeyboardInterrupt:
1490 self.write("\nKeyboardInterrupt\n")
1498 self.write("\nKeyboardInterrupt\n")
1491 self.resetbuffer()
1499 self.resetbuffer()
1492 more = 0
1500 more = 0
1493 # keep cache in sync with the prompt counter:
1501 # keep cache in sync with the prompt counter:
1494 self.outputcache.prompt_count -= 1
1502 self.outputcache.prompt_count -= 1
1495
1503
1496 if self.autoindent:
1504 if self.autoindent:
1497 self.readline_indent = 0
1505 self.readline_indent = 0
1498
1506
1499 except bdb.BdbQuit:
1507 except bdb.BdbQuit:
1500 warn("The Python debugger has exited with a BdbQuit exception.\n"
1508 warn("The Python debugger has exited with a BdbQuit exception.\n"
1501 "Because of how pdb handles the stack, it is impossible\n"
1509 "Because of how pdb handles the stack, it is impossible\n"
1502 "for IPython to properly format this particular exception.\n"
1510 "for IPython to properly format this particular exception.\n"
1503 "IPython will resume normal operation.")
1511 "IPython will resume normal operation.")
1504
1512
1505 # We are off again...
1513 # We are off again...
1506 __builtin__.__dict__['__IPYTHON__active'] -= 1
1514 __builtin__.__dict__['__IPYTHON__active'] -= 1
1507
1515
1508 def excepthook(self, type, value, tb):
1516 def excepthook(self, type, value, tb):
1509 """One more defense for GUI apps that call sys.excepthook.
1517 """One more defense for GUI apps that call sys.excepthook.
1510
1518
1511 GUI frameworks like wxPython trap exceptions and call
1519 GUI frameworks like wxPython trap exceptions and call
1512 sys.excepthook themselves. I guess this is a feature that
1520 sys.excepthook themselves. I guess this is a feature that
1513 enables them to keep running after exceptions that would
1521 enables them to keep running after exceptions that would
1514 otherwise kill their mainloop. This is a bother for IPython
1522 otherwise kill their mainloop. This is a bother for IPython
1515 which excepts to catch all of the program exceptions with a try:
1523 which excepts to catch all of the program exceptions with a try:
1516 except: statement.
1524 except: statement.
1517
1525
1518 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1526 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1519 any app directly invokes sys.excepthook, it will look to the user like
1527 any app directly invokes sys.excepthook, it will look to the user like
1520 IPython crashed. In order to work around this, we can disable the
1528 IPython crashed. In order to work around this, we can disable the
1521 CrashHandler and replace it with this excepthook instead, which prints a
1529 CrashHandler and replace it with this excepthook instead, which prints a
1522 regular traceback using our InteractiveTB. In this fashion, apps which
1530 regular traceback using our InteractiveTB. In this fashion, apps which
1523 call sys.excepthook will generate a regular-looking exception from
1531 call sys.excepthook will generate a regular-looking exception from
1524 IPython, and the CrashHandler will only be triggered by real IPython
1532 IPython, and the CrashHandler will only be triggered by real IPython
1525 crashes.
1533 crashes.
1526
1534
1527 This hook should be used sparingly, only in places which are not likely
1535 This hook should be used sparingly, only in places which are not likely
1528 to be true IPython errors.
1536 to be true IPython errors.
1529 """
1537 """
1530
1538
1531 self.InteractiveTB(type, value, tb, tb_offset=0)
1539 self.InteractiveTB(type, value, tb, tb_offset=0)
1532 if self.InteractiveTB.call_pdb and self.has_readline:
1540 if self.InteractiveTB.call_pdb and self.has_readline:
1533 self.readline.set_completer(self.Completer.complete)
1541 self.readline.set_completer(self.Completer.complete)
1534
1542
1535 def call_alias(self,alias,rest=''):
1543 def call_alias(self,alias,rest=''):
1536 """Call an alias given its name and the rest of the line.
1544 """Call an alias given its name and the rest of the line.
1537
1545
1538 This function MUST be given a proper alias, because it doesn't make
1546 This function MUST be given a proper alias, because it doesn't make
1539 any checks when looking up into the alias table. The caller is
1547 any checks when looking up into the alias table. The caller is
1540 responsible for invoking it only with a valid alias."""
1548 responsible for invoking it only with a valid alias."""
1541
1549
1542 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1550 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1543 nargs,cmd = self.alias_table[alias]
1551 nargs,cmd = self.alias_table[alias]
1544 # Expand the %l special to be the user's input line
1552 # Expand the %l special to be the user's input line
1545 if cmd.find('%l') >= 0:
1553 if cmd.find('%l') >= 0:
1546 cmd = cmd.replace('%l',rest)
1554 cmd = cmd.replace('%l',rest)
1547 rest = ''
1555 rest = ''
1548 if nargs==0:
1556 if nargs==0:
1549 # Simple, argument-less aliases
1557 # Simple, argument-less aliases
1550 cmd = '%s %s' % (cmd,rest)
1558 cmd = '%s %s' % (cmd,rest)
1551 else:
1559 else:
1552 # Handle aliases with positional arguments
1560 # Handle aliases with positional arguments
1553 args = rest.split(None,nargs)
1561 args = rest.split(None,nargs)
1554 if len(args)< nargs:
1562 if len(args)< nargs:
1555 error('Alias <%s> requires %s arguments, %s given.' %
1563 error('Alias <%s> requires %s arguments, %s given.' %
1556 (alias,nargs,len(args)))
1564 (alias,nargs,len(args)))
1557 return
1565 return
1558 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1566 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1559 # Now call the macro, evaluating in the user's namespace
1567 # Now call the macro, evaluating in the user's namespace
1560 try:
1568 try:
1561 self.system(cmd)
1569 self.system(cmd)
1562 except:
1570 except:
1563 self.showtraceback()
1571 self.showtraceback()
1564
1572
1565 def runlines(self,lines):
1573 def runlines(self,lines):
1566 """Run a string of one or more lines of source.
1574 """Run a string of one or more lines of source.
1567
1575
1568 This method is capable of running a string containing multiple source
1576 This method is capable of running a string containing multiple source
1569 lines, as if they had been entered at the IPython prompt. Since it
1577 lines, as if they had been entered at the IPython prompt. Since it
1570 exposes IPython's processing machinery, the given strings can contain
1578 exposes IPython's processing machinery, the given strings can contain
1571 magic calls (%magic), special shell access (!cmd), etc."""
1579 magic calls (%magic), special shell access (!cmd), etc."""
1572
1580
1573 # We must start with a clean buffer, in case this is run from an
1581 # We must start with a clean buffer, in case this is run from an
1574 # interactive IPython session (via a magic, for example).
1582 # interactive IPython session (via a magic, for example).
1575 self.resetbuffer()
1583 self.resetbuffer()
1576 lines = lines.split('\n')
1584 lines = lines.split('\n')
1577 more = 0
1585 more = 0
1578 for line in lines:
1586 for line in lines:
1579 # skip blank lines so we don't mess up the prompt counter, but do
1587 # skip blank lines so we don't mess up the prompt counter, but do
1580 # NOT skip even a blank line if we are in a code block (more is
1588 # NOT skip even a blank line if we are in a code block (more is
1581 # true)
1589 # true)
1582 if line or more:
1590 if line or more:
1583 more = self.push((self.prefilter(line,more)))
1591 more = self.push((self.prefilter(line,more)))
1584 # IPython's runsource returns None if there was an error
1592 # IPython's runsource returns None if there was an error
1585 # compiling the code. This allows us to stop processing right
1593 # compiling the code. This allows us to stop processing right
1586 # away, so the user gets the error message at the right place.
1594 # away, so the user gets the error message at the right place.
1587 if more is None:
1595 if more is None:
1588 break
1596 break
1589 # final newline in case the input didn't have it, so that the code
1597 # final newline in case the input didn't have it, so that the code
1590 # actually does get executed
1598 # actually does get executed
1591 if more:
1599 if more:
1592 self.push('\n')
1600 self.push('\n')
1593
1601
1594 def runsource(self, source, filename="<input>", symbol="single"):
1602 def runsource(self, source, filename="<input>", symbol="single"):
1595 """Compile and run some source in the interpreter.
1603 """Compile and run some source in the interpreter.
1596
1604
1597 Arguments are as for compile_command().
1605 Arguments are as for compile_command().
1598
1606
1599 One several things can happen:
1607 One several things can happen:
1600
1608
1601 1) The input is incorrect; compile_command() raised an
1609 1) The input is incorrect; compile_command() raised an
1602 exception (SyntaxError or OverflowError). A syntax traceback
1610 exception (SyntaxError or OverflowError). A syntax traceback
1603 will be printed by calling the showsyntaxerror() method.
1611 will be printed by calling the showsyntaxerror() method.
1604
1612
1605 2) The input is incomplete, and more input is required;
1613 2) The input is incomplete, and more input is required;
1606 compile_command() returned None. Nothing happens.
1614 compile_command() returned None. Nothing happens.
1607
1615
1608 3) The input is complete; compile_command() returned a code
1616 3) The input is complete; compile_command() returned a code
1609 object. The code is executed by calling self.runcode() (which
1617 object. The code is executed by calling self.runcode() (which
1610 also handles run-time exceptions, except for SystemExit).
1618 also handles run-time exceptions, except for SystemExit).
1611
1619
1612 The return value is:
1620 The return value is:
1613
1621
1614 - True in case 2
1622 - True in case 2
1615
1623
1616 - False in the other cases, unless an exception is raised, where
1624 - False in the other cases, unless an exception is raised, where
1617 None is returned instead. This can be used by external callers to
1625 None is returned instead. This can be used by external callers to
1618 know whether to continue feeding input or not.
1626 know whether to continue feeding input or not.
1619
1627
1620 The return value can be used to decide whether to use sys.ps1 or
1628 The return value can be used to decide whether to use sys.ps1 or
1621 sys.ps2 to prompt the next line."""
1629 sys.ps2 to prompt the next line."""
1622
1630
1623 try:
1631 try:
1624 code = self.compile(source, filename, symbol)
1632 code = self.compile(source, filename, symbol)
1625 except (OverflowError, SyntaxError, ValueError):
1633 except (OverflowError, SyntaxError, ValueError):
1626 # Case 1
1634 # Case 1
1627 self.showsyntaxerror(filename)
1635 self.showsyntaxerror(filename)
1628 return None
1636 return None
1629
1637
1630 if code is None:
1638 if code is None:
1631 # Case 2
1639 # Case 2
1632 return True
1640 return True
1633
1641
1634 # Case 3
1642 # Case 3
1635 # We store the code object so that threaded shells and
1643 # We store the code object so that threaded shells and
1636 # custom exception handlers can access all this info if needed.
1644 # custom exception handlers can access all this info if needed.
1637 # The source corresponding to this can be obtained from the
1645 # The source corresponding to this can be obtained from the
1638 # buffer attribute as '\n'.join(self.buffer).
1646 # buffer attribute as '\n'.join(self.buffer).
1639 self.code_to_run = code
1647 self.code_to_run = code
1640 # now actually execute the code object
1648 # now actually execute the code object
1641 if self.runcode(code) == 0:
1649 if self.runcode(code) == 0:
1642 return False
1650 return False
1643 else:
1651 else:
1644 return None
1652 return None
1645
1653
1646 def runcode(self,code_obj):
1654 def runcode(self,code_obj):
1647 """Execute a code object.
1655 """Execute a code object.
1648
1656
1649 When an exception occurs, self.showtraceback() is called to display a
1657 When an exception occurs, self.showtraceback() is called to display a
1650 traceback.
1658 traceback.
1651
1659
1652 Return value: a flag indicating whether the code to be run completed
1660 Return value: a flag indicating whether the code to be run completed
1653 successfully:
1661 successfully:
1654
1662
1655 - 0: successful execution.
1663 - 0: successful execution.
1656 - 1: an error occurred.
1664 - 1: an error occurred.
1657 """
1665 """
1658
1666
1659 # Set our own excepthook in case the user code tries to call it
1667 # Set our own excepthook in case the user code tries to call it
1660 # directly, so that the IPython crash handler doesn't get triggered
1668 # directly, so that the IPython crash handler doesn't get triggered
1661 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1669 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1662 outflag = 1 # happens in more places, so it's easier as default
1670 outflag = 1 # happens in more places, so it's easier as default
1663 try:
1671 try:
1664 try:
1672 try:
1665 # Embedded instances require separate global/local namespaces
1673 # Embedded instances require separate global/local namespaces
1666 # so they can see both the surrounding (local) namespace and
1674 # so they can see both the surrounding (local) namespace and
1667 # the module-level globals when called inside another function.
1675 # the module-level globals when called inside another function.
1668 if self.embedded:
1676 if self.embedded:
1669 exec code_obj in self.user_global_ns, self.user_ns
1677 exec code_obj in self.user_global_ns, self.user_ns
1670 # Normal (non-embedded) instances should only have a single
1678 # Normal (non-embedded) instances should only have a single
1671 # namespace for user code execution, otherwise functions won't
1679 # namespace for user code execution, otherwise functions won't
1672 # see interactive top-level globals.
1680 # see interactive top-level globals.
1673 else:
1681 else:
1674 exec code_obj in self.user_ns
1682 exec code_obj in self.user_ns
1675 finally:
1683 finally:
1676 # Reset our crash handler in place
1684 # Reset our crash handler in place
1677 sys.excepthook = old_excepthook
1685 sys.excepthook = old_excepthook
1678 except SystemExit:
1686 except SystemExit:
1679 self.resetbuffer()
1687 self.resetbuffer()
1680 self.showtraceback()
1688 self.showtraceback()
1681 warn( __builtin__.exit,level=1)
1689 warn( __builtin__.exit,level=1)
1682 except self.custom_exceptions:
1690 except self.custom_exceptions:
1683 etype,value,tb = sys.exc_info()
1691 etype,value,tb = sys.exc_info()
1684 self.CustomTB(etype,value,tb)
1692 self.CustomTB(etype,value,tb)
1685 except:
1693 except:
1686 self.showtraceback()
1694 self.showtraceback()
1687 else:
1695 else:
1688 outflag = 0
1696 outflag = 0
1689 if code.softspace(sys.stdout, 0):
1697 if code.softspace(sys.stdout, 0):
1690 print
1698 print
1691 # Flush out code object which has been run (and source)
1699 # Flush out code object which has been run (and source)
1692 self.code_to_run = None
1700 self.code_to_run = None
1693 return outflag
1701 return outflag
1694
1702
1695 def raw_input(self, prompt=""):
1703 def raw_input(self, prompt=""):
1696 """Write a prompt and read a line.
1704 """Write a prompt and read a line.
1697
1705
1698 The returned line does not include the trailing newline.
1706 The returned line does not include the trailing newline.
1699 When the user enters the EOF key sequence, EOFError is raised.
1707 When the user enters the EOF key sequence, EOFError is raised.
1700
1708
1701 The base implementation uses the built-in function
1709 The base implementation uses the built-in function
1702 raw_input(); a subclass may replace this with a different
1710 raw_input(); a subclass may replace this with a different
1703 implementation.
1711 implementation.
1704 """
1712 """
1705 return self.prefilter(raw_input_original(prompt),
1713 return self.prefilter(raw_input_original(prompt),
1706 prompt==self.outputcache.prompt2)
1714 prompt==self.outputcache.prompt2)
1707
1715
1708 def split_user_input(self,line):
1716 def split_user_input(self,line):
1709 """Split user input into pre-char, function part and rest."""
1717 """Split user input into pre-char, function part and rest."""
1710
1718
1711 lsplit = self.line_split.match(line)
1719 lsplit = self.line_split.match(line)
1712 if lsplit is None: # no regexp match returns None
1720 if lsplit is None: # no regexp match returns None
1713 try:
1721 try:
1714 iFun,theRest = line.split(None,1)
1722 iFun,theRest = line.split(None,1)
1715 except ValueError:
1723 except ValueError:
1716 iFun,theRest = line,''
1724 iFun,theRest = line,''
1717 pre = re.match('^(\s*)(.*)',line).groups()[0]
1725 pre = re.match('^(\s*)(.*)',line).groups()[0]
1718 else:
1726 else:
1719 pre,iFun,theRest = lsplit.groups()
1727 pre,iFun,theRest = lsplit.groups()
1720
1728
1721 #print 'line:<%s>' % line # dbg
1729 #print 'line:<%s>' % line # dbg
1722 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1730 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1723 return pre,iFun.strip(),theRest
1731 return pre,iFun.strip(),theRest
1724
1732
1725 def _prefilter(self, line, continue_prompt):
1733 def _prefilter(self, line, continue_prompt):
1726 """Calls different preprocessors, depending on the form of line."""
1734 """Calls different preprocessors, depending on the form of line."""
1727
1735
1728 # All handlers *must* return a value, even if it's blank ('').
1736 # All handlers *must* return a value, even if it's blank ('').
1729
1737
1730 # Lines are NOT logged here. Handlers should process the line as
1738 # Lines are NOT logged here. Handlers should process the line as
1731 # needed, update the cache AND log it (so that the input cache array
1739 # needed, update the cache AND log it (so that the input cache array
1732 # stays synced).
1740 # stays synced).
1733
1741
1734 # This function is _very_ delicate, and since it's also the one which
1742 # This function is _very_ delicate, and since it's also the one which
1735 # determines IPython's response to user input, it must be as efficient
1743 # determines IPython's response to user input, it must be as efficient
1736 # as possible. For this reason it has _many_ returns in it, trying
1744 # as possible. For this reason it has _many_ returns in it, trying
1737 # always to exit as quickly as it can figure out what it needs to do.
1745 # always to exit as quickly as it can figure out what it needs to do.
1738
1746
1739 # This function is the main responsible for maintaining IPython's
1747 # This function is the main responsible for maintaining IPython's
1740 # behavior respectful of Python's semantics. So be _very_ careful if
1748 # behavior respectful of Python's semantics. So be _very_ careful if
1741 # making changes to anything here.
1749 # making changes to anything here.
1742
1750
1743 #.....................................................................
1751 #.....................................................................
1744 # Code begins
1752 # Code begins
1745
1753
1746 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1754 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1747
1755
1748 # save the line away in case we crash, so the post-mortem handler can
1756 # save the line away in case we crash, so the post-mortem handler can
1749 # record it
1757 # record it
1750 self._last_input_line = line
1758 self._last_input_line = line
1751
1759
1752 #print '***line: <%s>' % line # dbg
1760 #print '***line: <%s>' % line # dbg
1753
1761
1754 # the input history needs to track even empty lines
1762 # the input history needs to track even empty lines
1755 if not line.strip():
1763 if not line.strip():
1756 if not continue_prompt:
1764 if not continue_prompt:
1757 self.outputcache.prompt_count -= 1
1765 self.outputcache.prompt_count -= 1
1758 return self.handle_normal('',continue_prompt)
1766 return self.handle_normal('',continue_prompt)
1759
1767
1760 # print '***cont',continue_prompt # dbg
1768 # print '***cont',continue_prompt # dbg
1761 # special handlers are only allowed for single line statements
1769 # special handlers are only allowed for single line statements
1762 if continue_prompt and not self.rc.multi_line_specials:
1770 if continue_prompt and not self.rc.multi_line_specials:
1763 return self.handle_normal(line,continue_prompt)
1771 return self.handle_normal(line,continue_prompt)
1764
1772
1765 # For the rest, we need the structure of the input
1773 # For the rest, we need the structure of the input
1766 pre,iFun,theRest = self.split_user_input(line)
1774 pre,iFun,theRest = self.split_user_input(line)
1767 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1775 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1768
1776
1769 # First check for explicit escapes in the last/first character
1777 # First check for explicit escapes in the last/first character
1770 handler = None
1778 handler = None
1771 if line[-1] == self.ESC_HELP:
1779 if line[-1] == self.ESC_HELP:
1772 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1780 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1773 if handler is None:
1781 if handler is None:
1774 # look at the first character of iFun, NOT of line, so we skip
1782 # look at the first character of iFun, NOT of line, so we skip
1775 # leading whitespace in multiline input
1783 # leading whitespace in multiline input
1776 handler = self.esc_handlers.get(iFun[0:1])
1784 handler = self.esc_handlers.get(iFun[0:1])
1777 if handler is not None:
1785 if handler is not None:
1778 return handler(line,continue_prompt,pre,iFun,theRest)
1786 return handler(line,continue_prompt,pre,iFun,theRest)
1779 # Emacs ipython-mode tags certain input lines
1787 # Emacs ipython-mode tags certain input lines
1780 if line.endswith('# PYTHON-MODE'):
1788 if line.endswith('# PYTHON-MODE'):
1781 return self.handle_emacs(line,continue_prompt)
1789 return self.handle_emacs(line,continue_prompt)
1782
1790
1783 # Next, check if we can automatically execute this thing
1791 # Next, check if we can automatically execute this thing
1784
1792
1785 # Allow ! in multi-line statements if multi_line_specials is on:
1793 # Allow ! in multi-line statements if multi_line_specials is on:
1786 if continue_prompt and self.rc.multi_line_specials and \
1794 if continue_prompt and self.rc.multi_line_specials and \
1787 iFun.startswith(self.ESC_SHELL):
1795 iFun.startswith(self.ESC_SHELL):
1788 return self.handle_shell_escape(line,continue_prompt,
1796 return self.handle_shell_escape(line,continue_prompt,
1789 pre=pre,iFun=iFun,
1797 pre=pre,iFun=iFun,
1790 theRest=theRest)
1798 theRest=theRest)
1791
1799
1792 # Let's try to find if the input line is a magic fn
1800 # Let's try to find if the input line is a magic fn
1793 oinfo = None
1801 oinfo = None
1794 if hasattr(self,'magic_'+iFun):
1802 if hasattr(self,'magic_'+iFun):
1795 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1803 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1796 if oinfo['ismagic']:
1804 if oinfo['ismagic']:
1797 # Be careful not to call magics when a variable assignment is
1805 # Be careful not to call magics when a variable assignment is
1798 # being made (ls='hi', for example)
1806 # being made (ls='hi', for example)
1799 if self.rc.automagic and \
1807 if self.rc.automagic and \
1800 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1808 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1801 (self.rc.multi_line_specials or not continue_prompt):
1809 (self.rc.multi_line_specials or not continue_prompt):
1802 return self.handle_magic(line,continue_prompt,
1810 return self.handle_magic(line,continue_prompt,
1803 pre,iFun,theRest)
1811 pre,iFun,theRest)
1804 else:
1812 else:
1805 return self.handle_normal(line,continue_prompt)
1813 return self.handle_normal(line,continue_prompt)
1806
1814
1807 # If the rest of the line begins with an (in)equality, assginment or
1815 # If the rest of the line begins with an (in)equality, assginment or
1808 # function call, we should not call _ofind but simply execute it.
1816 # function call, we should not call _ofind but simply execute it.
1809 # This avoids spurious geattr() accesses on objects upon assignment.
1817 # This avoids spurious geattr() accesses on objects upon assignment.
1810 #
1818 #
1811 # It also allows users to assign to either alias or magic names true
1819 # It also allows users to assign to either alias or magic names true
1812 # python variables (the magic/alias systems always take second seat to
1820 # python variables (the magic/alias systems always take second seat to
1813 # true python code).
1821 # true python code).
1814 if theRest and theRest[0] in '!=()':
1822 if theRest and theRest[0] in '!=()':
1815 return self.handle_normal(line,continue_prompt)
1823 return self.handle_normal(line,continue_prompt)
1816
1824
1817 if oinfo is None:
1825 if oinfo is None:
1818 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1826 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1819
1827
1820 if not oinfo['found']:
1828 if not oinfo['found']:
1821 return self.handle_normal(line,continue_prompt)
1829 return self.handle_normal(line,continue_prompt)
1822 else:
1830 else:
1823 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1831 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1824 if oinfo['isalias']:
1832 if oinfo['isalias']:
1825 return self.handle_alias(line,continue_prompt,
1833 return self.handle_alias(line,continue_prompt,
1826 pre,iFun,theRest)
1834 pre,iFun,theRest)
1827
1835
1828 if self.rc.autocall and \
1836 if self.rc.autocall and \
1829 not self.re_exclude_auto.match(theRest) and \
1837 not self.re_exclude_auto.match(theRest) and \
1830 self.re_fun_name.match(iFun) and \
1838 self.re_fun_name.match(iFun) and \
1831 callable(oinfo['obj']) :
1839 callable(oinfo['obj']) :
1832 #print 'going auto' # dbg
1840 #print 'going auto' # dbg
1833 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1841 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1834 else:
1842 else:
1835 #print 'was callable?', callable(oinfo['obj']) # dbg
1843 #print 'was callable?', callable(oinfo['obj']) # dbg
1836 return self.handle_normal(line,continue_prompt)
1844 return self.handle_normal(line,continue_prompt)
1837
1845
1838 # If we get here, we have a normal Python line. Log and return.
1846 # If we get here, we have a normal Python line. Log and return.
1839 return self.handle_normal(line,continue_prompt)
1847 return self.handle_normal(line,continue_prompt)
1840
1848
1841 def _prefilter_dumb(self, line, continue_prompt):
1849 def _prefilter_dumb(self, line, continue_prompt):
1842 """simple prefilter function, for debugging"""
1850 """simple prefilter function, for debugging"""
1843 return self.handle_normal(line,continue_prompt)
1851 return self.handle_normal(line,continue_prompt)
1844
1852
1845 # Set the default prefilter() function (this can be user-overridden)
1853 # Set the default prefilter() function (this can be user-overridden)
1846 prefilter = _prefilter
1854 prefilter = _prefilter
1847
1855
1848 def handle_normal(self,line,continue_prompt=None,
1856 def handle_normal(self,line,continue_prompt=None,
1849 pre=None,iFun=None,theRest=None):
1857 pre=None,iFun=None,theRest=None):
1850 """Handle normal input lines. Use as a template for handlers."""
1858 """Handle normal input lines. Use as a template for handlers."""
1851
1859
1852 self.log(line,continue_prompt)
1860 self.log(line,continue_prompt)
1853 self.update_cache(line)
1861 self.update_cache(line)
1854 return line
1862 return line
1855
1863
1856 def handle_alias(self,line,continue_prompt=None,
1864 def handle_alias(self,line,continue_prompt=None,
1857 pre=None,iFun=None,theRest=None):
1865 pre=None,iFun=None,theRest=None):
1858 """Handle alias input lines. """
1866 """Handle alias input lines. """
1859
1867
1860 theRest = esc_quotes(theRest)
1868 theRest = esc_quotes(theRest)
1861 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1869 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1862 self.log(line_out,continue_prompt)
1870 self.log(line_out,continue_prompt)
1863 self.update_cache(line_out)
1871 self.update_cache(line_out)
1864 return line_out
1872 return line_out
1865
1873
1866 def handle_shell_escape(self, line, continue_prompt=None,
1874 def handle_shell_escape(self, line, continue_prompt=None,
1867 pre=None,iFun=None,theRest=None):
1875 pre=None,iFun=None,theRest=None):
1868 """Execute the line in a shell, empty return value"""
1876 """Execute the line in a shell, empty return value"""
1869
1877
1870 #print 'line in :', `line` # dbg
1878 #print 'line in :', `line` # dbg
1871 # Example of a special handler. Others follow a similar pattern.
1879 # Example of a special handler. Others follow a similar pattern.
1872 if continue_prompt: # multi-line statements
1880 if continue_prompt: # multi-line statements
1873 if iFun.startswith('!!'):
1881 if iFun.startswith('!!'):
1874 print 'SyntaxError: !! is not allowed in multiline statements'
1882 print 'SyntaxError: !! is not allowed in multiline statements'
1875 return pre
1883 return pre
1876 else:
1884 else:
1877 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1885 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1878 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1886 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1879 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1887 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1880 else: # single-line input
1888 else: # single-line input
1881 if line.startswith('!!'):
1889 if line.startswith('!!'):
1882 # rewrite iFun/theRest to properly hold the call to %sx and
1890 # rewrite iFun/theRest to properly hold the call to %sx and
1883 # the actual command to be executed, so handle_magic can work
1891 # the actual command to be executed, so handle_magic can work
1884 # correctly
1892 # correctly
1885 theRest = '%s %s' % (iFun[2:],theRest)
1893 theRest = '%s %s' % (iFun[2:],theRest)
1886 iFun = 'sx'
1894 iFun = 'sx'
1887 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1895 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1888 continue_prompt,pre,iFun,theRest)
1896 continue_prompt,pre,iFun,theRest)
1889 else:
1897 else:
1890 cmd = esc_quotes(line[1:])
1898 cmd = esc_quotes(line[1:])
1891 line_out = '%s.system("%s")' % (self.name,cmd)
1899 line_out = '%s.system("%s")' % (self.name,cmd)
1892 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1900 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1893 # update cache/log and return
1901 # update cache/log and return
1894 self.log(line_out,continue_prompt)
1902 self.log(line_out,continue_prompt)
1895 self.update_cache(line_out) # readline cache gets normal line
1903 self.update_cache(line_out) # readline cache gets normal line
1896 #print 'line out r:', `line_out` # dbg
1904 #print 'line out r:', `line_out` # dbg
1897 #print 'line out s:', line_out # dbg
1905 #print 'line out s:', line_out # dbg
1898 return line_out
1906 return line_out
1899
1907
1900 def handle_magic(self, line, continue_prompt=None,
1908 def handle_magic(self, line, continue_prompt=None,
1901 pre=None,iFun=None,theRest=None):
1909 pre=None,iFun=None,theRest=None):
1902 """Execute magic functions.
1910 """Execute magic functions.
1903
1911
1904 Also log them with a prepended # so the log is clean Python."""
1912 Also log them with a prepended # so the log is clean Python."""
1905
1913
1906 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1914 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1907 self.log(cmd,continue_prompt)
1915 self.log(cmd,continue_prompt)
1908 self.update_cache(line)
1916 self.update_cache(line)
1909 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1917 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1910 return cmd
1918 return cmd
1911
1919
1912 def handle_auto(self, line, continue_prompt=None,
1920 def handle_auto(self, line, continue_prompt=None,
1913 pre=None,iFun=None,theRest=None):
1921 pre=None,iFun=None,theRest=None):
1914 """Hande lines which can be auto-executed, quoting if requested."""
1922 """Hande lines which can be auto-executed, quoting if requested."""
1915
1923
1916 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1924 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1917
1925
1918 # This should only be active for single-line input!
1926 # This should only be active for single-line input!
1919 if continue_prompt:
1927 if continue_prompt:
1920 return line
1928 return line
1921
1929
1922 if pre == self.ESC_QUOTE:
1930 if pre == self.ESC_QUOTE:
1923 # Auto-quote splitting on whitespace
1931 # Auto-quote splitting on whitespace
1924 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1932 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1925 elif pre == self.ESC_QUOTE2:
1933 elif pre == self.ESC_QUOTE2:
1926 # Auto-quote whole string
1934 # Auto-quote whole string
1927 newcmd = '%s("%s")' % (iFun,theRest)
1935 newcmd = '%s("%s")' % (iFun,theRest)
1928 else:
1936 else:
1929 # Auto-paren
1937 # Auto-paren
1930 if theRest[0:1] in ('=','['):
1938 if theRest[0:1] in ('=','['):
1931 # Don't autocall in these cases. They can be either
1939 # Don't autocall in these cases. They can be either
1932 # rebindings of an existing callable's name, or item access
1940 # rebindings of an existing callable's name, or item access
1933 # for an object which is BOTH callable and implements
1941 # for an object which is BOTH callable and implements
1934 # __getitem__.
1942 # __getitem__.
1935 return '%s %s' % (iFun,theRest)
1943 return '%s %s' % (iFun,theRest)
1936 if theRest.endswith(';'):
1944 if theRest.endswith(';'):
1937 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1945 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1938 else:
1946 else:
1939 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1947 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1940
1948
1941 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1949 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1942 # log what is now valid Python, not the actual user input (without the
1950 # log what is now valid Python, not the actual user input (without the
1943 # final newline)
1951 # final newline)
1944 self.log(newcmd,continue_prompt)
1952 self.log(newcmd,continue_prompt)
1945 return newcmd
1953 return newcmd
1946
1954
1947 def handle_help(self, line, continue_prompt=None,
1955 def handle_help(self, line, continue_prompt=None,
1948 pre=None,iFun=None,theRest=None):
1956 pre=None,iFun=None,theRest=None):
1949 """Try to get some help for the object.
1957 """Try to get some help for the object.
1950
1958
1951 obj? or ?obj -> basic information.
1959 obj? or ?obj -> basic information.
1952 obj?? or ??obj -> more details.
1960 obj?? or ??obj -> more details.
1953 """
1961 """
1954
1962
1955 # We need to make sure that we don't process lines which would be
1963 # We need to make sure that we don't process lines which would be
1956 # otherwise valid python, such as "x=1 # what?"
1964 # otherwise valid python, such as "x=1 # what?"
1957 try:
1965 try:
1958 code.compile_command(line)
1966 code.compile_command(line)
1959 except SyntaxError:
1967 except SyntaxError:
1960 # We should only handle as help stuff which is NOT valid syntax
1968 # We should only handle as help stuff which is NOT valid syntax
1961 if line[0]==self.ESC_HELP:
1969 if line[0]==self.ESC_HELP:
1962 line = line[1:]
1970 line = line[1:]
1963 elif line[-1]==self.ESC_HELP:
1971 elif line[-1]==self.ESC_HELP:
1964 line = line[:-1]
1972 line = line[:-1]
1965 self.log('#?'+line)
1973 self.log('#?'+line)
1966 self.update_cache(line)
1974 self.update_cache(line)
1967 if line:
1975 if line:
1968 self.magic_pinfo(line)
1976 self.magic_pinfo(line)
1969 else:
1977 else:
1970 page(self.usage,screen_lines=self.rc.screen_length)
1978 page(self.usage,screen_lines=self.rc.screen_length)
1971 return '' # Empty string is needed here!
1979 return '' # Empty string is needed here!
1972 except:
1980 except:
1973 # Pass any other exceptions through to the normal handler
1981 # Pass any other exceptions through to the normal handler
1974 return self.handle_normal(line,continue_prompt)
1982 return self.handle_normal(line,continue_prompt)
1975 else:
1983 else:
1976 # If the code compiles ok, we should handle it normally
1984 # If the code compiles ok, we should handle it normally
1977 return self.handle_normal(line,continue_prompt)
1985 return self.handle_normal(line,continue_prompt)
1978
1986
1979 def handle_emacs(self,line,continue_prompt=None,
1987 def handle_emacs(self,line,continue_prompt=None,
1980 pre=None,iFun=None,theRest=None):
1988 pre=None,iFun=None,theRest=None):
1981 """Handle input lines marked by python-mode."""
1989 """Handle input lines marked by python-mode."""
1982
1990
1983 # Currently, nothing is done. Later more functionality can be added
1991 # Currently, nothing is done. Later more functionality can be added
1984 # here if needed.
1992 # here if needed.
1985
1993
1986 # The input cache shouldn't be updated
1994 # The input cache shouldn't be updated
1987
1995
1988 return line
1996 return line
1989
1997
1990 def write(self,data):
1998 def write(self,data):
1991 """Write a string to the default output"""
1999 """Write a string to the default output"""
1992 Term.cout.write(data)
2000 Term.cout.write(data)
1993
2001
1994 def write_err(self,data):
2002 def write_err(self,data):
1995 """Write a string to the default error output"""
2003 """Write a string to the default error output"""
1996 Term.cerr.write(data)
2004 Term.cerr.write(data)
1997
2005
1998 def safe_execfile(self,fname,*where,**kw):
2006 def safe_execfile(self,fname,*where,**kw):
1999 fname = os.path.expanduser(fname)
2007 fname = os.path.expanduser(fname)
2000
2008
2001 # find things also in current directory
2009 # find things also in current directory
2002 dname = os.path.dirname(fname)
2010 dname = os.path.dirname(fname)
2003 if not sys.path.count(dname):
2011 if not sys.path.count(dname):
2004 sys.path.append(dname)
2012 sys.path.append(dname)
2005
2013
2006 try:
2014 try:
2007 xfile = open(fname)
2015 xfile = open(fname)
2008 except:
2016 except:
2009 print >> Term.cerr, \
2017 print >> Term.cerr, \
2010 'Could not open file <%s> for safe execution.' % fname
2018 'Could not open file <%s> for safe execution.' % fname
2011 return None
2019 return None
2012
2020
2013 kw.setdefault('islog',0)
2021 kw.setdefault('islog',0)
2014 kw.setdefault('quiet',1)
2022 kw.setdefault('quiet',1)
2015 kw.setdefault('exit_ignore',0)
2023 kw.setdefault('exit_ignore',0)
2016 first = xfile.readline()
2024 first = xfile.readline()
2017 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
2025 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
2018 xfile.close()
2026 xfile.close()
2019 # line by line execution
2027 # line by line execution
2020 if first.startswith(_LOGHEAD) or kw['islog']:
2028 if first.startswith(_LOGHEAD) or kw['islog']:
2021 print 'Loading log file <%s> one line at a time...' % fname
2029 print 'Loading log file <%s> one line at a time...' % fname
2022 if kw['quiet']:
2030 if kw['quiet']:
2023 stdout_save = sys.stdout
2031 stdout_save = sys.stdout
2024 sys.stdout = StringIO.StringIO()
2032 sys.stdout = StringIO.StringIO()
2025 try:
2033 try:
2026 globs,locs = where[0:2]
2034 globs,locs = where[0:2]
2027 except:
2035 except:
2028 try:
2036 try:
2029 globs = locs = where[0]
2037 globs = locs = where[0]
2030 except:
2038 except:
2031 globs = locs = globals()
2039 globs = locs = globals()
2032 badblocks = []
2040 badblocks = []
2033
2041
2034 # we also need to identify indented blocks of code when replaying
2042 # we also need to identify indented blocks of code when replaying
2035 # logs and put them together before passing them to an exec
2043 # logs and put them together before passing them to an exec
2036 # statement. This takes a bit of regexp and look-ahead work in the
2044 # statement. This takes a bit of regexp and look-ahead work in the
2037 # file. It's easiest if we swallow the whole thing in memory
2045 # file. It's easiest if we swallow the whole thing in memory
2038 # first, and manually walk through the lines list moving the
2046 # first, and manually walk through the lines list moving the
2039 # counter ourselves.
2047 # counter ourselves.
2040 indent_re = re.compile('\s+\S')
2048 indent_re = re.compile('\s+\S')
2041 xfile = open(fname)
2049 xfile = open(fname)
2042 filelines = xfile.readlines()
2050 filelines = xfile.readlines()
2043 xfile.close()
2051 xfile.close()
2044 nlines = len(filelines)
2052 nlines = len(filelines)
2045 lnum = 0
2053 lnum = 0
2046 while lnum < nlines:
2054 while lnum < nlines:
2047 line = filelines[lnum]
2055 line = filelines[lnum]
2048 lnum += 1
2056 lnum += 1
2049 # don't re-insert logger status info into cache
2057 # don't re-insert logger status info into cache
2050 if line.startswith('#log#'):
2058 if line.startswith('#log#'):
2051 continue
2059 continue
2052 elif line.startswith('#%s'% self.ESC_MAGIC):
2060 elif line.startswith('#%s'% self.ESC_MAGIC):
2053 self.update_cache(line[1:])
2061 self.update_cache(line[1:])
2054 line = magic2python(line)
2062 line = magic2python(line)
2055 elif line.startswith('#!'):
2063 elif line.startswith('#!'):
2056 self.update_cache(line[1:])
2064 self.update_cache(line[1:])
2057 else:
2065 else:
2058 # build a block of code (maybe a single line) for execution
2066 # build a block of code (maybe a single line) for execution
2059 block = line
2067 block = line
2060 try:
2068 try:
2061 next = filelines[lnum] # lnum has already incremented
2069 next = filelines[lnum] # lnum has already incremented
2062 except:
2070 except:
2063 next = None
2071 next = None
2064 while next and indent_re.match(next):
2072 while next and indent_re.match(next):
2065 block += next
2073 block += next
2066 lnum += 1
2074 lnum += 1
2067 try:
2075 try:
2068 next = filelines[lnum]
2076 next = filelines[lnum]
2069 except:
2077 except:
2070 next = None
2078 next = None
2071 # now execute the block of one or more lines
2079 # now execute the block of one or more lines
2072 try:
2080 try:
2073 exec block in globs,locs
2081 exec block in globs,locs
2074 self.update_cache(block.rstrip())
2082 self.update_cache(block.rstrip())
2075 except SystemExit:
2083 except SystemExit:
2076 pass
2084 pass
2077 except:
2085 except:
2078 badblocks.append(block.rstrip())
2086 badblocks.append(block.rstrip())
2079 if kw['quiet']: # restore stdout
2087 if kw['quiet']: # restore stdout
2080 sys.stdout.close()
2088 sys.stdout.close()
2081 sys.stdout = stdout_save
2089 sys.stdout = stdout_save
2082 print 'Finished replaying log file <%s>' % fname
2090 print 'Finished replaying log file <%s>' % fname
2083 if badblocks:
2091 if badblocks:
2084 print >> sys.stderr, \
2092 print >> sys.stderr, \
2085 '\nThe following lines/blocks in file <%s> reported errors:' \
2093 '\nThe following lines/blocks in file <%s> reported errors:' \
2086 % fname
2094 % fname
2087 for badline in badblocks:
2095 for badline in badblocks:
2088 print >> sys.stderr, badline
2096 print >> sys.stderr, badline
2089 else: # regular file execution
2097 else: # regular file execution
2090 try:
2098 try:
2091 execfile(fname,*where)
2099 execfile(fname,*where)
2092 except SyntaxError:
2100 except SyntaxError:
2093 etype, evalue = sys.exc_info()[0:2]
2101 etype, evalue = sys.exc_info()[0:2]
2094 self.SyntaxTB(etype,evalue,[])
2102 self.SyntaxTB(etype,evalue,[])
2095 warn('Failure executing file: <%s>' % fname)
2103 warn('Failure executing file: <%s>' % fname)
2096 except SystemExit,status:
2104 except SystemExit,status:
2097 if not kw['exit_ignore']:
2105 if not kw['exit_ignore']:
2098 self.InteractiveTB()
2106 self.InteractiveTB()
2099 warn('Failure executing file: <%s>' % fname)
2107 warn('Failure executing file: <%s>' % fname)
2100 except:
2108 except:
2101 self.InteractiveTB()
2109 self.InteractiveTB()
2102 warn('Failure executing file: <%s>' % fname)
2110 warn('Failure executing file: <%s>' % fname)
2103
2111
2104 #************************* end of file <iplib.py> *****************************
2112 #************************* end of file <iplib.py> *****************************
@@ -1,860 +1,778 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 703 2005-08-16 17:34:44Z fperez $"""
63 $Id: ultraTB.py 951 2005-12-25 00:57:24Z 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 sys, os, traceback, types, string, time
79 import sys, os, traceback, types, string, time
80 import keyword, tokenize, linecache, inspect, pydoc
80 import keyword, tokenize, linecache, inspect, pydoc
81 from UserDict import UserDict
81 from UserDict import UserDict
82
82
83 # IPython's own modules
83 # IPython's own modules
84 # Modified pdb which doesn't damage IPython's readline handling
84 # Modified pdb which doesn't damage IPython's readline handling
85 from IPython import Debugger
85 from IPython import Debugger
86
86
87 from IPython.Struct import Struct
87 from IPython.Struct import Struct
88 from IPython.ColorANSI import *
89 from IPython.genutils import Term,uniq_stable,error,info
88 from IPython.genutils import Term,uniq_stable,error,info
89 from IPython.excolors import ExceptionColors
90
90
91 #---------------------------------------------------------------------------
91 #---------------------------------------------------------------------------
92 # Code begins
92 # Code begins
93
93
94 def inspect_error():
94 def inspect_error():
95 """Print a message about internal inspect errors.
95 """Print a message about internal inspect errors.
96
96
97 These are unfortunately quite common."""
97 These are unfortunately quite common."""
98
98
99 error('Internal Python error in the inspect module.\n'
99 error('Internal Python error in the inspect module.\n'
100 'Below is the traceback from this internal error.\n')
100 'Below is the traceback from this internal error.\n')
101
101
102 # Make a global variable out of the color scheme table used for coloring
103 # exception tracebacks. This allows user code to add new schemes at runtime.
104 ExceptionColors = ColorSchemeTable()
105
106 # Populate it with color schemes
107 C = TermColors # shorthand and local lookup
108 ExceptionColors.add_scheme(ColorScheme(
109 'NoColor',
110 # The color to be used for the top line
111 topline = C.NoColor,
112
113 # The colors to be used in the traceback
114 filename = C.NoColor,
115 lineno = C.NoColor,
116 name = C.NoColor,
117 vName = C.NoColor,
118 val = C.NoColor,
119 em = C.NoColor,
120
121 # Emphasized colors for the last frame of the traceback
122 normalEm = C.NoColor,
123 filenameEm = C.NoColor,
124 linenoEm = C.NoColor,
125 nameEm = C.NoColor,
126 valEm = C.NoColor,
127
128 # Colors for printing the exception
129 excName = C.NoColor,
130 line = C.NoColor,
131 caret = C.NoColor,
132 Normal = C.NoColor
133 ))
134
135 # make some schemes as instances so we can copy them for modification easily
136 ExceptionColors.add_scheme(ColorScheme(
137 'Linux',
138 # The color to be used for the top line
139 topline = C.LightRed,
140
141 # The colors to be used in the traceback
142 filename = C.Green,
143 lineno = C.Green,
144 name = C.Purple,
145 vName = C.Cyan,
146 val = C.Green,
147 em = C.LightCyan,
148
149 # Emphasized colors for the last frame of the traceback
150 normalEm = C.LightCyan,
151 filenameEm = C.LightGreen,
152 linenoEm = C.LightGreen,
153 nameEm = C.LightPurple,
154 valEm = C.LightBlue,
155
156 # Colors for printing the exception
157 excName = C.LightRed,
158 line = C.Yellow,
159 caret = C.White,
160 Normal = C.Normal
161 ))
162
163 # For light backgrounds, swap dark/light colors
164 ExceptionColors.add_scheme(ColorScheme(
165 'LightBG',
166 # The color to be used for the top line
167 topline = C.Red,
168
169 # The colors to be used in the traceback
170 filename = C.LightGreen,
171 lineno = C.LightGreen,
172 name = C.LightPurple,
173 vName = C.Cyan,
174 val = C.LightGreen,
175 em = C.Cyan,
176
177 # Emphasized colors for the last frame of the traceback
178 normalEm = C.Cyan,
179 filenameEm = C.Green,
180 linenoEm = C.Green,
181 nameEm = C.Purple,
182 valEm = C.Blue,
183
184 # Colors for printing the exception
185 excName = C.Red,
186 #line = C.Brown, # brown often is displayed as yellow
187 line = C.Red,
188 caret = C.Normal,
189 Normal = C.Normal
190 ))
191
192 class TBTools:
102 class TBTools:
193 """Basic tools used by all traceback printer classes."""
103 """Basic tools used by all traceback printer classes."""
194
104
195 def __init__(self,color_scheme = 'NoColor',call_pdb=0):
105 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
196 # Whether to call the interactive pdb debugger after printing
106 # Whether to call the interactive pdb debugger after printing
197 # tracebacks or not
107 # tracebacks or not
198 self.call_pdb = call_pdb
108 self.call_pdb = call_pdb
199 if call_pdb:
200 self.pdb = Debugger.Pdb()
201 else:
202 self.pdb = None
203
109
204 # Create color table
110 # Create color table
205 self.ColorSchemeTable = ExceptionColors
111 self.color_scheme_table = ExceptionColors
206
112
207 self.set_colors(color_scheme)
113 self.set_colors(color_scheme)
208 self.old_scheme = color_scheme # save initial value for toggles
114 self.old_scheme = color_scheme # save initial value for toggles
209
115
116 if call_pdb:
117 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
118 else:
119 self.pdb = None
120
210 def set_colors(self,*args,**kw):
121 def set_colors(self,*args,**kw):
211 """Shorthand access to the color table scheme selector method."""
122 """Shorthand access to the color table scheme selector method."""
212
123
213 self.ColorSchemeTable.set_active_scheme(*args,**kw)
124 self.color_scheme_table.set_active_scheme(*args,**kw)
214 # for convenience, set Colors to the active scheme
125 # for convenience, set Colors to the active scheme
215 self.Colors = self.ColorSchemeTable.active_colors
126 self.Colors = self.color_scheme_table.active_colors
216
127
217 def color_toggle(self):
128 def color_toggle(self):
218 """Toggle between the currently active color scheme and NoColor."""
129 """Toggle between the currently active color scheme and NoColor."""
219
130
220 if self.ColorSchemeTable.active_scheme_name == 'NoColor':
131 if self.color_scheme_table.active_scheme_name == 'NoColor':
221 self.ColorSchemeTable.set_active_scheme(self.old_scheme)
132 self.color_scheme_table.set_active_scheme(self.old_scheme)
222 self.Colors = self.ColorSchemeTable.active_colors
133 self.Colors = self.color_scheme_table.active_colors
223 else:
134 else:
224 self.old_scheme = self.ColorSchemeTable.active_scheme_name
135 self.old_scheme = self.color_scheme_table.active_scheme_name
225 self.ColorSchemeTable.set_active_scheme('NoColor')
136 self.color_scheme_table.set_active_scheme('NoColor')
226 self.Colors = self.ColorSchemeTable.active_colors
137 self.Colors = self.color_scheme_table.active_colors
227
138
228 #---------------------------------------------------------------------------
139 #---------------------------------------------------------------------------
229 class ListTB(TBTools):
140 class ListTB(TBTools):
230 """Print traceback information from a traceback list, with optional color.
141 """Print traceback information from a traceback list, with optional color.
231
142
232 Calling: requires 3 arguments:
143 Calling: requires 3 arguments:
233 (etype, evalue, elist)
144 (etype, evalue, elist)
234 as would be obtained by:
145 as would be obtained by:
235 etype, evalue, tb = sys.exc_info()
146 etype, evalue, tb = sys.exc_info()
236 if tb:
147 if tb:
237 elist = traceback.extract_tb(tb)
148 elist = traceback.extract_tb(tb)
238 else:
149 else:
239 elist = None
150 elist = None
240
151
241 It can thus be used by programs which need to process the traceback before
152 It can thus be used by programs which need to process the traceback before
242 printing (such as console replacements based on the code module from the
153 printing (such as console replacements based on the code module from the
243 standard library).
154 standard library).
244
155
245 Because they are meant to be called without a full traceback (only a
156 Because they are meant to be called without a full traceback (only a
246 list), instances of this class can't call the interactive pdb debugger."""
157 list), instances of this class can't call the interactive pdb debugger."""
247
158
248 def __init__(self,color_scheme = 'NoColor'):
159 def __init__(self,color_scheme = 'NoColor'):
249 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
160 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
250
161
251 def __call__(self, etype, value, elist):
162 def __call__(self, etype, value, elist):
252 print >> Term.cerr, self.text(etype,value,elist)
163 print >> Term.cerr, self.text(etype,value,elist)
253
164
254 def text(self,etype, value, elist,context=5):
165 def text(self,etype, value, elist,context=5):
255 """Return a color formatted string with the traceback info."""
166 """Return a color formatted string with the traceback info."""
256
167
257 Colors = self.Colors
168 Colors = self.Colors
258 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
169 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
259 if elist:
170 if elist:
260 out_string.append('Traceback %s(most recent call last)%s:' % \
171 out_string.append('Traceback %s(most recent call last)%s:' % \
261 (Colors.normalEm, Colors.Normal) + '\n')
172 (Colors.normalEm, Colors.Normal) + '\n')
262 out_string.extend(self._format_list(elist))
173 out_string.extend(self._format_list(elist))
263 lines = self._format_exception_only(etype, value)
174 lines = self._format_exception_only(etype, value)
264 for line in lines[:-1]:
175 for line in lines[:-1]:
265 out_string.append(" "+line)
176 out_string.append(" "+line)
266 out_string.append(lines[-1])
177 out_string.append(lines[-1])
267 return ''.join(out_string)
178 return ''.join(out_string)
268
179
269 def _format_list(self, extracted_list):
180 def _format_list(self, extracted_list):
270 """Format a list of traceback entry tuples for printing.
181 """Format a list of traceback entry tuples for printing.
271
182
272 Given a list of tuples as returned by extract_tb() or
183 Given a list of tuples as returned by extract_tb() or
273 extract_stack(), return a list of strings ready for printing.
184 extract_stack(), return a list of strings ready for printing.
274 Each string in the resulting list corresponds to the item with the
185 Each string in the resulting list corresponds to the item with the
275 same index in the argument list. Each string ends in a newline;
186 same index in the argument list. Each string ends in a newline;
276 the strings may contain internal newlines as well, for those items
187 the strings may contain internal newlines as well, for those items
277 whose source text line is not None.
188 whose source text line is not None.
278
189
279 Lifted almost verbatim from traceback.py
190 Lifted almost verbatim from traceback.py
280 """
191 """
281
192
282 Colors = self.Colors
193 Colors = self.Colors
283 list = []
194 list = []
284 for filename, lineno, name, line in extracted_list[:-1]:
195 for filename, lineno, name, line in extracted_list[:-1]:
285 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
196 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
286 (Colors.filename, filename, Colors.Normal,
197 (Colors.filename, filename, Colors.Normal,
287 Colors.lineno, lineno, Colors.Normal,
198 Colors.lineno, lineno, Colors.Normal,
288 Colors.name, name, Colors.Normal)
199 Colors.name, name, Colors.Normal)
289 if line:
200 if line:
290 item = item + ' %s\n' % line.strip()
201 item = item + ' %s\n' % line.strip()
291 list.append(item)
202 list.append(item)
292 # Emphasize the last entry
203 # Emphasize the last entry
293 filename, lineno, name, line = extracted_list[-1]
204 filename, lineno, name, line = extracted_list[-1]
294 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
205 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
295 (Colors.normalEm,
206 (Colors.normalEm,
296 Colors.filenameEm, filename, Colors.normalEm,
207 Colors.filenameEm, filename, Colors.normalEm,
297 Colors.linenoEm, lineno, Colors.normalEm,
208 Colors.linenoEm, lineno, Colors.normalEm,
298 Colors.nameEm, name, Colors.normalEm,
209 Colors.nameEm, name, Colors.normalEm,
299 Colors.Normal)
210 Colors.Normal)
300 if line:
211 if line:
301 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
212 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
302 Colors.Normal)
213 Colors.Normal)
303 list.append(item)
214 list.append(item)
304 return list
215 return list
305
216
306 def _format_exception_only(self, etype, value):
217 def _format_exception_only(self, etype, value):
307 """Format the exception part of a traceback.
218 """Format the exception part of a traceback.
308
219
309 The arguments are the exception type and value such as given by
220 The arguments are the exception type and value such as given by
310 sys.last_type and sys.last_value. The return value is a list of
221 sys.last_type and sys.last_value. The return value is a list of
311 strings, each ending in a newline. Normally, the list contains a
222 strings, each ending in a newline. Normally, the list contains a
312 single string; however, for SyntaxError exceptions, it contains
223 single string; however, for SyntaxError exceptions, it contains
313 several lines that (when printed) display detailed information
224 several lines that (when printed) display detailed information
314 about where the syntax error occurred. The message indicating
225 about where the syntax error occurred. The message indicating
315 which exception occurred is the always last string in the list.
226 which exception occurred is the always last string in the list.
316
227
317 Also lifted nearly verbatim from traceback.py
228 Also lifted nearly verbatim from traceback.py
318 """
229 """
319
230
320 Colors = self.Colors
231 Colors = self.Colors
321 list = []
232 list = []
322 if type(etype) == types.ClassType:
233 if type(etype) == types.ClassType:
323 stype = Colors.excName + etype.__name__ + Colors.Normal
234 stype = Colors.excName + etype.__name__ + Colors.Normal
324 else:
235 else:
325 stype = etype # String exceptions don't get special coloring
236 stype = etype # String exceptions don't get special coloring
326 if value is None:
237 if value is None:
327 list.append( str(stype) + '\n')
238 list.append( str(stype) + '\n')
328 else:
239 else:
329 if etype is SyntaxError:
240 if etype is SyntaxError:
330 try:
241 try:
331 msg, (filename, lineno, offset, line) = value
242 msg, (filename, lineno, offset, line) = value
332 except:
243 except:
333 pass
244 pass
334 else:
245 else:
335 #print 'filename is',filename # dbg
246 #print 'filename is',filename # dbg
336 if not filename: filename = "<string>"
247 if not filename: filename = "<string>"
337 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
248 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
338 (Colors.normalEm,
249 (Colors.normalEm,
339 Colors.filenameEm, filename, Colors.normalEm,
250 Colors.filenameEm, filename, Colors.normalEm,
340 Colors.linenoEm, lineno, Colors.Normal ))
251 Colors.linenoEm, lineno, Colors.Normal ))
341 if line is not None:
252 if line is not None:
342 i = 0
253 i = 0
343 while i < len(line) and line[i].isspace():
254 while i < len(line) and line[i].isspace():
344 i = i+1
255 i = i+1
345 list.append('%s %s%s\n' % (Colors.line,
256 list.append('%s %s%s\n' % (Colors.line,
346 line.strip(),
257 line.strip(),
347 Colors.Normal))
258 Colors.Normal))
348 if offset is not None:
259 if offset is not None:
349 s = ' '
260 s = ' '
350 for c in line[i:offset-1]:
261 for c in line[i:offset-1]:
351 if c.isspace():
262 if c.isspace():
352 s = s + c
263 s = s + c
353 else:
264 else:
354 s = s + ' '
265 s = s + ' '
355 list.append('%s%s^%s\n' % (Colors.caret, s,
266 list.append('%s%s^%s\n' % (Colors.caret, s,
356 Colors.Normal) )
267 Colors.Normal) )
357 value = msg
268 value = msg
358 s = self._some_str(value)
269 s = self._some_str(value)
359 if s:
270 if s:
360 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
271 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
361 Colors.Normal, s))
272 Colors.Normal, s))
362 else:
273 else:
363 list.append('%s\n' % str(stype))
274 list.append('%s\n' % str(stype))
364 return list
275 return list
365
276
366 def _some_str(self, value):
277 def _some_str(self, value):
367 # Lifted from traceback.py
278 # Lifted from traceback.py
368 try:
279 try:
369 return str(value)
280 return str(value)
370 except:
281 except:
371 return '<unprintable %s object>' % type(value).__name__
282 return '<unprintable %s object>' % type(value).__name__
372
283
373 #----------------------------------------------------------------------------
284 #----------------------------------------------------------------------------
374 class VerboseTB(TBTools):
285 class VerboseTB(TBTools):
375 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
286 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
376 of HTML. Requires inspect and pydoc. Crazy, man.
287 of HTML. Requires inspect and pydoc. Crazy, man.
377
288
378 Modified version which optionally strips the topmost entries from the
289 Modified version which optionally strips the topmost entries from the
379 traceback, to be used with alternate interpreters (because their own code
290 traceback, to be used with alternate interpreters (because their own code
380 would appear in the traceback)."""
291 would appear in the traceback)."""
381
292
382 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
293 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
383 call_pdb = 0, include_vars=1):
294 call_pdb = 0, include_vars=1):
384 """Specify traceback offset, headers and color scheme.
295 """Specify traceback offset, headers and color scheme.
385
296
386 Define how many frames to drop from the tracebacks. Calling it with
297 Define how many frames to drop from the tracebacks. Calling it with
387 tb_offset=1 allows use of this handler in interpreters which will have
298 tb_offset=1 allows use of this handler in interpreters which will have
388 their own code at the top of the traceback (VerboseTB will first
299 their own code at the top of the traceback (VerboseTB will first
389 remove that frame before printing the traceback info)."""
300 remove that frame before printing the traceback info)."""
390 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
301 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
391 self.tb_offset = tb_offset
302 self.tb_offset = tb_offset
392 self.long_header = long_header
303 self.long_header = long_header
393 self.include_vars = include_vars
304 self.include_vars = include_vars
394
305
395 def text(self, etype, evalue, etb, context=5):
306 def text(self, etype, evalue, etb, context=5):
396 """Return a nice text document describing the traceback."""
307 """Return a nice text document describing the traceback."""
397
308
398 # some locals
309 # some locals
399 Colors = self.Colors # just a shorthand + quicker name lookup
310 Colors = self.Colors # just a shorthand + quicker name lookup
400 ColorsNormal = Colors.Normal # used a lot
311 ColorsNormal = Colors.Normal # used a lot
401 indent_size = 8 # we need some space to put line numbers before
312 indent_size = 8 # we need some space to put line numbers before
402 indent = ' '*indent_size
313 indent = ' '*indent_size
403 numbers_width = indent_size - 1 # leave space between numbers & code
314 numbers_width = indent_size - 1 # leave space between numbers & code
404 text_repr = pydoc.text.repr
315 text_repr = pydoc.text.repr
405 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
316 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
406 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
317 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
407 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
318 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
408
319
409 # some internal-use functions
320 # some internal-use functions
410 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
321 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
411 def nullrepr(value, repr=text_repr): return ''
322 def nullrepr(value, repr=text_repr): return ''
412
323
413 # meat of the code begins
324 # meat of the code begins
414 if type(etype) is types.ClassType:
325 if type(etype) is types.ClassType:
415 etype = etype.__name__
326 etype = etype.__name__
416
327
417 if self.long_header:
328 if self.long_header:
418 # Header with the exception type, python version, and date
329 # Header with the exception type, python version, and date
419 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
330 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
420 date = time.ctime(time.time())
331 date = time.ctime(time.time())
421
332
422 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
333 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
423 exc, ' '*(75-len(str(etype))-len(pyver)),
334 exc, ' '*(75-len(str(etype))-len(pyver)),
424 pyver, string.rjust(date, 75) )
335 pyver, string.rjust(date, 75) )
425 head += "\nA problem occured executing Python code. Here is the sequence of function"\
336 head += "\nA problem occured executing Python code. Here is the sequence of function"\
426 "\ncalls leading up to the error, with the most recent (innermost) call last."
337 "\ncalls leading up to the error, with the most recent (innermost) call last."
427 else:
338 else:
428 # Simplified header
339 # Simplified header
429 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
340 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
430 string.rjust('Traceback (most recent call last)',
341 string.rjust('Traceback (most recent call last)',
431 75 - len(str(etype)) ) )
342 75 - len(str(etype)) ) )
432 frames = []
343 frames = []
433 # Flush cache before calling inspect. This helps alleviate some of the
344 # Flush cache before calling inspect. This helps alleviate some of the
434 # problems with python 2.3's inspect.py.
345 # problems with python 2.3's inspect.py.
435 linecache.checkcache()
346 linecache.checkcache()
436 # Drop topmost frames if requested
347 # Drop topmost frames if requested
437 try:
348 try:
438 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
349 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
439 except:
350 except:
440
351
441 # FIXME: I've been getting many crash reports from python 2.3
352 # FIXME: I've been getting many crash reports from python 2.3
442 # users, traceable to inspect.py. If I can find a small test-case
353 # users, traceable to inspect.py. If I can find a small test-case
443 # to reproduce this, I should either write a better workaround or
354 # to reproduce this, I should either write a better workaround or
444 # file a bug report against inspect (if that's the real problem).
355 # file a bug report against inspect (if that's the real problem).
445 # So far, I haven't been able to find an isolated example to
356 # So far, I haven't been able to find an isolated example to
446 # reproduce the problem.
357 # reproduce the problem.
447 inspect_error()
358 inspect_error()
448 traceback.print_exc(file=Term.cerr)
359 traceback.print_exc(file=Term.cerr)
449 info('\nUnfortunately, your original traceback can not be constructed.\n')
360 info('\nUnfortunately, your original traceback can not be constructed.\n')
450 return ''
361 return ''
451
362
452 # build some color string templates outside these nested loops
363 # build some color string templates outside these nested loops
453 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
364 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
454 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
365 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
455 ColorsNormal)
366 ColorsNormal)
456 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
367 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
457 (Colors.vName, Colors.valEm, ColorsNormal)
368 (Colors.vName, Colors.valEm, ColorsNormal)
458 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
369 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
459 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
370 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
460 Colors.vName, ColorsNormal)
371 Colors.vName, ColorsNormal)
461 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
372 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
462 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
373 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
463 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
374 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
464 ColorsNormal)
375 ColorsNormal)
465
376
466 # now, loop over all records printing context and info
377 # now, loop over all records printing context and info
467 abspath = os.path.abspath
378 abspath = os.path.abspath
468 for frame, file, lnum, func, lines, index in records:
379 for frame, file, lnum, func, lines, index in records:
469 #print '*** record:',file,lnum,func,lines,index # dbg
380 #print '*** record:',file,lnum,func,lines,index # dbg
470 try:
381 try:
471 file = file and abspath(file) or '?'
382 file = file and abspath(file) or '?'
472 except OSError:
383 except OSError:
473 # if file is '<console>' or something not in the filesystem,
384 # if file is '<console>' or something not in the filesystem,
474 # the abspath call will throw an OSError. Just ignore it and
385 # the abspath call will throw an OSError. Just ignore it and
475 # keep the original file string.
386 # keep the original file string.
476 pass
387 pass
477 link = tpl_link % file
388 link = tpl_link % file
478 try:
389 try:
479 args, varargs, varkw, locals = inspect.getargvalues(frame)
390 args, varargs, varkw, locals = inspect.getargvalues(frame)
480 except:
391 except:
481 # This can happen due to a bug in python2.3. We should be
392 # This can happen due to a bug in python2.3. We should be
482 # able to remove this try/except when 2.4 becomes a
393 # able to remove this try/except when 2.4 becomes a
483 # requirement. Bug details at http://python.org/sf/1005466
394 # requirement. Bug details at http://python.org/sf/1005466
484 inspect_error()
395 inspect_error()
485 traceback.print_exc(file=Term.cerr)
396 traceback.print_exc(file=Term.cerr)
486 info("\nIPython's exception reporting continues...\n")
397 info("\nIPython's exception reporting continues...\n")
487
398
488 if func == '?':
399 if func == '?':
489 call = ''
400 call = ''
490 else:
401 else:
491 # Decide whether to include variable details or not
402 # Decide whether to include variable details or not
492 var_repr = self.include_vars and eqrepr or nullrepr
403 var_repr = self.include_vars and eqrepr or nullrepr
493 try:
404 try:
494 call = tpl_call % (func,inspect.formatargvalues(args,
405 call = tpl_call % (func,inspect.formatargvalues(args,
495 varargs, varkw,
406 varargs, varkw,
496 locals,formatvalue=var_repr))
407 locals,formatvalue=var_repr))
497 except KeyError:
408 except KeyError:
498 # Very odd crash from inspect.formatargvalues(). The
409 # Very odd crash from inspect.formatargvalues(). The
499 # scenario under which it appeared was a call to
410 # scenario under which it appeared was a call to
500 # view(array,scale) in NumTut.view.view(), where scale had
411 # view(array,scale) in NumTut.view.view(), where scale had
501 # been defined as a scalar (it should be a tuple). Somehow
412 # been defined as a scalar (it should be a tuple). Somehow
502 # inspect messes up resolving the argument list of view()
413 # inspect messes up resolving the argument list of view()
503 # and barfs out. At some point I should dig into this one
414 # and barfs out. At some point I should dig into this one
504 # and file a bug report about it.
415 # and file a bug report about it.
505 inspect_error()
416 inspect_error()
506 traceback.print_exc(file=Term.cerr)
417 traceback.print_exc(file=Term.cerr)
507 info("\nIPython's exception reporting continues...\n")
418 info("\nIPython's exception reporting continues...\n")
508 call = tpl_call_fail % func
419 call = tpl_call_fail % func
509
420
510 # Initialize a list of names on the current line, which the
421 # Initialize a list of names on the current line, which the
511 # tokenizer below will populate.
422 # tokenizer below will populate.
512 names = []
423 names = []
513
424
514 def tokeneater(token_type, token, start, end, line):
425 def tokeneater(token_type, token, start, end, line):
515 """Stateful tokeneater which builds dotted names.
426 """Stateful tokeneater which builds dotted names.
516
427
517 The list of names it appends to (from the enclosing scope) can
428 The list of names it appends to (from the enclosing scope) can
518 contain repeated composite names. This is unavoidable, since
429 contain repeated composite names. This is unavoidable, since
519 there is no way to disambguate partial dotted structures until
430 there is no way to disambguate partial dotted structures until
520 the full list is known. The caller is responsible for pruning
431 the full list is known. The caller is responsible for pruning
521 the final list of duplicates before using it."""
432 the final list of duplicates before using it."""
522
433
523 # build composite names
434 # build composite names
524 if token == '.':
435 if token == '.':
525 try:
436 try:
526 names[-1] += '.'
437 names[-1] += '.'
527 # store state so the next token is added for x.y.z names
438 # store state so the next token is added for x.y.z names
528 tokeneater.name_cont = True
439 tokeneater.name_cont = True
529 return
440 return
530 except IndexError:
441 except IndexError:
531 pass
442 pass
532 if token_type == tokenize.NAME and token not in keyword.kwlist:
443 if token_type == tokenize.NAME and token not in keyword.kwlist:
533 if tokeneater.name_cont:
444 if tokeneater.name_cont:
534 # Dotted names
445 # Dotted names
535 names[-1] += token
446 names[-1] += token
536 tokeneater.name_cont = False
447 tokeneater.name_cont = False
537 else:
448 else:
538 # Regular new names. We append everything, the caller
449 # Regular new names. We append everything, the caller
539 # will be responsible for pruning the list later. It's
450 # will be responsible for pruning the list later. It's
540 # very tricky to try to prune as we go, b/c composite
451 # very tricky to try to prune as we go, b/c composite
541 # names can fool us. The pruning at the end is easy
452 # names can fool us. The pruning at the end is easy
542 # to do (or the caller can print a list with repeated
453 # to do (or the caller can print a list with repeated
543 # names if so desired.
454 # names if so desired.
544 names.append(token)
455 names.append(token)
545 elif token_type == tokenize.NEWLINE:
456 elif token_type == tokenize.NEWLINE:
546 raise IndexError
457 raise IndexError
547 # we need to store a bit of state in the tokenizer to build
458 # we need to store a bit of state in the tokenizer to build
548 # dotted names
459 # dotted names
549 tokeneater.name_cont = False
460 tokeneater.name_cont = False
550
461
551 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
462 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
552 line = getline(file, lnum[0])
463 line = getline(file, lnum[0])
553 lnum[0] += 1
464 lnum[0] += 1
554 return line
465 return line
555
466
556 # Build the list of names on this line of code where the exception
467 # Build the list of names on this line of code where the exception
557 # occurred.
468 # occurred.
558 try:
469 try:
559 # This builds the names list in-place by capturing it from the
470 # This builds the names list in-place by capturing it from the
560 # enclosing scope.
471 # enclosing scope.
561 tokenize.tokenize(linereader, tokeneater)
472 tokenize.tokenize(linereader, tokeneater)
562 except IndexError:
473 except IndexError:
563 # signals exit of tokenizer
474 # signals exit of tokenizer
564 pass
475 pass
565 except tokenize.TokenError,msg:
476 except tokenize.TokenError,msg:
566 _m = ("An unexpected error occurred while tokenizing input\n"
477 _m = ("An unexpected error occurred while tokenizing input\n"
567 "The following traceback may be corrupted or invalid\n"
478 "The following traceback may be corrupted or invalid\n"
568 "The error message is: %s\n" % msg)
479 "The error message is: %s\n" % msg)
569 error(_m)
480 error(_m)
570
481
571 # prune names list of duplicates, but keep the right order
482 # prune names list of duplicates, but keep the right order
572 unique_names = uniq_stable(names)
483 unique_names = uniq_stable(names)
573
484
574 # Start loop over vars
485 # Start loop over vars
575 lvals = []
486 lvals = []
576 if self.include_vars:
487 if self.include_vars:
577 for name_full in unique_names:
488 for name_full in unique_names:
578 name_base = name_full.split('.',1)[0]
489 name_base = name_full.split('.',1)[0]
579 if name_base in frame.f_code.co_varnames:
490 if name_base in frame.f_code.co_varnames:
580 if locals.has_key(name_base):
491 if locals.has_key(name_base):
581 try:
492 try:
582 value = repr(eval(name_full,locals))
493 value = repr(eval(name_full,locals))
583 except:
494 except:
584 value = undefined
495 value = undefined
585 else:
496 else:
586 value = undefined
497 value = undefined
587 name = tpl_local_var % name_full
498 name = tpl_local_var % name_full
588 else:
499 else:
589 if frame.f_globals.has_key(name_base):
500 if frame.f_globals.has_key(name_base):
590 try:
501 try:
591 value = repr(eval(name_full,frame.f_globals))
502 value = repr(eval(name_full,frame.f_globals))
592 except:
503 except:
593 value = undefined
504 value = undefined
594 else:
505 else:
595 value = undefined
506 value = undefined
596 name = tpl_global_var % name_full
507 name = tpl_global_var % name_full
597 lvals.append(tpl_name_val % (name,value))
508 lvals.append(tpl_name_val % (name,value))
598 if lvals:
509 if lvals:
599 lvals = '%s%s' % (indent,em_normal.join(lvals))
510 lvals = '%s%s' % (indent,em_normal.join(lvals))
600 else:
511 else:
601 lvals = ''
512 lvals = ''
602
513
603 level = '%s %s\n' % (link,call)
514 level = '%s %s\n' % (link,call)
604 excerpt = []
515 excerpt = []
605 if index is not None:
516 if index is not None:
606 i = lnum - index
517 i = lnum - index
607 for line in lines:
518 for line in lines:
608 if i == lnum:
519 if i == lnum:
609 # This is the line with the error
520 # This is the line with the error
610 pad = numbers_width - len(str(i))
521 pad = numbers_width - len(str(i))
611 if pad >= 3:
522 if pad >= 3:
612 marker = '-'*(pad-3) + '-> '
523 marker = '-'*(pad-3) + '-> '
613 elif pad == 2:
524 elif pad == 2:
614 marker = '> '
525 marker = '> '
615 elif pad == 1:
526 elif pad == 1:
616 marker = '>'
527 marker = '>'
617 else:
528 else:
618 marker = ''
529 marker = ''
619 num = '%s%s' % (marker,i)
530 num = '%s%s' % (marker,i)
620 line = tpl_line_em % (num,line)
531 line = tpl_line_em % (num,line)
621 else:
532 else:
622 num = '%*s' % (numbers_width,i)
533 num = '%*s' % (numbers_width,i)
623 line = tpl_line % (num,line)
534 line = tpl_line % (num,line)
624
535
625 excerpt.append(line)
536 excerpt.append(line)
626 if self.include_vars and i == lnum:
537 if self.include_vars and i == lnum:
627 excerpt.append('%s\n' % lvals)
538 excerpt.append('%s\n' % lvals)
628 i += 1
539 i += 1
629 frames.append('%s%s' % (level,''.join(excerpt)) )
540 frames.append('%s%s' % (level,''.join(excerpt)) )
630
541
631 # Get (safely) a string form of the exception info
542 # Get (safely) a string form of the exception info
632 try:
543 try:
633 etype_str,evalue_str = map(str,(etype,evalue))
544 etype_str,evalue_str = map(str,(etype,evalue))
634 except:
545 except:
635 # User exception is improperly defined.
546 # User exception is improperly defined.
636 etype,evalue = str,sys.exc_info()[:2]
547 etype,evalue = str,sys.exc_info()[:2]
637 etype_str,evalue_str = map(str,(etype,evalue))
548 etype_str,evalue_str = map(str,(etype,evalue))
638 # ... and format it
549 # ... and format it
639 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
550 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
640 ColorsNormal, evalue_str)]
551 ColorsNormal, evalue_str)]
641 if type(evalue) is types.InstanceType:
552 if type(evalue) is types.InstanceType:
642 names = [w for w in dir(evalue) if isinstance(w, basestring)]
553 names = [w for w in dir(evalue) if isinstance(w, basestring)]
643 for name in names:
554 for name in names:
644 value = text_repr(getattr(evalue, name))
555 value = text_repr(getattr(evalue, name))
645 exception.append('\n%s%s = %s' % (indent, name, value))
556 exception.append('\n%s%s = %s' % (indent, name, value))
646 # return all our info assembled as a single string
557 # return all our info assembled as a single string
647 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
558 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
648
559
649 def debugger(self):
560 def debugger(self):
650 """Call up the pdb debugger if desired, always clean up the tb reference.
561 """Call up the pdb debugger if desired, always clean up the tb reference.
651
562
652 If the call_pdb flag is set, the pdb interactive debugger is
563 If the call_pdb flag is set, the pdb interactive debugger is
653 invoked. In all cases, the self.tb reference to the current traceback
564 invoked. In all cases, the self.tb reference to the current traceback
654 is deleted to prevent lingering references which hamper memory
565 is deleted to prevent lingering references which hamper memory
655 management.
566 management.
656
567
657 Note that each call to pdb() does an 'import readline', so if your app
568 Note that each call to pdb() does an 'import readline', so if your app
658 requires a special setup for the readline completers, you'll have to
569 requires a special setup for the readline completers, you'll have to
659 fix that by hand after invoking the exception handler."""
570 fix that by hand after invoking the exception handler."""
660
571
661 if self.call_pdb:
572 if self.call_pdb:
662 if self.pdb is None:
573 if self.pdb is None:
663 self.pdb = Debugger.Pdb()
574 self.pdb = Debugger.Pdb(
664 # the system displayhook may have changed, restore the original for pdb
575 self.color_scheme_table.active_scheme_name)
576 # the system displayhook may have changed, restore the original
577 # for pdb
665 dhook = sys.displayhook
578 dhook = sys.displayhook
666 sys.displayhook = sys.__displayhook__
579 sys.displayhook = sys.__displayhook__
667 self.pdb.reset()
580 self.pdb.reset()
581 # Find the right frame so we don't pop up inside ipython itself
582 etb = self.tb
668 while self.tb.tb_next is not None:
583 while self.tb.tb_next is not None:
669 self.tb = self.tb.tb_next
584 self.tb = self.tb.tb_next
670 try:
585 try:
586 if etb and etb.tb_next:
587 etb = etb.tb_next
588 self.pdb.botframe = etb.tb_frame
671 self.pdb.interaction(self.tb.tb_frame, self.tb)
589 self.pdb.interaction(self.tb.tb_frame, self.tb)
672 except:
590 except:
673 print '*** ERROR ***'
591 print '*** ERROR ***'
674 print 'This version of pdb has a bug and crashed.'
592 print 'This version of pdb has a bug and crashed.'
675 print 'Returning to IPython...'
593 print 'Returning to IPython...'
676 sys.displayhook = dhook
594 sys.displayhook = dhook
677 del self.tb
595 del self.tb
678
596
679 def handler(self, info=None):
597 def handler(self, info=None):
680 (etype, evalue, etb) = info or sys.exc_info()
598 (etype, evalue, etb) = info or sys.exc_info()
681 self.tb = etb
599 self.tb = etb
682 print >> Term.cerr, self.text(etype, evalue, etb)
600 print >> Term.cerr, self.text(etype, evalue, etb)
683
601
684 # Changed so an instance can just be called as VerboseTB_inst() and print
602 # Changed so an instance can just be called as VerboseTB_inst() and print
685 # out the right info on its own.
603 # out the right info on its own.
686 def __call__(self, etype=None, evalue=None, etb=None):
604 def __call__(self, etype=None, evalue=None, etb=None):
687 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
605 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
688 if etb is not None:
606 if etb is not None:
689 self.handler((etype, evalue, etb))
607 self.handler((etype, evalue, etb))
690 else:
608 else:
691 self.handler()
609 self.handler()
692 self.debugger()
610 self.debugger()
693
611
694 #----------------------------------------------------------------------------
612 #----------------------------------------------------------------------------
695 class FormattedTB(VerboseTB,ListTB):
613 class FormattedTB(VerboseTB,ListTB):
696 """Subclass ListTB but allow calling with a traceback.
614 """Subclass ListTB but allow calling with a traceback.
697
615
698 It can thus be used as a sys.excepthook for Python > 2.1.
616 It can thus be used as a sys.excepthook for Python > 2.1.
699
617
700 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
618 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
701
619
702 Allows a tb_offset to be specified. This is useful for situations where
620 Allows a tb_offset to be specified. This is useful for situations where
703 one needs to remove a number of topmost frames from the traceback (such as
621 one needs to remove a number of topmost frames from the traceback (such as
704 occurs with python programs that themselves execute other python code,
622 occurs with python programs that themselves execute other python code,
705 like Python shells). """
623 like Python shells). """
706
624
707 def __init__(self, mode = 'Plain', color_scheme='Linux',
625 def __init__(self, mode = 'Plain', color_scheme='Linux',
708 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
626 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
709
627
710 # NEVER change the order of this list. Put new modes at the end:
628 # NEVER change the order of this list. Put new modes at the end:
711 self.valid_modes = ['Plain','Context','Verbose']
629 self.valid_modes = ['Plain','Context','Verbose']
712 self.verbose_modes = self.valid_modes[1:3]
630 self.verbose_modes = self.valid_modes[1:3]
713
631
714 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
632 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
715 call_pdb=call_pdb,include_vars=include_vars)
633 call_pdb=call_pdb,include_vars=include_vars)
716 self.set_mode(mode)
634 self.set_mode(mode)
717
635
718 def _extract_tb(self,tb):
636 def _extract_tb(self,tb):
719 if tb:
637 if tb:
720 return traceback.extract_tb(tb)
638 return traceback.extract_tb(tb)
721 else:
639 else:
722 return None
640 return None
723
641
724 def text(self, etype, value, tb,context=5,mode=None):
642 def text(self, etype, value, tb,context=5,mode=None):
725 """Return formatted traceback.
643 """Return formatted traceback.
726
644
727 If the optional mode parameter is given, it overrides the current
645 If the optional mode parameter is given, it overrides the current
728 mode."""
646 mode."""
729
647
730 if mode is None:
648 if mode is None:
731 mode = self.mode
649 mode = self.mode
732 if mode in self.verbose_modes:
650 if mode in self.verbose_modes:
733 # verbose modes need a full traceback
651 # verbose modes need a full traceback
734 return VerboseTB.text(self,etype, value, tb,context=5)
652 return VerboseTB.text(self,etype, value, tb,context=5)
735 else:
653 else:
736 # We must check the source cache because otherwise we can print
654 # We must check the source cache because otherwise we can print
737 # out-of-date source code.
655 # out-of-date source code.
738 linecache.checkcache()
656 linecache.checkcache()
739 # Now we can extract and format the exception
657 # Now we can extract and format the exception
740 elist = self._extract_tb(tb)
658 elist = self._extract_tb(tb)
741 if len(elist) > self.tb_offset:
659 if len(elist) > self.tb_offset:
742 del elist[:self.tb_offset]
660 del elist[:self.tb_offset]
743 return ListTB.text(self,etype,value,elist)
661 return ListTB.text(self,etype,value,elist)
744
662
745 def set_mode(self,mode=None):
663 def set_mode(self,mode=None):
746 """Switch to the desired mode.
664 """Switch to the desired mode.
747
665
748 If mode is not specified, cycles through the available modes."""
666 If mode is not specified, cycles through the available modes."""
749
667
750 if not mode:
668 if not mode:
751 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
669 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
752 len(self.valid_modes)
670 len(self.valid_modes)
753 self.mode = self.valid_modes[new_idx]
671 self.mode = self.valid_modes[new_idx]
754 elif mode not in self.valid_modes:
672 elif mode not in self.valid_modes:
755 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
673 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
756 'Valid modes: '+str(self.valid_modes)
674 'Valid modes: '+str(self.valid_modes)
757 else:
675 else:
758 self.mode = mode
676 self.mode = mode
759 # include variable details only in 'Verbose' mode
677 # include variable details only in 'Verbose' mode
760 self.include_vars = (self.mode == self.valid_modes[2])
678 self.include_vars = (self.mode == self.valid_modes[2])
761
679
762 # some convenient shorcuts
680 # some convenient shorcuts
763 def plain(self):
681 def plain(self):
764 self.set_mode(self.valid_modes[0])
682 self.set_mode(self.valid_modes[0])
765
683
766 def context(self):
684 def context(self):
767 self.set_mode(self.valid_modes[1])
685 self.set_mode(self.valid_modes[1])
768
686
769 def verbose(self):
687 def verbose(self):
770 self.set_mode(self.valid_modes[2])
688 self.set_mode(self.valid_modes[2])
771
689
772 #----------------------------------------------------------------------------
690 #----------------------------------------------------------------------------
773 class AutoFormattedTB(FormattedTB):
691 class AutoFormattedTB(FormattedTB):
774 """A traceback printer which can be called on the fly.
692 """A traceback printer which can be called on the fly.
775
693
776 It will find out about exceptions by itself.
694 It will find out about exceptions by itself.
777
695
778 A brief example:
696 A brief example:
779
697
780 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
698 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
781 try:
699 try:
782 ...
700 ...
783 except:
701 except:
784 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
702 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
785 """
703 """
786 def __call__(self,etype=None,evalue=None,etb=None,
704 def __call__(self,etype=None,evalue=None,etb=None,
787 out=None,tb_offset=None):
705 out=None,tb_offset=None):
788 """Print out a formatted exception traceback.
706 """Print out a formatted exception traceback.
789
707
790 Optional arguments:
708 Optional arguments:
791 - out: an open file-like object to direct output to.
709 - out: an open file-like object to direct output to.
792
710
793 - tb_offset: the number of frames to skip over in the stack, on a
711 - tb_offset: the number of frames to skip over in the stack, on a
794 per-call basis (this overrides temporarily the instance's tb_offset
712 per-call basis (this overrides temporarily the instance's tb_offset
795 given at initialization time. """
713 given at initialization time. """
796
714
797 if out is None:
715 if out is None:
798 out = Term.cerr
716 out = Term.cerr
799 if tb_offset is not None:
717 if tb_offset is not None:
800 tb_offset, self.tb_offset = self.tb_offset, tb_offset
718 tb_offset, self.tb_offset = self.tb_offset, tb_offset
801 print >> out, self.text(etype, evalue, etb)
719 print >> out, self.text(etype, evalue, etb)
802 self.tb_offset = tb_offset
720 self.tb_offset = tb_offset
803 else:
721 else:
804 print >> out, self.text()
722 print >> out, self.text(etype, evalue, etb)
805 self.debugger()
723 self.debugger()
806
724
807 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
725 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
808 if etype is None:
726 if etype is None:
809 etype,value,tb = sys.exc_info()
727 etype,value,tb = sys.exc_info()
810 self.tb = tb
728 self.tb = tb
811 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
729 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
812
730
813 #---------------------------------------------------------------------------
731 #---------------------------------------------------------------------------
814 # A simple class to preserve Nathan's original functionality.
732 # A simple class to preserve Nathan's original functionality.
815 class ColorTB(FormattedTB):
733 class ColorTB(FormattedTB):
816 """Shorthand to initialize a FormattedTB in Linux colors mode."""
734 """Shorthand to initialize a FormattedTB in Linux colors mode."""
817 def __init__(self,color_scheme='Linux',call_pdb=0):
735 def __init__(self,color_scheme='Linux',call_pdb=0):
818 FormattedTB.__init__(self,color_scheme=color_scheme,
736 FormattedTB.__init__(self,color_scheme=color_scheme,
819 call_pdb=call_pdb)
737 call_pdb=call_pdb)
820
738
821 #----------------------------------------------------------------------------
739 #----------------------------------------------------------------------------
822 # module testing (minimal)
740 # module testing (minimal)
823 if __name__ == "__main__":
741 if __name__ == "__main__":
824 def spam(c, (d, e)):
742 def spam(c, (d, e)):
825 x = c + d
743 x = c + d
826 y = c * d
744 y = c * d
827 foo(x, y)
745 foo(x, y)
828
746
829 def foo(a, b, bar=1):
747 def foo(a, b, bar=1):
830 eggs(a, b + bar)
748 eggs(a, b + bar)
831
749
832 def eggs(f, g, z=globals()):
750 def eggs(f, g, z=globals()):
833 h = f + g
751 h = f + g
834 i = f - g
752 i = f - g
835 return h / i
753 return h / i
836
754
837 print ''
755 print ''
838 print '*** Before ***'
756 print '*** Before ***'
839 try:
757 try:
840 print spam(1, (2, 3))
758 print spam(1, (2, 3))
841 except:
759 except:
842 traceback.print_exc()
760 traceback.print_exc()
843 print ''
761 print ''
844
762
845 handler = ColorTB()
763 handler = ColorTB()
846 print '*** ColorTB ***'
764 print '*** ColorTB ***'
847 try:
765 try:
848 print spam(1, (2, 3))
766 print spam(1, (2, 3))
849 except:
767 except:
850 apply(handler, sys.exc_info() )
768 apply(handler, sys.exc_info() )
851 print ''
769 print ''
852
770
853 handler = VerboseTB()
771 handler = VerboseTB()
854 print '*** VerboseTB ***'
772 print '*** VerboseTB ***'
855 try:
773 try:
856 print spam(1, (2, 3))
774 print spam(1, (2, 3))
857 except:
775 except:
858 apply(handler, sys.exc_info() )
776 apply(handler, sys.exc_info() )
859 print ''
777 print ''
860
778
@@ -1,4477 +1,4493 b''
1 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * setup.py: added download_url to setup(). This registers the
4 download address at PyPI, which is not only useful to humans
5 browsing the site, but is also picked up by setuptools (the Eggs
6 machinery). Thanks to Ville and R. Kern for the info/discussion
7 on this.
8
9 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
10
11 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
12 This brings a lot of nice functionality to the pdb mode, which now
13 has tab-completion, syntax highlighting, and better stack handling
14 than before. Many thanks to Vivian De Smedt
15 <vivian-AT-vdesmedt.com> for the original patches.
16
1 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
17 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
2
18
3 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
19 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
4 sequence to consistently accept the banner argument. The
20 sequence to consistently accept the banner argument. The
5 inconsistency was tripping SAGE, thanks to Gary Zablackis
21 inconsistency was tripping SAGE, thanks to Gary Zablackis
6 <gzabl-AT-yahoo.com> for the report.
22 <gzabl-AT-yahoo.com> for the report.
7
23
8 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
24 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
9
25
10 * IPython/iplib.py (InteractiveShell.post_config_initialization):
26 * IPython/iplib.py (InteractiveShell.post_config_initialization):
11 Fix bug where a naked 'alias' call in the ipythonrc file would
27 Fix bug where a naked 'alias' call in the ipythonrc file would
12 cause a crash. Bug reported by Jorgen Stenarson.
28 cause a crash. Bug reported by Jorgen Stenarson.
13
29
14 2005-11-15 <Fernando.Perez@colorado.edu>
30 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
15
31
16 * IPython/ipmaker.py (make_IPython): cleanups which should improve
32 * IPython/ipmaker.py (make_IPython): cleanups which should improve
17 startup time.
33 startup time.
18
34
19 * IPython/iplib.py (runcode): my globals 'fix' for embedded
35 * IPython/iplib.py (runcode): my globals 'fix' for embedded
20 instances had introduced a bug with globals in normal code. Now
36 instances had introduced a bug with globals in normal code. Now
21 it's working in all cases.
37 it's working in all cases.
22
38
23 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
39 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
24 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
40 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
25 has been introduced to set the default case sensitivity of the
41 has been introduced to set the default case sensitivity of the
26 searches. Users can still select either mode at runtime on a
42 searches. Users can still select either mode at runtime on a
27 per-search basis.
43 per-search basis.
28
44
29 2005-11-13 <Fernando.Perez@colorado.edu>
45 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
30
46
31 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
47 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
32 attributes in wildcard searches for subclasses. Modified version
48 attributes in wildcard searches for subclasses. Modified version
33 of a patch by Jorgen.
49 of a patch by Jorgen.
34
50
35 2005-11-12 <Fernando.Perez@colorado.edu>
51 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
36
52
37 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
53 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
38 embedded instances. I added a user_global_ns attribute to the
54 embedded instances. I added a user_global_ns attribute to the
39 InteractiveShell class to handle this.
55 InteractiveShell class to handle this.
40
56
41 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
57 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
42
58
43 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
59 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
44 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
60 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
45 (reported under win32, but may happen also in other platforms).
61 (reported under win32, but may happen also in other platforms).
46 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
62 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
47
63
48 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
64 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
49
65
50 * IPython/Magic.py (magic_psearch): new support for wildcard
66 * IPython/Magic.py (magic_psearch): new support for wildcard
51 patterns. Now, typing ?a*b will list all names which begin with a
67 patterns. Now, typing ?a*b will list all names which begin with a
52 and end in b, for example. The %psearch magic has full
68 and end in b, for example. The %psearch magic has full
53 docstrings. Many thanks to JΓΆrgen Stenarson
69 docstrings. Many thanks to JΓΆrgen Stenarson
54 <jorgen.stenarson-AT-bostream.nu>, author of the patches
70 <jorgen.stenarson-AT-bostream.nu>, author of the patches
55 implementing this functionality.
71 implementing this functionality.
56
72
57 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
73 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
58
74
59 * Manual: fixed long-standing annoyance of double-dashes (as in
75 * Manual: fixed long-standing annoyance of double-dashes (as in
60 --prefix=~, for example) being stripped in the HTML version. This
76 --prefix=~, for example) being stripped in the HTML version. This
61 is a latex2html bug, but a workaround was provided. Many thanks
77 is a latex2html bug, but a workaround was provided. Many thanks
62 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
78 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
63 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
79 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
64 rolling. This seemingly small issue had tripped a number of users
80 rolling. This seemingly small issue had tripped a number of users
65 when first installing, so I'm glad to see it gone.
81 when first installing, so I'm glad to see it gone.
66
82
67 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
83 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
68
84
69 * IPython/Extensions/numeric_formats.py: fix missing import,
85 * IPython/Extensions/numeric_formats.py: fix missing import,
70 reported by Stephen Walton.
86 reported by Stephen Walton.
71
87
72 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
88 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
73
89
74 * IPython/demo.py: finish demo module, fully documented now.
90 * IPython/demo.py: finish demo module, fully documented now.
75
91
76 * IPython/genutils.py (file_read): simple little utility to read a
92 * IPython/genutils.py (file_read): simple little utility to read a
77 file and ensure it's closed afterwards.
93 file and ensure it's closed afterwards.
78
94
79 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
95 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
80
96
81 * IPython/demo.py (Demo.__init__): added support for individually
97 * IPython/demo.py (Demo.__init__): added support for individually
82 tagging blocks for automatic execution.
98 tagging blocks for automatic execution.
83
99
84 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
100 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
85 syntax-highlighted python sources, requested by John.
101 syntax-highlighted python sources, requested by John.
86
102
87 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
103 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
88
104
89 * IPython/demo.py (Demo.again): fix bug where again() blocks after
105 * IPython/demo.py (Demo.again): fix bug where again() blocks after
90 finishing.
106 finishing.
91
107
92 * IPython/genutils.py (shlex_split): moved from Magic to here,
108 * IPython/genutils.py (shlex_split): moved from Magic to here,
93 where all 2.2 compatibility stuff lives. I needed it for demo.py.
109 where all 2.2 compatibility stuff lives. I needed it for demo.py.
94
110
95 * IPython/demo.py (Demo.__init__): added support for silent
111 * IPython/demo.py (Demo.__init__): added support for silent
96 blocks, improved marks as regexps, docstrings written.
112 blocks, improved marks as regexps, docstrings written.
97 (Demo.__init__): better docstring, added support for sys.argv.
113 (Demo.__init__): better docstring, added support for sys.argv.
98
114
99 * IPython/genutils.py (marquee): little utility used by the demo
115 * IPython/genutils.py (marquee): little utility used by the demo
100 code, handy in general.
116 code, handy in general.
101
117
102 * IPython/demo.py (Demo.__init__): new class for interactive
118 * IPython/demo.py (Demo.__init__): new class for interactive
103 demos. Not documented yet, I just wrote it in a hurry for
119 demos. Not documented yet, I just wrote it in a hurry for
104 scipy'05. Will docstring later.
120 scipy'05. Will docstring later.
105
121
106 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
122 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
107
123
108 * IPython/Shell.py (sigint_handler): Drastic simplification which
124 * IPython/Shell.py (sigint_handler): Drastic simplification which
109 also seems to make Ctrl-C work correctly across threads! This is
125 also seems to make Ctrl-C work correctly across threads! This is
110 so simple, that I can't beleive I'd missed it before. Needs more
126 so simple, that I can't beleive I'd missed it before. Needs more
111 testing, though.
127 testing, though.
112 (KBINT): Never mind, revert changes. I'm sure I'd tried something
128 (KBINT): Never mind, revert changes. I'm sure I'd tried something
113 like this before...
129 like this before...
114
130
115 * IPython/genutils.py (get_home_dir): add protection against
131 * IPython/genutils.py (get_home_dir): add protection against
116 non-dirs in win32 registry.
132 non-dirs in win32 registry.
117
133
118 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
134 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
119 bug where dict was mutated while iterating (pysh crash).
135 bug where dict was mutated while iterating (pysh crash).
120
136
121 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
137 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
122
138
123 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
139 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
124 spurious newlines added by this routine. After a report by
140 spurious newlines added by this routine. After a report by
125 F. Mantegazza.
141 F. Mantegazza.
126
142
127 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
143 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
128
144
129 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
145 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
130 calls. These were a leftover from the GTK 1.x days, and can cause
146 calls. These were a leftover from the GTK 1.x days, and can cause
131 problems in certain cases (after a report by John Hunter).
147 problems in certain cases (after a report by John Hunter).
132
148
133 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
149 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
134 os.getcwd() fails at init time. Thanks to patch from David Remahl
150 os.getcwd() fails at init time. Thanks to patch from David Remahl
135 <chmod007-AT-mac.com>.
151 <chmod007-AT-mac.com>.
136 (InteractiveShell.__init__): prevent certain special magics from
152 (InteractiveShell.__init__): prevent certain special magics from
137 being shadowed by aliases. Closes
153 being shadowed by aliases. Closes
138 http://www.scipy.net/roundup/ipython/issue41.
154 http://www.scipy.net/roundup/ipython/issue41.
139
155
140 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
156 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
141
157
142 * IPython/iplib.py (InteractiveShell.complete): Added new
158 * IPython/iplib.py (InteractiveShell.complete): Added new
143 top-level completion method to expose the completion mechanism
159 top-level completion method to expose the completion mechanism
144 beyond readline-based environments.
160 beyond readline-based environments.
145
161
146 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
162 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
147
163
148 * tools/ipsvnc (svnversion): fix svnversion capture.
164 * tools/ipsvnc (svnversion): fix svnversion capture.
149
165
150 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
166 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
151 attribute to self, which was missing. Before, it was set by a
167 attribute to self, which was missing. Before, it was set by a
152 routine which in certain cases wasn't being called, so the
168 routine which in certain cases wasn't being called, so the
153 instance could end up missing the attribute. This caused a crash.
169 instance could end up missing the attribute. This caused a crash.
154 Closes http://www.scipy.net/roundup/ipython/issue40.
170 Closes http://www.scipy.net/roundup/ipython/issue40.
155
171
156 2005-08-16 Fernando Perez <fperez@colorado.edu>
172 2005-08-16 Fernando Perez <fperez@colorado.edu>
157
173
158 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
174 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
159 contains non-string attribute. Closes
175 contains non-string attribute. Closes
160 http://www.scipy.net/roundup/ipython/issue38.
176 http://www.scipy.net/roundup/ipython/issue38.
161
177
162 2005-08-14 Fernando Perez <fperez@colorado.edu>
178 2005-08-14 Fernando Perez <fperez@colorado.edu>
163
179
164 * tools/ipsvnc: Minor improvements, to add changeset info.
180 * tools/ipsvnc: Minor improvements, to add changeset info.
165
181
166 2005-08-12 Fernando Perez <fperez@colorado.edu>
182 2005-08-12 Fernando Perez <fperez@colorado.edu>
167
183
168 * IPython/iplib.py (runsource): remove self.code_to_run_src
184 * IPython/iplib.py (runsource): remove self.code_to_run_src
169 attribute. I realized this is nothing more than
185 attribute. I realized this is nothing more than
170 '\n'.join(self.buffer), and having the same data in two different
186 '\n'.join(self.buffer), and having the same data in two different
171 places is just asking for synchronization bugs. This may impact
187 places is just asking for synchronization bugs. This may impact
172 people who have custom exception handlers, so I need to warn
188 people who have custom exception handlers, so I need to warn
173 ipython-dev about it (F. Mantegazza may use them).
189 ipython-dev about it (F. Mantegazza may use them).
174
190
175 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
191 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
176
192
177 * IPython/genutils.py: fix 2.2 compatibility (generators)
193 * IPython/genutils.py: fix 2.2 compatibility (generators)
178
194
179 2005-07-18 Fernando Perez <fperez@colorado.edu>
195 2005-07-18 Fernando Perez <fperez@colorado.edu>
180
196
181 * IPython/genutils.py (get_home_dir): fix to help users with
197 * IPython/genutils.py (get_home_dir): fix to help users with
182 invalid $HOME under win32.
198 invalid $HOME under win32.
183
199
184 2005-07-17 Fernando Perez <fperez@colorado.edu>
200 2005-07-17 Fernando Perez <fperez@colorado.edu>
185
201
186 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
202 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
187 some old hacks and clean up a bit other routines; code should be
203 some old hacks and clean up a bit other routines; code should be
188 simpler and a bit faster.
204 simpler and a bit faster.
189
205
190 * IPython/iplib.py (interact): removed some last-resort attempts
206 * IPython/iplib.py (interact): removed some last-resort attempts
191 to survive broken stdout/stderr. That code was only making it
207 to survive broken stdout/stderr. That code was only making it
192 harder to abstract out the i/o (necessary for gui integration),
208 harder to abstract out the i/o (necessary for gui integration),
193 and the crashes it could prevent were extremely rare in practice
209 and the crashes it could prevent were extremely rare in practice
194 (besides being fully user-induced in a pretty violent manner).
210 (besides being fully user-induced in a pretty violent manner).
195
211
196 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
212 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
197 Nothing major yet, but the code is simpler to read; this should
213 Nothing major yet, but the code is simpler to read; this should
198 make it easier to do more serious modifications in the future.
214 make it easier to do more serious modifications in the future.
199
215
200 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
216 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
201 which broke in .15 (thanks to a report by Ville).
217 which broke in .15 (thanks to a report by Ville).
202
218
203 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
219 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
204 be quite correct, I know next to nothing about unicode). This
220 be quite correct, I know next to nothing about unicode). This
205 will allow unicode strings to be used in prompts, amongst other
221 will allow unicode strings to be used in prompts, amongst other
206 cases. It also will prevent ipython from crashing when unicode
222 cases. It also will prevent ipython from crashing when unicode
207 shows up unexpectedly in many places. If ascii encoding fails, we
223 shows up unexpectedly in many places. If ascii encoding fails, we
208 assume utf_8. Currently the encoding is not a user-visible
224 assume utf_8. Currently the encoding is not a user-visible
209 setting, though it could be made so if there is demand for it.
225 setting, though it could be made so if there is demand for it.
210
226
211 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
227 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
212
228
213 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
229 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
214
230
215 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
231 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
216
232
217 * IPython/genutils.py: Add 2.2 compatibility here, so all other
233 * IPython/genutils.py: Add 2.2 compatibility here, so all other
218 code can work transparently for 2.2/2.3.
234 code can work transparently for 2.2/2.3.
219
235
220 2005-07-16 Fernando Perez <fperez@colorado.edu>
236 2005-07-16 Fernando Perez <fperez@colorado.edu>
221
237
222 * IPython/ultraTB.py (ExceptionColors): Make a global variable
238 * IPython/ultraTB.py (ExceptionColors): Make a global variable
223 out of the color scheme table used for coloring exception
239 out of the color scheme table used for coloring exception
224 tracebacks. This allows user code to add new schemes at runtime.
240 tracebacks. This allows user code to add new schemes at runtime.
225 This is a minimally modified version of the patch at
241 This is a minimally modified version of the patch at
226 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
242 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
227 for the contribution.
243 for the contribution.
228
244
229 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
245 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
230 slightly modified version of the patch in
246 slightly modified version of the patch in
231 http://www.scipy.net/roundup/ipython/issue34, which also allows me
247 http://www.scipy.net/roundup/ipython/issue34, which also allows me
232 to remove the previous try/except solution (which was costlier).
248 to remove the previous try/except solution (which was costlier).
233 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
249 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
234
250
235 2005-06-08 Fernando Perez <fperez@colorado.edu>
251 2005-06-08 Fernando Perez <fperez@colorado.edu>
236
252
237 * IPython/iplib.py (write/write_err): Add methods to abstract all
253 * IPython/iplib.py (write/write_err): Add methods to abstract all
238 I/O a bit more.
254 I/O a bit more.
239
255
240 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
256 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
241 warning, reported by Aric Hagberg, fix by JD Hunter.
257 warning, reported by Aric Hagberg, fix by JD Hunter.
242
258
243 2005-06-02 *** Released version 0.6.15
259 2005-06-02 *** Released version 0.6.15
244
260
245 2005-06-01 Fernando Perez <fperez@colorado.edu>
261 2005-06-01 Fernando Perez <fperez@colorado.edu>
246
262
247 * IPython/iplib.py (MagicCompleter.file_matches): Fix
263 * IPython/iplib.py (MagicCompleter.file_matches): Fix
248 tab-completion of filenames within open-quoted strings. Note that
264 tab-completion of filenames within open-quoted strings. Note that
249 this requires that in ~/.ipython/ipythonrc, users change the
265 this requires that in ~/.ipython/ipythonrc, users change the
250 readline delimiters configuration to read:
266 readline delimiters configuration to read:
251
267
252 readline_remove_delims -/~
268 readline_remove_delims -/~
253
269
254
270
255 2005-05-31 *** Released version 0.6.14
271 2005-05-31 *** Released version 0.6.14
256
272
257 2005-05-29 Fernando Perez <fperez@colorado.edu>
273 2005-05-29 Fernando Perez <fperez@colorado.edu>
258
274
259 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
275 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
260 with files not on the filesystem. Reported by Eliyahu Sandler
276 with files not on the filesystem. Reported by Eliyahu Sandler
261 <eli@gondolin.net>
277 <eli@gondolin.net>
262
278
263 2005-05-22 Fernando Perez <fperez@colorado.edu>
279 2005-05-22 Fernando Perez <fperez@colorado.edu>
264
280
265 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
281 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
266 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
282 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
267
283
268 2005-05-19 Fernando Perez <fperez@colorado.edu>
284 2005-05-19 Fernando Perez <fperez@colorado.edu>
269
285
270 * IPython/iplib.py (safe_execfile): close a file which could be
286 * IPython/iplib.py (safe_execfile): close a file which could be
271 left open (causing problems in win32, which locks open files).
287 left open (causing problems in win32, which locks open files).
272 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
288 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
273
289
274 2005-05-18 Fernando Perez <fperez@colorado.edu>
290 2005-05-18 Fernando Perez <fperez@colorado.edu>
275
291
276 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
292 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
277 keyword arguments correctly to safe_execfile().
293 keyword arguments correctly to safe_execfile().
278
294
279 2005-05-13 Fernando Perez <fperez@colorado.edu>
295 2005-05-13 Fernando Perez <fperez@colorado.edu>
280
296
281 * ipython.1: Added info about Qt to manpage, and threads warning
297 * ipython.1: Added info about Qt to manpage, and threads warning
282 to usage page (invoked with --help).
298 to usage page (invoked with --help).
283
299
284 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
300 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
285 new matcher (it goes at the end of the priority list) to do
301 new matcher (it goes at the end of the priority list) to do
286 tab-completion on named function arguments. Submitted by George
302 tab-completion on named function arguments. Submitted by George
287 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
303 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
288 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
304 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
289 for more details.
305 for more details.
290
306
291 * IPython/Magic.py (magic_run): Added new -e flag to ignore
307 * IPython/Magic.py (magic_run): Added new -e flag to ignore
292 SystemExit exceptions in the script being run. Thanks to a report
308 SystemExit exceptions in the script being run. Thanks to a report
293 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
309 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
294 producing very annoying behavior when running unit tests.
310 producing very annoying behavior when running unit tests.
295
311
296 2005-05-12 Fernando Perez <fperez@colorado.edu>
312 2005-05-12 Fernando Perez <fperez@colorado.edu>
297
313
298 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
314 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
299 which I'd broken (again) due to a changed regexp. In the process,
315 which I'd broken (again) due to a changed regexp. In the process,
300 added ';' as an escape to auto-quote the whole line without
316 added ';' as an escape to auto-quote the whole line without
301 splitting its arguments. Thanks to a report by Jerry McRae
317 splitting its arguments. Thanks to a report by Jerry McRae
302 <qrs0xyc02-AT-sneakemail.com>.
318 <qrs0xyc02-AT-sneakemail.com>.
303
319
304 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
320 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
305 possible crashes caused by a TokenError. Reported by Ed Schofield
321 possible crashes caused by a TokenError. Reported by Ed Schofield
306 <schofield-AT-ftw.at>.
322 <schofield-AT-ftw.at>.
307
323
308 2005-05-06 Fernando Perez <fperez@colorado.edu>
324 2005-05-06 Fernando Perez <fperez@colorado.edu>
309
325
310 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
326 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
311
327
312 2005-04-29 Fernando Perez <fperez@colorado.edu>
328 2005-04-29 Fernando Perez <fperez@colorado.edu>
313
329
314 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
330 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
315 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
331 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
316 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
332 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
317 which provides support for Qt interactive usage (similar to the
333 which provides support for Qt interactive usage (similar to the
318 existing one for WX and GTK). This had been often requested.
334 existing one for WX and GTK). This had been often requested.
319
335
320 2005-04-14 *** Released version 0.6.13
336 2005-04-14 *** Released version 0.6.13
321
337
322 2005-04-08 Fernando Perez <fperez@colorado.edu>
338 2005-04-08 Fernando Perez <fperez@colorado.edu>
323
339
324 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
340 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
325 from _ofind, which gets called on almost every input line. Now,
341 from _ofind, which gets called on almost every input line. Now,
326 we only try to get docstrings if they are actually going to be
342 we only try to get docstrings if they are actually going to be
327 used (the overhead of fetching unnecessary docstrings can be
343 used (the overhead of fetching unnecessary docstrings can be
328 noticeable for certain objects, such as Pyro proxies).
344 noticeable for certain objects, such as Pyro proxies).
329
345
330 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
346 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
331 for completers. For some reason I had been passing them the state
347 for completers. For some reason I had been passing them the state
332 variable, which completers never actually need, and was in
348 variable, which completers never actually need, and was in
333 conflict with the rlcompleter API. Custom completers ONLY need to
349 conflict with the rlcompleter API. Custom completers ONLY need to
334 take the text parameter.
350 take the text parameter.
335
351
336 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
352 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
337 work correctly in pysh. I've also moved all the logic which used
353 work correctly in pysh. I've also moved all the logic which used
338 to be in pysh.py here, which will prevent problems with future
354 to be in pysh.py here, which will prevent problems with future
339 upgrades. However, this time I must warn users to update their
355 upgrades. However, this time I must warn users to update their
340 pysh profile to include the line
356 pysh profile to include the line
341
357
342 import_all IPython.Extensions.InterpreterExec
358 import_all IPython.Extensions.InterpreterExec
343
359
344 because otherwise things won't work for them. They MUST also
360 because otherwise things won't work for them. They MUST also
345 delete pysh.py and the line
361 delete pysh.py and the line
346
362
347 execfile pysh.py
363 execfile pysh.py
348
364
349 from their ipythonrc-pysh.
365 from their ipythonrc-pysh.
350
366
351 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
367 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
352 robust in the face of objects whose dir() returns non-strings
368 robust in the face of objects whose dir() returns non-strings
353 (which it shouldn't, but some broken libs like ITK do). Thanks to
369 (which it shouldn't, but some broken libs like ITK do). Thanks to
354 a patch by John Hunter (implemented differently, though). Also
370 a patch by John Hunter (implemented differently, though). Also
355 minor improvements by using .extend instead of + on lists.
371 minor improvements by using .extend instead of + on lists.
356
372
357 * pysh.py:
373 * pysh.py:
358
374
359 2005-04-06 Fernando Perez <fperez@colorado.edu>
375 2005-04-06 Fernando Perez <fperez@colorado.edu>
360
376
361 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
377 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
362 by default, so that all users benefit from it. Those who don't
378 by default, so that all users benefit from it. Those who don't
363 want it can still turn it off.
379 want it can still turn it off.
364
380
365 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
381 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
366 config file, I'd forgotten about this, so users were getting it
382 config file, I'd forgotten about this, so users were getting it
367 off by default.
383 off by default.
368
384
369 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
385 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
370 consistency. Now magics can be called in multiline statements,
386 consistency. Now magics can be called in multiline statements,
371 and python variables can be expanded in magic calls via $var.
387 and python variables can be expanded in magic calls via $var.
372 This makes the magic system behave just like aliases or !system
388 This makes the magic system behave just like aliases or !system
373 calls.
389 calls.
374
390
375 2005-03-28 Fernando Perez <fperez@colorado.edu>
391 2005-03-28 Fernando Perez <fperez@colorado.edu>
376
392
377 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
393 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
378 expensive string additions for building command. Add support for
394 expensive string additions for building command. Add support for
379 trailing ';' when autocall is used.
395 trailing ';' when autocall is used.
380
396
381 2005-03-26 Fernando Perez <fperez@colorado.edu>
397 2005-03-26 Fernando Perez <fperez@colorado.edu>
382
398
383 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
399 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
384 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
400 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
385 ipython.el robust against prompts with any number of spaces
401 ipython.el robust against prompts with any number of spaces
386 (including 0) after the ':' character.
402 (including 0) after the ':' character.
387
403
388 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
404 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
389 continuation prompt, which misled users to think the line was
405 continuation prompt, which misled users to think the line was
390 already indented. Closes debian Bug#300847, reported to me by
406 already indented. Closes debian Bug#300847, reported to me by
391 Norbert Tretkowski <tretkowski-AT-inittab.de>.
407 Norbert Tretkowski <tretkowski-AT-inittab.de>.
392
408
393 2005-03-23 Fernando Perez <fperez@colorado.edu>
409 2005-03-23 Fernando Perez <fperez@colorado.edu>
394
410
395 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
411 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
396 properly aligned if they have embedded newlines.
412 properly aligned if they have embedded newlines.
397
413
398 * IPython/iplib.py (runlines): Add a public method to expose
414 * IPython/iplib.py (runlines): Add a public method to expose
399 IPython's code execution machinery, so that users can run strings
415 IPython's code execution machinery, so that users can run strings
400 as if they had been typed at the prompt interactively.
416 as if they had been typed at the prompt interactively.
401 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
417 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
402 methods which can call the system shell, but with python variable
418 methods which can call the system shell, but with python variable
403 expansion. The three such methods are: __IPYTHON__.system,
419 expansion. The three such methods are: __IPYTHON__.system,
404 .getoutput and .getoutputerror. These need to be documented in a
420 .getoutput and .getoutputerror. These need to be documented in a
405 'public API' section (to be written) of the manual.
421 'public API' section (to be written) of the manual.
406
422
407 2005-03-20 Fernando Perez <fperez@colorado.edu>
423 2005-03-20 Fernando Perez <fperez@colorado.edu>
408
424
409 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
425 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
410 for custom exception handling. This is quite powerful, and it
426 for custom exception handling. This is quite powerful, and it
411 allows for user-installable exception handlers which can trap
427 allows for user-installable exception handlers which can trap
412 custom exceptions at runtime and treat them separately from
428 custom exceptions at runtime and treat them separately from
413 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
429 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
414 Mantegazza <mantegazza-AT-ill.fr>.
430 Mantegazza <mantegazza-AT-ill.fr>.
415 (InteractiveShell.set_custom_completer): public API function to
431 (InteractiveShell.set_custom_completer): public API function to
416 add new completers at runtime.
432 add new completers at runtime.
417
433
418 2005-03-19 Fernando Perez <fperez@colorado.edu>
434 2005-03-19 Fernando Perez <fperez@colorado.edu>
419
435
420 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
436 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
421 allow objects which provide their docstrings via non-standard
437 allow objects which provide their docstrings via non-standard
422 mechanisms (like Pyro proxies) to still be inspected by ipython's
438 mechanisms (like Pyro proxies) to still be inspected by ipython's
423 ? system.
439 ? system.
424
440
425 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
441 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
426 automatic capture system. I tried quite hard to make it work
442 automatic capture system. I tried quite hard to make it work
427 reliably, and simply failed. I tried many combinations with the
443 reliably, and simply failed. I tried many combinations with the
428 subprocess module, but eventually nothing worked in all needed
444 subprocess module, but eventually nothing worked in all needed
429 cases (not blocking stdin for the child, duplicating stdout
445 cases (not blocking stdin for the child, duplicating stdout
430 without blocking, etc). The new %sc/%sx still do capture to these
446 without blocking, etc). The new %sc/%sx still do capture to these
431 magical list/string objects which make shell use much more
447 magical list/string objects which make shell use much more
432 conveninent, so not all is lost.
448 conveninent, so not all is lost.
433
449
434 XXX - FIX MANUAL for the change above!
450 XXX - FIX MANUAL for the change above!
435
451
436 (runsource): I copied code.py's runsource() into ipython to modify
452 (runsource): I copied code.py's runsource() into ipython to modify
437 it a bit. Now the code object and source to be executed are
453 it a bit. Now the code object and source to be executed are
438 stored in ipython. This makes this info accessible to third-party
454 stored in ipython. This makes this info accessible to third-party
439 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
455 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
440 Mantegazza <mantegazza-AT-ill.fr>.
456 Mantegazza <mantegazza-AT-ill.fr>.
441
457
442 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
458 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
443 history-search via readline (like C-p/C-n). I'd wanted this for a
459 history-search via readline (like C-p/C-n). I'd wanted this for a
444 long time, but only recently found out how to do it. For users
460 long time, but only recently found out how to do it. For users
445 who already have their ipythonrc files made and want this, just
461 who already have their ipythonrc files made and want this, just
446 add:
462 add:
447
463
448 readline_parse_and_bind "\e[A": history-search-backward
464 readline_parse_and_bind "\e[A": history-search-backward
449 readline_parse_and_bind "\e[B": history-search-forward
465 readline_parse_and_bind "\e[B": history-search-forward
450
466
451 2005-03-18 Fernando Perez <fperez@colorado.edu>
467 2005-03-18 Fernando Perez <fperez@colorado.edu>
452
468
453 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
469 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
454 LSString and SList classes which allow transparent conversions
470 LSString and SList classes which allow transparent conversions
455 between list mode and whitespace-separated string.
471 between list mode and whitespace-separated string.
456 (magic_r): Fix recursion problem in %r.
472 (magic_r): Fix recursion problem in %r.
457
473
458 * IPython/genutils.py (LSString): New class to be used for
474 * IPython/genutils.py (LSString): New class to be used for
459 automatic storage of the results of all alias/system calls in _o
475 automatic storage of the results of all alias/system calls in _o
460 and _e (stdout/err). These provide a .l/.list attribute which
476 and _e (stdout/err). These provide a .l/.list attribute which
461 does automatic splitting on newlines. This means that for most
477 does automatic splitting on newlines. This means that for most
462 uses, you'll never need to do capturing of output with %sc/%sx
478 uses, you'll never need to do capturing of output with %sc/%sx
463 anymore, since ipython keeps this always done for you. Note that
479 anymore, since ipython keeps this always done for you. Note that
464 only the LAST results are stored, the _o/e variables are
480 only the LAST results are stored, the _o/e variables are
465 overwritten on each call. If you need to save their contents
481 overwritten on each call. If you need to save their contents
466 further, simply bind them to any other name.
482 further, simply bind them to any other name.
467
483
468 2005-03-17 Fernando Perez <fperez@colorado.edu>
484 2005-03-17 Fernando Perez <fperez@colorado.edu>
469
485
470 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
486 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
471 prompt namespace handling.
487 prompt namespace handling.
472
488
473 2005-03-16 Fernando Perez <fperez@colorado.edu>
489 2005-03-16 Fernando Perez <fperez@colorado.edu>
474
490
475 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
491 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
476 classic prompts to be '>>> ' (final space was missing, and it
492 classic prompts to be '>>> ' (final space was missing, and it
477 trips the emacs python mode).
493 trips the emacs python mode).
478 (BasePrompt.__str__): Added safe support for dynamic prompt
494 (BasePrompt.__str__): Added safe support for dynamic prompt
479 strings. Now you can set your prompt string to be '$x', and the
495 strings. Now you can set your prompt string to be '$x', and the
480 value of x will be printed from your interactive namespace. The
496 value of x will be printed from your interactive namespace. The
481 interpolation syntax includes the full Itpl support, so
497 interpolation syntax includes the full Itpl support, so
482 ${foo()+x+bar()} is a valid prompt string now, and the function
498 ${foo()+x+bar()} is a valid prompt string now, and the function
483 calls will be made at runtime.
499 calls will be made at runtime.
484
500
485 2005-03-15 Fernando Perez <fperez@colorado.edu>
501 2005-03-15 Fernando Perez <fperez@colorado.edu>
486
502
487 * IPython/Magic.py (magic_history): renamed %hist to %history, to
503 * IPython/Magic.py (magic_history): renamed %hist to %history, to
488 avoid name clashes in pylab. %hist still works, it just forwards
504 avoid name clashes in pylab. %hist still works, it just forwards
489 the call to %history.
505 the call to %history.
490
506
491 2005-03-02 *** Released version 0.6.12
507 2005-03-02 *** Released version 0.6.12
492
508
493 2005-03-02 Fernando Perez <fperez@colorado.edu>
509 2005-03-02 Fernando Perez <fperez@colorado.edu>
494
510
495 * IPython/iplib.py (handle_magic): log magic calls properly as
511 * IPython/iplib.py (handle_magic): log magic calls properly as
496 ipmagic() function calls.
512 ipmagic() function calls.
497
513
498 * IPython/Magic.py (magic_time): Improved %time to support
514 * IPython/Magic.py (magic_time): Improved %time to support
499 statements and provide wall-clock as well as CPU time.
515 statements and provide wall-clock as well as CPU time.
500
516
501 2005-02-27 Fernando Perez <fperez@colorado.edu>
517 2005-02-27 Fernando Perez <fperez@colorado.edu>
502
518
503 * IPython/hooks.py: New hooks module, to expose user-modifiable
519 * IPython/hooks.py: New hooks module, to expose user-modifiable
504 IPython functionality in a clean manner. For now only the editor
520 IPython functionality in a clean manner. For now only the editor
505 hook is actually written, and other thigns which I intend to turn
521 hook is actually written, and other thigns which I intend to turn
506 into proper hooks aren't yet there. The display and prefilter
522 into proper hooks aren't yet there. The display and prefilter
507 stuff, for example, should be hooks. But at least now the
523 stuff, for example, should be hooks. But at least now the
508 framework is in place, and the rest can be moved here with more
524 framework is in place, and the rest can be moved here with more
509 time later. IPython had had a .hooks variable for a long time for
525 time later. IPython had had a .hooks variable for a long time for
510 this purpose, but I'd never actually used it for anything.
526 this purpose, but I'd never actually used it for anything.
511
527
512 2005-02-26 Fernando Perez <fperez@colorado.edu>
528 2005-02-26 Fernando Perez <fperez@colorado.edu>
513
529
514 * IPython/ipmaker.py (make_IPython): make the default ipython
530 * IPython/ipmaker.py (make_IPython): make the default ipython
515 directory be called _ipython under win32, to follow more the
531 directory be called _ipython under win32, to follow more the
516 naming peculiarities of that platform (where buggy software like
532 naming peculiarities of that platform (where buggy software like
517 Visual Sourcesafe breaks with .named directories). Reported by
533 Visual Sourcesafe breaks with .named directories). Reported by
518 Ville Vainio.
534 Ville Vainio.
519
535
520 2005-02-23 Fernando Perez <fperez@colorado.edu>
536 2005-02-23 Fernando Perez <fperez@colorado.edu>
521
537
522 * IPython/iplib.py (InteractiveShell.__init__): removed a few
538 * IPython/iplib.py (InteractiveShell.__init__): removed a few
523 auto_aliases for win32 which were causing problems. Users can
539 auto_aliases for win32 which were causing problems. Users can
524 define the ones they personally like.
540 define the ones they personally like.
525
541
526 2005-02-21 Fernando Perez <fperez@colorado.edu>
542 2005-02-21 Fernando Perez <fperez@colorado.edu>
527
543
528 * IPython/Magic.py (magic_time): new magic to time execution of
544 * IPython/Magic.py (magic_time): new magic to time execution of
529 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
545 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
530
546
531 2005-02-19 Fernando Perez <fperez@colorado.edu>
547 2005-02-19 Fernando Perez <fperez@colorado.edu>
532
548
533 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
549 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
534 into keys (for prompts, for example).
550 into keys (for prompts, for example).
535
551
536 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
552 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
537 prompts in case users want them. This introduces a small behavior
553 prompts in case users want them. This introduces a small behavior
538 change: ipython does not automatically add a space to all prompts
554 change: ipython does not automatically add a space to all prompts
539 anymore. To get the old prompts with a space, users should add it
555 anymore. To get the old prompts with a space, users should add it
540 manually to their ipythonrc file, so for example prompt_in1 should
556 manually to their ipythonrc file, so for example prompt_in1 should
541 now read 'In [\#]: ' instead of 'In [\#]:'.
557 now read 'In [\#]: ' instead of 'In [\#]:'.
542 (BasePrompt.__init__): New option prompts_pad_left (only in rc
558 (BasePrompt.__init__): New option prompts_pad_left (only in rc
543 file) to control left-padding of secondary prompts.
559 file) to control left-padding of secondary prompts.
544
560
545 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
561 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
546 the profiler can't be imported. Fix for Debian, which removed
562 the profiler can't be imported. Fix for Debian, which removed
547 profile.py because of License issues. I applied a slightly
563 profile.py because of License issues. I applied a slightly
548 modified version of the original Debian patch at
564 modified version of the original Debian patch at
549 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
565 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
550
566
551 2005-02-17 Fernando Perez <fperez@colorado.edu>
567 2005-02-17 Fernando Perez <fperez@colorado.edu>
552
568
553 * IPython/genutils.py (native_line_ends): Fix bug which would
569 * IPython/genutils.py (native_line_ends): Fix bug which would
554 cause improper line-ends under win32 b/c I was not opening files
570 cause improper line-ends under win32 b/c I was not opening files
555 in binary mode. Bug report and fix thanks to Ville.
571 in binary mode. Bug report and fix thanks to Ville.
556
572
557 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
573 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
558 trying to catch spurious foo[1] autocalls. My fix actually broke
574 trying to catch spurious foo[1] autocalls. My fix actually broke
559 ',/' autoquote/call with explicit escape (bad regexp).
575 ',/' autoquote/call with explicit escape (bad regexp).
560
576
561 2005-02-15 *** Released version 0.6.11
577 2005-02-15 *** Released version 0.6.11
562
578
563 2005-02-14 Fernando Perez <fperez@colorado.edu>
579 2005-02-14 Fernando Perez <fperez@colorado.edu>
564
580
565 * IPython/background_jobs.py: New background job management
581 * IPython/background_jobs.py: New background job management
566 subsystem. This is implemented via a new set of classes, and
582 subsystem. This is implemented via a new set of classes, and
567 IPython now provides a builtin 'jobs' object for background job
583 IPython now provides a builtin 'jobs' object for background job
568 execution. A convenience %bg magic serves as a lightweight
584 execution. A convenience %bg magic serves as a lightweight
569 frontend for starting the more common type of calls. This was
585 frontend for starting the more common type of calls. This was
570 inspired by discussions with B. Granger and the BackgroundCommand
586 inspired by discussions with B. Granger and the BackgroundCommand
571 class described in the book Python Scripting for Computational
587 class described in the book Python Scripting for Computational
572 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
588 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
573 (although ultimately no code from this text was used, as IPython's
589 (although ultimately no code from this text was used, as IPython's
574 system is a separate implementation).
590 system is a separate implementation).
575
591
576 * IPython/iplib.py (MagicCompleter.python_matches): add new option
592 * IPython/iplib.py (MagicCompleter.python_matches): add new option
577 to control the completion of single/double underscore names
593 to control the completion of single/double underscore names
578 separately. As documented in the example ipytonrc file, the
594 separately. As documented in the example ipytonrc file, the
579 readline_omit__names variable can now be set to 2, to omit even
595 readline_omit__names variable can now be set to 2, to omit even
580 single underscore names. Thanks to a patch by Brian Wong
596 single underscore names. Thanks to a patch by Brian Wong
581 <BrianWong-AT-AirgoNetworks.Com>.
597 <BrianWong-AT-AirgoNetworks.Com>.
582 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
598 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
583 be autocalled as foo([1]) if foo were callable. A problem for
599 be autocalled as foo([1]) if foo were callable. A problem for
584 things which are both callable and implement __getitem__.
600 things which are both callable and implement __getitem__.
585 (init_readline): Fix autoindentation for win32. Thanks to a patch
601 (init_readline): Fix autoindentation for win32. Thanks to a patch
586 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
602 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
587
603
588 2005-02-12 Fernando Perez <fperez@colorado.edu>
604 2005-02-12 Fernando Perez <fperez@colorado.edu>
589
605
590 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
606 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
591 which I had written long ago to sort out user error messages which
607 which I had written long ago to sort out user error messages which
592 may occur during startup. This seemed like a good idea initially,
608 may occur during startup. This seemed like a good idea initially,
593 but it has proven a disaster in retrospect. I don't want to
609 but it has proven a disaster in retrospect. I don't want to
594 change much code for now, so my fix is to set the internal 'debug'
610 change much code for now, so my fix is to set the internal 'debug'
595 flag to true everywhere, whose only job was precisely to control
611 flag to true everywhere, whose only job was precisely to control
596 this subsystem. This closes issue 28 (as well as avoiding all
612 this subsystem. This closes issue 28 (as well as avoiding all
597 sorts of strange hangups which occur from time to time).
613 sorts of strange hangups which occur from time to time).
598
614
599 2005-02-07 Fernando Perez <fperez@colorado.edu>
615 2005-02-07 Fernando Perez <fperez@colorado.edu>
600
616
601 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
617 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
602 previous call produced a syntax error.
618 previous call produced a syntax error.
603
619
604 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
620 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
605 classes without constructor.
621 classes without constructor.
606
622
607 2005-02-06 Fernando Perez <fperez@colorado.edu>
623 2005-02-06 Fernando Perez <fperez@colorado.edu>
608
624
609 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
625 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
610 completions with the results of each matcher, so we return results
626 completions with the results of each matcher, so we return results
611 to the user from all namespaces. This breaks with ipython
627 to the user from all namespaces. This breaks with ipython
612 tradition, but I think it's a nicer behavior. Now you get all
628 tradition, but I think it's a nicer behavior. Now you get all
613 possible completions listed, from all possible namespaces (python,
629 possible completions listed, from all possible namespaces (python,
614 filesystem, magics...) After a request by John Hunter
630 filesystem, magics...) After a request by John Hunter
615 <jdhunter-AT-nitace.bsd.uchicago.edu>.
631 <jdhunter-AT-nitace.bsd.uchicago.edu>.
616
632
617 2005-02-05 Fernando Perez <fperez@colorado.edu>
633 2005-02-05 Fernando Perez <fperez@colorado.edu>
618
634
619 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
635 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
620 the call had quote characters in it (the quotes were stripped).
636 the call had quote characters in it (the quotes were stripped).
621
637
622 2005-01-31 Fernando Perez <fperez@colorado.edu>
638 2005-01-31 Fernando Perez <fperez@colorado.edu>
623
639
624 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
640 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
625 Itpl.itpl() to make the code more robust against psyco
641 Itpl.itpl() to make the code more robust against psyco
626 optimizations.
642 optimizations.
627
643
628 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
644 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
629 of causing an exception. Quicker, cleaner.
645 of causing an exception. Quicker, cleaner.
630
646
631 2005-01-28 Fernando Perez <fperez@colorado.edu>
647 2005-01-28 Fernando Perez <fperez@colorado.edu>
632
648
633 * scripts/ipython_win_post_install.py (install): hardcode
649 * scripts/ipython_win_post_install.py (install): hardcode
634 sys.prefix+'python.exe' as the executable path. It turns out that
650 sys.prefix+'python.exe' as the executable path. It turns out that
635 during the post-installation run, sys.executable resolves to the
651 during the post-installation run, sys.executable resolves to the
636 name of the binary installer! I should report this as a distutils
652 name of the binary installer! I should report this as a distutils
637 bug, I think. I updated the .10 release with this tiny fix, to
653 bug, I think. I updated the .10 release with this tiny fix, to
638 avoid annoying the lists further.
654 avoid annoying the lists further.
639
655
640 2005-01-27 *** Released version 0.6.10
656 2005-01-27 *** Released version 0.6.10
641
657
642 2005-01-27 Fernando Perez <fperez@colorado.edu>
658 2005-01-27 Fernando Perez <fperez@colorado.edu>
643
659
644 * IPython/numutils.py (norm): Added 'inf' as optional name for
660 * IPython/numutils.py (norm): Added 'inf' as optional name for
645 L-infinity norm, included references to mathworld.com for vector
661 L-infinity norm, included references to mathworld.com for vector
646 norm definitions.
662 norm definitions.
647 (amin/amax): added amin/amax for array min/max. Similar to what
663 (amin/amax): added amin/amax for array min/max. Similar to what
648 pylab ships with after the recent reorganization of names.
664 pylab ships with after the recent reorganization of names.
649 (spike/spike_odd): removed deprecated spike/spike_odd functions.
665 (spike/spike_odd): removed deprecated spike/spike_odd functions.
650
666
651 * ipython.el: committed Alex's recent fixes and improvements.
667 * ipython.el: committed Alex's recent fixes and improvements.
652 Tested with python-mode from CVS, and it looks excellent. Since
668 Tested with python-mode from CVS, and it looks excellent. Since
653 python-mode hasn't released anything in a while, I'm temporarily
669 python-mode hasn't released anything in a while, I'm temporarily
654 putting a copy of today's CVS (v 4.70) of python-mode in:
670 putting a copy of today's CVS (v 4.70) of python-mode in:
655 http://ipython.scipy.org/tmp/python-mode.el
671 http://ipython.scipy.org/tmp/python-mode.el
656
672
657 * scripts/ipython_win_post_install.py (install): Win32 fix to use
673 * scripts/ipython_win_post_install.py (install): Win32 fix to use
658 sys.executable for the executable name, instead of assuming it's
674 sys.executable for the executable name, instead of assuming it's
659 called 'python.exe' (the post-installer would have produced broken
675 called 'python.exe' (the post-installer would have produced broken
660 setups on systems with a differently named python binary).
676 setups on systems with a differently named python binary).
661
677
662 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
678 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
663 references to os.linesep, to make the code more
679 references to os.linesep, to make the code more
664 platform-independent. This is also part of the win32 coloring
680 platform-independent. This is also part of the win32 coloring
665 fixes.
681 fixes.
666
682
667 * IPython/genutils.py (page_dumb): Remove attempts to chop long
683 * IPython/genutils.py (page_dumb): Remove attempts to chop long
668 lines, which actually cause coloring bugs because the length of
684 lines, which actually cause coloring bugs because the length of
669 the line is very difficult to correctly compute with embedded
685 the line is very difficult to correctly compute with embedded
670 escapes. This was the source of all the coloring problems under
686 escapes. This was the source of all the coloring problems under
671 Win32. I think that _finally_, Win32 users have a properly
687 Win32. I think that _finally_, Win32 users have a properly
672 working ipython in all respects. This would never have happened
688 working ipython in all respects. This would never have happened
673 if not for Gary Bishop and Viktor Ransmayr's great help and work.
689 if not for Gary Bishop and Viktor Ransmayr's great help and work.
674
690
675 2005-01-26 *** Released version 0.6.9
691 2005-01-26 *** Released version 0.6.9
676
692
677 2005-01-25 Fernando Perez <fperez@colorado.edu>
693 2005-01-25 Fernando Perez <fperez@colorado.edu>
678
694
679 * setup.py: finally, we have a true Windows installer, thanks to
695 * setup.py: finally, we have a true Windows installer, thanks to
680 the excellent work of Viktor Ransmayr
696 the excellent work of Viktor Ransmayr
681 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
697 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
682 Windows users. The setup routine is quite a bit cleaner thanks to
698 Windows users. The setup routine is quite a bit cleaner thanks to
683 this, and the post-install script uses the proper functions to
699 this, and the post-install script uses the proper functions to
684 allow a clean de-installation using the standard Windows Control
700 allow a clean de-installation using the standard Windows Control
685 Panel.
701 Panel.
686
702
687 * IPython/genutils.py (get_home_dir): changed to use the $HOME
703 * IPython/genutils.py (get_home_dir): changed to use the $HOME
688 environment variable under all OSes (including win32) if
704 environment variable under all OSes (including win32) if
689 available. This will give consistency to win32 users who have set
705 available. This will give consistency to win32 users who have set
690 this variable for any reason. If os.environ['HOME'] fails, the
706 this variable for any reason. If os.environ['HOME'] fails, the
691 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
707 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
692
708
693 2005-01-24 Fernando Perez <fperez@colorado.edu>
709 2005-01-24 Fernando Perez <fperez@colorado.edu>
694
710
695 * IPython/numutils.py (empty_like): add empty_like(), similar to
711 * IPython/numutils.py (empty_like): add empty_like(), similar to
696 zeros_like() but taking advantage of the new empty() Numeric routine.
712 zeros_like() but taking advantage of the new empty() Numeric routine.
697
713
698 2005-01-23 *** Released version 0.6.8
714 2005-01-23 *** Released version 0.6.8
699
715
700 2005-01-22 Fernando Perez <fperez@colorado.edu>
716 2005-01-22 Fernando Perez <fperez@colorado.edu>
701
717
702 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
718 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
703 automatic show() calls. After discussing things with JDH, it
719 automatic show() calls. After discussing things with JDH, it
704 turns out there are too many corner cases where this can go wrong.
720 turns out there are too many corner cases where this can go wrong.
705 It's best not to try to be 'too smart', and simply have ipython
721 It's best not to try to be 'too smart', and simply have ipython
706 reproduce as much as possible the default behavior of a normal
722 reproduce as much as possible the default behavior of a normal
707 python shell.
723 python shell.
708
724
709 * IPython/iplib.py (InteractiveShell.__init__): Modified the
725 * IPython/iplib.py (InteractiveShell.__init__): Modified the
710 line-splitting regexp and _prefilter() to avoid calling getattr()
726 line-splitting regexp and _prefilter() to avoid calling getattr()
711 on assignments. This closes
727 on assignments. This closes
712 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
728 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
713 readline uses getattr(), so a simple <TAB> keypress is still
729 readline uses getattr(), so a simple <TAB> keypress is still
714 enough to trigger getattr() calls on an object.
730 enough to trigger getattr() calls on an object.
715
731
716 2005-01-21 Fernando Perez <fperez@colorado.edu>
732 2005-01-21 Fernando Perez <fperez@colorado.edu>
717
733
718 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
734 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
719 docstring under pylab so it doesn't mask the original.
735 docstring under pylab so it doesn't mask the original.
720
736
721 2005-01-21 *** Released version 0.6.7
737 2005-01-21 *** Released version 0.6.7
722
738
723 2005-01-21 Fernando Perez <fperez@colorado.edu>
739 2005-01-21 Fernando Perez <fperez@colorado.edu>
724
740
725 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
741 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
726 signal handling for win32 users in multithreaded mode.
742 signal handling for win32 users in multithreaded mode.
727
743
728 2005-01-17 Fernando Perez <fperez@colorado.edu>
744 2005-01-17 Fernando Perez <fperez@colorado.edu>
729
745
730 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
746 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
731 instances with no __init__. After a crash report by Norbert Nemec
747 instances with no __init__. After a crash report by Norbert Nemec
732 <Norbert-AT-nemec-online.de>.
748 <Norbert-AT-nemec-online.de>.
733
749
734 2005-01-14 Fernando Perez <fperez@colorado.edu>
750 2005-01-14 Fernando Perez <fperez@colorado.edu>
735
751
736 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
752 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
737 names for verbose exceptions, when multiple dotted names and the
753 names for verbose exceptions, when multiple dotted names and the
738 'parent' object were present on the same line.
754 'parent' object were present on the same line.
739
755
740 2005-01-11 Fernando Perez <fperez@colorado.edu>
756 2005-01-11 Fernando Perez <fperez@colorado.edu>
741
757
742 * IPython/genutils.py (flag_calls): new utility to trap and flag
758 * IPython/genutils.py (flag_calls): new utility to trap and flag
743 calls in functions. I need it to clean up matplotlib support.
759 calls in functions. I need it to clean up matplotlib support.
744 Also removed some deprecated code in genutils.
760 Also removed some deprecated code in genutils.
745
761
746 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
762 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
747 that matplotlib scripts called with %run, which don't call show()
763 that matplotlib scripts called with %run, which don't call show()
748 themselves, still have their plotting windows open.
764 themselves, still have their plotting windows open.
749
765
750 2005-01-05 Fernando Perez <fperez@colorado.edu>
766 2005-01-05 Fernando Perez <fperez@colorado.edu>
751
767
752 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
768 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
753 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
769 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
754
770
755 2004-12-19 Fernando Perez <fperez@colorado.edu>
771 2004-12-19 Fernando Perez <fperez@colorado.edu>
756
772
757 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
773 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
758 parent_runcode, which was an eyesore. The same result can be
774 parent_runcode, which was an eyesore. The same result can be
759 obtained with Python's regular superclass mechanisms.
775 obtained with Python's regular superclass mechanisms.
760
776
761 2004-12-17 Fernando Perez <fperez@colorado.edu>
777 2004-12-17 Fernando Perez <fperez@colorado.edu>
762
778
763 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
779 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
764 reported by Prabhu.
780 reported by Prabhu.
765 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
781 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
766 sys.stderr) instead of explicitly calling sys.stderr. This helps
782 sys.stderr) instead of explicitly calling sys.stderr. This helps
767 maintain our I/O abstractions clean, for future GUI embeddings.
783 maintain our I/O abstractions clean, for future GUI embeddings.
768
784
769 * IPython/genutils.py (info): added new utility for sys.stderr
785 * IPython/genutils.py (info): added new utility for sys.stderr
770 unified info message handling (thin wrapper around warn()).
786 unified info message handling (thin wrapper around warn()).
771
787
772 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
788 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
773 composite (dotted) names on verbose exceptions.
789 composite (dotted) names on verbose exceptions.
774 (VerboseTB.nullrepr): harden against another kind of errors which
790 (VerboseTB.nullrepr): harden against another kind of errors which
775 Python's inspect module can trigger, and which were crashing
791 Python's inspect module can trigger, and which were crashing
776 IPython. Thanks to a report by Marco Lombardi
792 IPython. Thanks to a report by Marco Lombardi
777 <mlombard-AT-ma010192.hq.eso.org>.
793 <mlombard-AT-ma010192.hq.eso.org>.
778
794
779 2004-12-13 *** Released version 0.6.6
795 2004-12-13 *** Released version 0.6.6
780
796
781 2004-12-12 Fernando Perez <fperez@colorado.edu>
797 2004-12-12 Fernando Perez <fperez@colorado.edu>
782
798
783 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
799 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
784 generated by pygtk upon initialization if it was built without
800 generated by pygtk upon initialization if it was built without
785 threads (for matplotlib users). After a crash reported by
801 threads (for matplotlib users). After a crash reported by
786 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
802 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
787
803
788 * IPython/ipmaker.py (make_IPython): fix small bug in the
804 * IPython/ipmaker.py (make_IPython): fix small bug in the
789 import_some parameter for multiple imports.
805 import_some parameter for multiple imports.
790
806
791 * IPython/iplib.py (ipmagic): simplified the interface of
807 * IPython/iplib.py (ipmagic): simplified the interface of
792 ipmagic() to take a single string argument, just as it would be
808 ipmagic() to take a single string argument, just as it would be
793 typed at the IPython cmd line.
809 typed at the IPython cmd line.
794 (ipalias): Added new ipalias() with an interface identical to
810 (ipalias): Added new ipalias() with an interface identical to
795 ipmagic(). This completes exposing a pure python interface to the
811 ipmagic(). This completes exposing a pure python interface to the
796 alias and magic system, which can be used in loops or more complex
812 alias and magic system, which can be used in loops or more complex
797 code where IPython's automatic line mangling is not active.
813 code where IPython's automatic line mangling is not active.
798
814
799 * IPython/genutils.py (timing): changed interface of timing to
815 * IPython/genutils.py (timing): changed interface of timing to
800 simply run code once, which is the most common case. timings()
816 simply run code once, which is the most common case. timings()
801 remains unchanged, for the cases where you want multiple runs.
817 remains unchanged, for the cases where you want multiple runs.
802
818
803 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
819 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
804 bug where Python2.2 crashes with exec'ing code which does not end
820 bug where Python2.2 crashes with exec'ing code which does not end
805 in a single newline. Python 2.3 is OK, so I hadn't noticed this
821 in a single newline. Python 2.3 is OK, so I hadn't noticed this
806 before.
822 before.
807
823
808 2004-12-10 Fernando Perez <fperez@colorado.edu>
824 2004-12-10 Fernando Perez <fperez@colorado.edu>
809
825
810 * IPython/Magic.py (Magic.magic_prun): changed name of option from
826 * IPython/Magic.py (Magic.magic_prun): changed name of option from
811 -t to -T, to accomodate the new -t flag in %run (the %run and
827 -t to -T, to accomodate the new -t flag in %run (the %run and
812 %prun options are kind of intermixed, and it's not easy to change
828 %prun options are kind of intermixed, and it's not easy to change
813 this with the limitations of python's getopt).
829 this with the limitations of python's getopt).
814
830
815 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
831 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
816 the execution of scripts. It's not as fine-tuned as timeit.py,
832 the execution of scripts. It's not as fine-tuned as timeit.py,
817 but it works from inside ipython (and under 2.2, which lacks
833 but it works from inside ipython (and under 2.2, which lacks
818 timeit.py). Optionally a number of runs > 1 can be given for
834 timeit.py). Optionally a number of runs > 1 can be given for
819 timing very short-running code.
835 timing very short-running code.
820
836
821 * IPython/genutils.py (uniq_stable): new routine which returns a
837 * IPython/genutils.py (uniq_stable): new routine which returns a
822 list of unique elements in any iterable, but in stable order of
838 list of unique elements in any iterable, but in stable order of
823 appearance. I needed this for the ultraTB fixes, and it's a handy
839 appearance. I needed this for the ultraTB fixes, and it's a handy
824 utility.
840 utility.
825
841
826 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
842 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
827 dotted names in Verbose exceptions. This had been broken since
843 dotted names in Verbose exceptions. This had been broken since
828 the very start, now x.y will properly be printed in a Verbose
844 the very start, now x.y will properly be printed in a Verbose
829 traceback, instead of x being shown and y appearing always as an
845 traceback, instead of x being shown and y appearing always as an
830 'undefined global'. Getting this to work was a bit tricky,
846 'undefined global'. Getting this to work was a bit tricky,
831 because by default python tokenizers are stateless. Saved by
847 because by default python tokenizers are stateless. Saved by
832 python's ability to easily add a bit of state to an arbitrary
848 python's ability to easily add a bit of state to an arbitrary
833 function (without needing to build a full-blown callable object).
849 function (without needing to build a full-blown callable object).
834
850
835 Also big cleanup of this code, which had horrendous runtime
851 Also big cleanup of this code, which had horrendous runtime
836 lookups of zillions of attributes for colorization. Moved all
852 lookups of zillions of attributes for colorization. Moved all
837 this code into a few templates, which make it cleaner and quicker.
853 this code into a few templates, which make it cleaner and quicker.
838
854
839 Printout quality was also improved for Verbose exceptions: one
855 Printout quality was also improved for Verbose exceptions: one
840 variable per line, and memory addresses are printed (this can be
856 variable per line, and memory addresses are printed (this can be
841 quite handy in nasty debugging situations, which is what Verbose
857 quite handy in nasty debugging situations, which is what Verbose
842 is for).
858 is for).
843
859
844 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
860 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
845 the command line as scripts to be loaded by embedded instances.
861 the command line as scripts to be loaded by embedded instances.
846 Doing so has the potential for an infinite recursion if there are
862 Doing so has the potential for an infinite recursion if there are
847 exceptions thrown in the process. This fixes a strange crash
863 exceptions thrown in the process. This fixes a strange crash
848 reported by Philippe MULLER <muller-AT-irit.fr>.
864 reported by Philippe MULLER <muller-AT-irit.fr>.
849
865
850 2004-12-09 Fernando Perez <fperez@colorado.edu>
866 2004-12-09 Fernando Perez <fperez@colorado.edu>
851
867
852 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
868 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
853 to reflect new names in matplotlib, which now expose the
869 to reflect new names in matplotlib, which now expose the
854 matlab-compatible interface via a pylab module instead of the
870 matlab-compatible interface via a pylab module instead of the
855 'matlab' name. The new code is backwards compatible, so users of
871 'matlab' name. The new code is backwards compatible, so users of
856 all matplotlib versions are OK. Patch by J. Hunter.
872 all matplotlib versions are OK. Patch by J. Hunter.
857
873
858 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
874 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
859 of __init__ docstrings for instances (class docstrings are already
875 of __init__ docstrings for instances (class docstrings are already
860 automatically printed). Instances with customized docstrings
876 automatically printed). Instances with customized docstrings
861 (indep. of the class) are also recognized and all 3 separate
877 (indep. of the class) are also recognized and all 3 separate
862 docstrings are printed (instance, class, constructor). After some
878 docstrings are printed (instance, class, constructor). After some
863 comments/suggestions by J. Hunter.
879 comments/suggestions by J. Hunter.
864
880
865 2004-12-05 Fernando Perez <fperez@colorado.edu>
881 2004-12-05 Fernando Perez <fperez@colorado.edu>
866
882
867 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
883 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
868 warnings when tab-completion fails and triggers an exception.
884 warnings when tab-completion fails and triggers an exception.
869
885
870 2004-12-03 Fernando Perez <fperez@colorado.edu>
886 2004-12-03 Fernando Perez <fperez@colorado.edu>
871
887
872 * IPython/Magic.py (magic_prun): Fix bug where an exception would
888 * IPython/Magic.py (magic_prun): Fix bug where an exception would
873 be triggered when using 'run -p'. An incorrect option flag was
889 be triggered when using 'run -p'. An incorrect option flag was
874 being set ('d' instead of 'D').
890 being set ('d' instead of 'D').
875 (manpage): fix missing escaped \- sign.
891 (manpage): fix missing escaped \- sign.
876
892
877 2004-11-30 *** Released version 0.6.5
893 2004-11-30 *** Released version 0.6.5
878
894
879 2004-11-30 Fernando Perez <fperez@colorado.edu>
895 2004-11-30 Fernando Perez <fperez@colorado.edu>
880
896
881 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
897 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
882 setting with -d option.
898 setting with -d option.
883
899
884 * setup.py (docfiles): Fix problem where the doc glob I was using
900 * setup.py (docfiles): Fix problem where the doc glob I was using
885 was COMPLETELY BROKEN. It was giving the right files by pure
901 was COMPLETELY BROKEN. It was giving the right files by pure
886 accident, but failed once I tried to include ipython.el. Note:
902 accident, but failed once I tried to include ipython.el. Note:
887 glob() does NOT allow you to do exclusion on multiple endings!
903 glob() does NOT allow you to do exclusion on multiple endings!
888
904
889 2004-11-29 Fernando Perez <fperez@colorado.edu>
905 2004-11-29 Fernando Perez <fperez@colorado.edu>
890
906
891 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
907 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
892 the manpage as the source. Better formatting & consistency.
908 the manpage as the source. Better formatting & consistency.
893
909
894 * IPython/Magic.py (magic_run): Added new -d option, to run
910 * IPython/Magic.py (magic_run): Added new -d option, to run
895 scripts under the control of the python pdb debugger. Note that
911 scripts under the control of the python pdb debugger. Note that
896 this required changing the %prun option -d to -D, to avoid a clash
912 this required changing the %prun option -d to -D, to avoid a clash
897 (since %run must pass options to %prun, and getopt is too dumb to
913 (since %run must pass options to %prun, and getopt is too dumb to
898 handle options with string values with embedded spaces). Thanks
914 handle options with string values with embedded spaces). Thanks
899 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
915 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
900 (magic_who_ls): added type matching to %who and %whos, so that one
916 (magic_who_ls): added type matching to %who and %whos, so that one
901 can filter their output to only include variables of certain
917 can filter their output to only include variables of certain
902 types. Another suggestion by Matthew.
918 types. Another suggestion by Matthew.
903 (magic_whos): Added memory summaries in kb and Mb for arrays.
919 (magic_whos): Added memory summaries in kb and Mb for arrays.
904 (magic_who): Improve formatting (break lines every 9 vars).
920 (magic_who): Improve formatting (break lines every 9 vars).
905
921
906 2004-11-28 Fernando Perez <fperez@colorado.edu>
922 2004-11-28 Fernando Perez <fperez@colorado.edu>
907
923
908 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
924 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
909 cache when empty lines were present.
925 cache when empty lines were present.
910
926
911 2004-11-24 Fernando Perez <fperez@colorado.edu>
927 2004-11-24 Fernando Perez <fperez@colorado.edu>
912
928
913 * IPython/usage.py (__doc__): document the re-activated threading
929 * IPython/usage.py (__doc__): document the re-activated threading
914 options for WX and GTK.
930 options for WX and GTK.
915
931
916 2004-11-23 Fernando Perez <fperez@colorado.edu>
932 2004-11-23 Fernando Perez <fperez@colorado.edu>
917
933
918 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
934 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
919 the -wthread and -gthread options, along with a new -tk one to try
935 the -wthread and -gthread options, along with a new -tk one to try
920 and coordinate Tk threading with wx/gtk. The tk support is very
936 and coordinate Tk threading with wx/gtk. The tk support is very
921 platform dependent, since it seems to require Tcl and Tk to be
937 platform dependent, since it seems to require Tcl and Tk to be
922 built with threads (Fedora1/2 appears NOT to have it, but in
938 built with threads (Fedora1/2 appears NOT to have it, but in
923 Prabhu's Debian boxes it works OK). But even with some Tk
939 Prabhu's Debian boxes it works OK). But even with some Tk
924 limitations, this is a great improvement.
940 limitations, this is a great improvement.
925
941
926 * IPython/Prompts.py (prompt_specials_color): Added \t for time
942 * IPython/Prompts.py (prompt_specials_color): Added \t for time
927 info in user prompts. Patch by Prabhu.
943 info in user prompts. Patch by Prabhu.
928
944
929 2004-11-18 Fernando Perez <fperez@colorado.edu>
945 2004-11-18 Fernando Perez <fperez@colorado.edu>
930
946
931 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
947 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
932 EOFErrors and bail, to avoid infinite loops if a non-terminating
948 EOFErrors and bail, to avoid infinite loops if a non-terminating
933 file is fed into ipython. Patch submitted in issue 19 by user,
949 file is fed into ipython. Patch submitted in issue 19 by user,
934 many thanks.
950 many thanks.
935
951
936 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
952 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
937 autoquote/parens in continuation prompts, which can cause lots of
953 autoquote/parens in continuation prompts, which can cause lots of
938 problems. Closes roundup issue 20.
954 problems. Closes roundup issue 20.
939
955
940 2004-11-17 Fernando Perez <fperez@colorado.edu>
956 2004-11-17 Fernando Perez <fperez@colorado.edu>
941
957
942 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
958 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
943 reported as debian bug #280505. I'm not sure my local changelog
959 reported as debian bug #280505. I'm not sure my local changelog
944 entry has the proper debian format (Jack?).
960 entry has the proper debian format (Jack?).
945
961
946 2004-11-08 *** Released version 0.6.4
962 2004-11-08 *** Released version 0.6.4
947
963
948 2004-11-08 Fernando Perez <fperez@colorado.edu>
964 2004-11-08 Fernando Perez <fperez@colorado.edu>
949
965
950 * IPython/iplib.py (init_readline): Fix exit message for Windows
966 * IPython/iplib.py (init_readline): Fix exit message for Windows
951 when readline is active. Thanks to a report by Eric Jones
967 when readline is active. Thanks to a report by Eric Jones
952 <eric-AT-enthought.com>.
968 <eric-AT-enthought.com>.
953
969
954 2004-11-07 Fernando Perez <fperez@colorado.edu>
970 2004-11-07 Fernando Perez <fperez@colorado.edu>
955
971
956 * IPython/genutils.py (page): Add a trap for OSError exceptions,
972 * IPython/genutils.py (page): Add a trap for OSError exceptions,
957 sometimes seen by win2k/cygwin users.
973 sometimes seen by win2k/cygwin users.
958
974
959 2004-11-06 Fernando Perez <fperez@colorado.edu>
975 2004-11-06 Fernando Perez <fperez@colorado.edu>
960
976
961 * IPython/iplib.py (interact): Change the handling of %Exit from
977 * IPython/iplib.py (interact): Change the handling of %Exit from
962 trying to propagate a SystemExit to an internal ipython flag.
978 trying to propagate a SystemExit to an internal ipython flag.
963 This is less elegant than using Python's exception mechanism, but
979 This is less elegant than using Python's exception mechanism, but
964 I can't get that to work reliably with threads, so under -pylab
980 I can't get that to work reliably with threads, so under -pylab
965 %Exit was hanging IPython. Cross-thread exception handling is
981 %Exit was hanging IPython. Cross-thread exception handling is
966 really a bitch. Thaks to a bug report by Stephen Walton
982 really a bitch. Thaks to a bug report by Stephen Walton
967 <stephen.walton-AT-csun.edu>.
983 <stephen.walton-AT-csun.edu>.
968
984
969 2004-11-04 Fernando Perez <fperez@colorado.edu>
985 2004-11-04 Fernando Perez <fperez@colorado.edu>
970
986
971 * IPython/iplib.py (raw_input_original): store a pointer to the
987 * IPython/iplib.py (raw_input_original): store a pointer to the
972 true raw_input to harden against code which can modify it
988 true raw_input to harden against code which can modify it
973 (wx.py.PyShell does this and would otherwise crash ipython).
989 (wx.py.PyShell does this and would otherwise crash ipython).
974 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
990 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
975
991
976 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
992 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
977 Ctrl-C problem, which does not mess up the input line.
993 Ctrl-C problem, which does not mess up the input line.
978
994
979 2004-11-03 Fernando Perez <fperez@colorado.edu>
995 2004-11-03 Fernando Perez <fperez@colorado.edu>
980
996
981 * IPython/Release.py: Changed licensing to BSD, in all files.
997 * IPython/Release.py: Changed licensing to BSD, in all files.
982 (name): lowercase name for tarball/RPM release.
998 (name): lowercase name for tarball/RPM release.
983
999
984 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1000 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
985 use throughout ipython.
1001 use throughout ipython.
986
1002
987 * IPython/Magic.py (Magic._ofind): Switch to using the new
1003 * IPython/Magic.py (Magic._ofind): Switch to using the new
988 OInspect.getdoc() function.
1004 OInspect.getdoc() function.
989
1005
990 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1006 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
991 of the line currently being canceled via Ctrl-C. It's extremely
1007 of the line currently being canceled via Ctrl-C. It's extremely
992 ugly, but I don't know how to do it better (the problem is one of
1008 ugly, but I don't know how to do it better (the problem is one of
993 handling cross-thread exceptions).
1009 handling cross-thread exceptions).
994
1010
995 2004-10-28 Fernando Perez <fperez@colorado.edu>
1011 2004-10-28 Fernando Perez <fperez@colorado.edu>
996
1012
997 * IPython/Shell.py (signal_handler): add signal handlers to trap
1013 * IPython/Shell.py (signal_handler): add signal handlers to trap
998 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1014 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
999 report by Francesc Alted.
1015 report by Francesc Alted.
1000
1016
1001 2004-10-21 Fernando Perez <fperez@colorado.edu>
1017 2004-10-21 Fernando Perez <fperez@colorado.edu>
1002
1018
1003 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1019 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1004 to % for pysh syntax extensions.
1020 to % for pysh syntax extensions.
1005
1021
1006 2004-10-09 Fernando Perez <fperez@colorado.edu>
1022 2004-10-09 Fernando Perez <fperez@colorado.edu>
1007
1023
1008 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1024 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1009 arrays to print a more useful summary, without calling str(arr).
1025 arrays to print a more useful summary, without calling str(arr).
1010 This avoids the problem of extremely lengthy computations which
1026 This avoids the problem of extremely lengthy computations which
1011 occur if arr is large, and appear to the user as a system lockup
1027 occur if arr is large, and appear to the user as a system lockup
1012 with 100% cpu activity. After a suggestion by Kristian Sandberg
1028 with 100% cpu activity. After a suggestion by Kristian Sandberg
1013 <Kristian.Sandberg@colorado.edu>.
1029 <Kristian.Sandberg@colorado.edu>.
1014 (Magic.__init__): fix bug in global magic escapes not being
1030 (Magic.__init__): fix bug in global magic escapes not being
1015 correctly set.
1031 correctly set.
1016
1032
1017 2004-10-08 Fernando Perez <fperez@colorado.edu>
1033 2004-10-08 Fernando Perez <fperez@colorado.edu>
1018
1034
1019 * IPython/Magic.py (__license__): change to absolute imports of
1035 * IPython/Magic.py (__license__): change to absolute imports of
1020 ipython's own internal packages, to start adapting to the absolute
1036 ipython's own internal packages, to start adapting to the absolute
1021 import requirement of PEP-328.
1037 import requirement of PEP-328.
1022
1038
1023 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1039 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1024 files, and standardize author/license marks through the Release
1040 files, and standardize author/license marks through the Release
1025 module instead of having per/file stuff (except for files with
1041 module instead of having per/file stuff (except for files with
1026 particular licenses, like the MIT/PSF-licensed codes).
1042 particular licenses, like the MIT/PSF-licensed codes).
1027
1043
1028 * IPython/Debugger.py: remove dead code for python 2.1
1044 * IPython/Debugger.py: remove dead code for python 2.1
1029
1045
1030 2004-10-04 Fernando Perez <fperez@colorado.edu>
1046 2004-10-04 Fernando Perez <fperez@colorado.edu>
1031
1047
1032 * IPython/iplib.py (ipmagic): New function for accessing magics
1048 * IPython/iplib.py (ipmagic): New function for accessing magics
1033 via a normal python function call.
1049 via a normal python function call.
1034
1050
1035 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1051 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1036 from '@' to '%', to accomodate the new @decorator syntax of python
1052 from '@' to '%', to accomodate the new @decorator syntax of python
1037 2.4.
1053 2.4.
1038
1054
1039 2004-09-29 Fernando Perez <fperez@colorado.edu>
1055 2004-09-29 Fernando Perez <fperez@colorado.edu>
1040
1056
1041 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1057 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1042 matplotlib.use to prevent running scripts which try to switch
1058 matplotlib.use to prevent running scripts which try to switch
1043 interactive backends from within ipython. This will just crash
1059 interactive backends from within ipython. This will just crash
1044 the python interpreter, so we can't allow it (but a detailed error
1060 the python interpreter, so we can't allow it (but a detailed error
1045 is given to the user).
1061 is given to the user).
1046
1062
1047 2004-09-28 Fernando Perez <fperez@colorado.edu>
1063 2004-09-28 Fernando Perez <fperez@colorado.edu>
1048
1064
1049 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1065 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1050 matplotlib-related fixes so that using @run with non-matplotlib
1066 matplotlib-related fixes so that using @run with non-matplotlib
1051 scripts doesn't pop up spurious plot windows. This requires
1067 scripts doesn't pop up spurious plot windows. This requires
1052 matplotlib >= 0.63, where I had to make some changes as well.
1068 matplotlib >= 0.63, where I had to make some changes as well.
1053
1069
1054 * IPython/ipmaker.py (make_IPython): update version requirement to
1070 * IPython/ipmaker.py (make_IPython): update version requirement to
1055 python 2.2.
1071 python 2.2.
1056
1072
1057 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1073 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1058 banner arg for embedded customization.
1074 banner arg for embedded customization.
1059
1075
1060 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1076 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1061 explicit uses of __IP as the IPython's instance name. Now things
1077 explicit uses of __IP as the IPython's instance name. Now things
1062 are properly handled via the shell.name value. The actual code
1078 are properly handled via the shell.name value. The actual code
1063 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1079 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1064 is much better than before. I'll clean things completely when the
1080 is much better than before. I'll clean things completely when the
1065 magic stuff gets a real overhaul.
1081 magic stuff gets a real overhaul.
1066
1082
1067 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1083 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1068 minor changes to debian dir.
1084 minor changes to debian dir.
1069
1085
1070 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1086 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1071 pointer to the shell itself in the interactive namespace even when
1087 pointer to the shell itself in the interactive namespace even when
1072 a user-supplied dict is provided. This is needed for embedding
1088 a user-supplied dict is provided. This is needed for embedding
1073 purposes (found by tests with Michel Sanner).
1089 purposes (found by tests with Michel Sanner).
1074
1090
1075 2004-09-27 Fernando Perez <fperez@colorado.edu>
1091 2004-09-27 Fernando Perez <fperez@colorado.edu>
1076
1092
1077 * IPython/UserConfig/ipythonrc: remove []{} from
1093 * IPython/UserConfig/ipythonrc: remove []{} from
1078 readline_remove_delims, so that things like [modname.<TAB> do
1094 readline_remove_delims, so that things like [modname.<TAB> do
1079 proper completion. This disables [].TAB, but that's a less common
1095 proper completion. This disables [].TAB, but that's a less common
1080 case than module names in list comprehensions, for example.
1096 case than module names in list comprehensions, for example.
1081 Thanks to a report by Andrea Riciputi.
1097 Thanks to a report by Andrea Riciputi.
1082
1098
1083 2004-09-09 Fernando Perez <fperez@colorado.edu>
1099 2004-09-09 Fernando Perez <fperez@colorado.edu>
1084
1100
1085 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1101 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1086 blocking problems in win32 and osx. Fix by John.
1102 blocking problems in win32 and osx. Fix by John.
1087
1103
1088 2004-09-08 Fernando Perez <fperez@colorado.edu>
1104 2004-09-08 Fernando Perez <fperez@colorado.edu>
1089
1105
1090 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1106 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1091 for Win32 and OSX. Fix by John Hunter.
1107 for Win32 and OSX. Fix by John Hunter.
1092
1108
1093 2004-08-30 *** Released version 0.6.3
1109 2004-08-30 *** Released version 0.6.3
1094
1110
1095 2004-08-30 Fernando Perez <fperez@colorado.edu>
1111 2004-08-30 Fernando Perez <fperez@colorado.edu>
1096
1112
1097 * setup.py (isfile): Add manpages to list of dependent files to be
1113 * setup.py (isfile): Add manpages to list of dependent files to be
1098 updated.
1114 updated.
1099
1115
1100 2004-08-27 Fernando Perez <fperez@colorado.edu>
1116 2004-08-27 Fernando Perez <fperez@colorado.edu>
1101
1117
1102 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1118 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1103 for now. They don't really work with standalone WX/GTK code
1119 for now. They don't really work with standalone WX/GTK code
1104 (though matplotlib IS working fine with both of those backends).
1120 (though matplotlib IS working fine with both of those backends).
1105 This will neeed much more testing. I disabled most things with
1121 This will neeed much more testing. I disabled most things with
1106 comments, so turning it back on later should be pretty easy.
1122 comments, so turning it back on later should be pretty easy.
1107
1123
1108 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1124 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1109 autocalling of expressions like r'foo', by modifying the line
1125 autocalling of expressions like r'foo', by modifying the line
1110 split regexp. Closes
1126 split regexp. Closes
1111 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1127 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1112 Riley <ipythonbugs-AT-sabi.net>.
1128 Riley <ipythonbugs-AT-sabi.net>.
1113 (InteractiveShell.mainloop): honor --nobanner with banner
1129 (InteractiveShell.mainloop): honor --nobanner with banner
1114 extensions.
1130 extensions.
1115
1131
1116 * IPython/Shell.py: Significant refactoring of all classes, so
1132 * IPython/Shell.py: Significant refactoring of all classes, so
1117 that we can really support ALL matplotlib backends and threading
1133 that we can really support ALL matplotlib backends and threading
1118 models (John spotted a bug with Tk which required this). Now we
1134 models (John spotted a bug with Tk which required this). Now we
1119 should support single-threaded, WX-threads and GTK-threads, both
1135 should support single-threaded, WX-threads and GTK-threads, both
1120 for generic code and for matplotlib.
1136 for generic code and for matplotlib.
1121
1137
1122 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1138 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1123 -pylab, to simplify things for users. Will also remove the pylab
1139 -pylab, to simplify things for users. Will also remove the pylab
1124 profile, since now all of matplotlib configuration is directly
1140 profile, since now all of matplotlib configuration is directly
1125 handled here. This also reduces startup time.
1141 handled here. This also reduces startup time.
1126
1142
1127 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1143 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1128 shell wasn't being correctly called. Also in IPShellWX.
1144 shell wasn't being correctly called. Also in IPShellWX.
1129
1145
1130 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1146 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1131 fine-tune banner.
1147 fine-tune banner.
1132
1148
1133 * IPython/numutils.py (spike): Deprecate these spike functions,
1149 * IPython/numutils.py (spike): Deprecate these spike functions,
1134 delete (long deprecated) gnuplot_exec handler.
1150 delete (long deprecated) gnuplot_exec handler.
1135
1151
1136 2004-08-26 Fernando Perez <fperez@colorado.edu>
1152 2004-08-26 Fernando Perez <fperez@colorado.edu>
1137
1153
1138 * ipython.1: Update for threading options, plus some others which
1154 * ipython.1: Update for threading options, plus some others which
1139 were missing.
1155 were missing.
1140
1156
1141 * IPython/ipmaker.py (__call__): Added -wthread option for
1157 * IPython/ipmaker.py (__call__): Added -wthread option for
1142 wxpython thread handling. Make sure threading options are only
1158 wxpython thread handling. Make sure threading options are only
1143 valid at the command line.
1159 valid at the command line.
1144
1160
1145 * scripts/ipython: moved shell selection into a factory function
1161 * scripts/ipython: moved shell selection into a factory function
1146 in Shell.py, to keep the starter script to a minimum.
1162 in Shell.py, to keep the starter script to a minimum.
1147
1163
1148 2004-08-25 Fernando Perez <fperez@colorado.edu>
1164 2004-08-25 Fernando Perez <fperez@colorado.edu>
1149
1165
1150 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1166 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1151 John. Along with some recent changes he made to matplotlib, the
1167 John. Along with some recent changes he made to matplotlib, the
1152 next versions of both systems should work very well together.
1168 next versions of both systems should work very well together.
1153
1169
1154 2004-08-24 Fernando Perez <fperez@colorado.edu>
1170 2004-08-24 Fernando Perez <fperez@colorado.edu>
1155
1171
1156 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1172 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1157 tried to switch the profiling to using hotshot, but I'm getting
1173 tried to switch the profiling to using hotshot, but I'm getting
1158 strange errors from prof.runctx() there. I may be misreading the
1174 strange errors from prof.runctx() there. I may be misreading the
1159 docs, but it looks weird. For now the profiling code will
1175 docs, but it looks weird. For now the profiling code will
1160 continue to use the standard profiler.
1176 continue to use the standard profiler.
1161
1177
1162 2004-08-23 Fernando Perez <fperez@colorado.edu>
1178 2004-08-23 Fernando Perez <fperez@colorado.edu>
1163
1179
1164 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1180 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1165 threaded shell, by John Hunter. It's not quite ready yet, but
1181 threaded shell, by John Hunter. It's not quite ready yet, but
1166 close.
1182 close.
1167
1183
1168 2004-08-22 Fernando Perez <fperez@colorado.edu>
1184 2004-08-22 Fernando Perez <fperez@colorado.edu>
1169
1185
1170 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1186 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1171 in Magic and ultraTB.
1187 in Magic and ultraTB.
1172
1188
1173 * ipython.1: document threading options in manpage.
1189 * ipython.1: document threading options in manpage.
1174
1190
1175 * scripts/ipython: Changed name of -thread option to -gthread,
1191 * scripts/ipython: Changed name of -thread option to -gthread,
1176 since this is GTK specific. I want to leave the door open for a
1192 since this is GTK specific. I want to leave the door open for a
1177 -wthread option for WX, which will most likely be necessary. This
1193 -wthread option for WX, which will most likely be necessary. This
1178 change affects usage and ipmaker as well.
1194 change affects usage and ipmaker as well.
1179
1195
1180 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1196 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1181 handle the matplotlib shell issues. Code by John Hunter
1197 handle the matplotlib shell issues. Code by John Hunter
1182 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1198 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1183 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1199 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1184 broken (and disabled for end users) for now, but it puts the
1200 broken (and disabled for end users) for now, but it puts the
1185 infrastructure in place.
1201 infrastructure in place.
1186
1202
1187 2004-08-21 Fernando Perez <fperez@colorado.edu>
1203 2004-08-21 Fernando Perez <fperez@colorado.edu>
1188
1204
1189 * ipythonrc-pylab: Add matplotlib support.
1205 * ipythonrc-pylab: Add matplotlib support.
1190
1206
1191 * matplotlib_config.py: new files for matplotlib support, part of
1207 * matplotlib_config.py: new files for matplotlib support, part of
1192 the pylab profile.
1208 the pylab profile.
1193
1209
1194 * IPython/usage.py (__doc__): documented the threading options.
1210 * IPython/usage.py (__doc__): documented the threading options.
1195
1211
1196 2004-08-20 Fernando Perez <fperez@colorado.edu>
1212 2004-08-20 Fernando Perez <fperez@colorado.edu>
1197
1213
1198 * ipython: Modified the main calling routine to handle the -thread
1214 * ipython: Modified the main calling routine to handle the -thread
1199 and -mpthread options. This needs to be done as a top-level hack,
1215 and -mpthread options. This needs to be done as a top-level hack,
1200 because it determines which class to instantiate for IPython
1216 because it determines which class to instantiate for IPython
1201 itself.
1217 itself.
1202
1218
1203 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1219 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1204 classes to support multithreaded GTK operation without blocking,
1220 classes to support multithreaded GTK operation without blocking,
1205 and matplotlib with all backends. This is a lot of still very
1221 and matplotlib with all backends. This is a lot of still very
1206 experimental code, and threads are tricky. So it may still have a
1222 experimental code, and threads are tricky. So it may still have a
1207 few rough edges... This code owes a lot to
1223 few rough edges... This code owes a lot to
1208 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1224 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1209 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1225 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1210 to John Hunter for all the matplotlib work.
1226 to John Hunter for all the matplotlib work.
1211
1227
1212 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1228 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1213 options for gtk thread and matplotlib support.
1229 options for gtk thread and matplotlib support.
1214
1230
1215 2004-08-16 Fernando Perez <fperez@colorado.edu>
1231 2004-08-16 Fernando Perez <fperez@colorado.edu>
1216
1232
1217 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1233 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1218 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1234 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1219 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1235 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1220
1236
1221 2004-08-11 Fernando Perez <fperez@colorado.edu>
1237 2004-08-11 Fernando Perez <fperez@colorado.edu>
1222
1238
1223 * setup.py (isfile): Fix build so documentation gets updated for
1239 * setup.py (isfile): Fix build so documentation gets updated for
1224 rpms (it was only done for .tgz builds).
1240 rpms (it was only done for .tgz builds).
1225
1241
1226 2004-08-10 Fernando Perez <fperez@colorado.edu>
1242 2004-08-10 Fernando Perez <fperez@colorado.edu>
1227
1243
1228 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1244 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1229
1245
1230 * iplib.py : Silence syntax error exceptions in tab-completion.
1246 * iplib.py : Silence syntax error exceptions in tab-completion.
1231
1247
1232 2004-08-05 Fernando Perez <fperez@colorado.edu>
1248 2004-08-05 Fernando Perez <fperez@colorado.edu>
1233
1249
1234 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1250 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1235 'color off' mark for continuation prompts. This was causing long
1251 'color off' mark for continuation prompts. This was causing long
1236 continuation lines to mis-wrap.
1252 continuation lines to mis-wrap.
1237
1253
1238 2004-08-01 Fernando Perez <fperez@colorado.edu>
1254 2004-08-01 Fernando Perez <fperez@colorado.edu>
1239
1255
1240 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1256 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1241 for building ipython to be a parameter. All this is necessary
1257 for building ipython to be a parameter. All this is necessary
1242 right now to have a multithreaded version, but this insane
1258 right now to have a multithreaded version, but this insane
1243 non-design will be cleaned up soon. For now, it's a hack that
1259 non-design will be cleaned up soon. For now, it's a hack that
1244 works.
1260 works.
1245
1261
1246 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1262 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1247 args in various places. No bugs so far, but it's a dangerous
1263 args in various places. No bugs so far, but it's a dangerous
1248 practice.
1264 practice.
1249
1265
1250 2004-07-31 Fernando Perez <fperez@colorado.edu>
1266 2004-07-31 Fernando Perez <fperez@colorado.edu>
1251
1267
1252 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1268 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1253 fix completion of files with dots in their names under most
1269 fix completion of files with dots in their names under most
1254 profiles (pysh was OK because the completion order is different).
1270 profiles (pysh was OK because the completion order is different).
1255
1271
1256 2004-07-27 Fernando Perez <fperez@colorado.edu>
1272 2004-07-27 Fernando Perez <fperez@colorado.edu>
1257
1273
1258 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1274 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1259 keywords manually, b/c the one in keyword.py was removed in python
1275 keywords manually, b/c the one in keyword.py was removed in python
1260 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1276 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1261 This is NOT a bug under python 2.3 and earlier.
1277 This is NOT a bug under python 2.3 and earlier.
1262
1278
1263 2004-07-26 Fernando Perez <fperez@colorado.edu>
1279 2004-07-26 Fernando Perez <fperez@colorado.edu>
1264
1280
1265 * IPython/ultraTB.py (VerboseTB.text): Add another
1281 * IPython/ultraTB.py (VerboseTB.text): Add another
1266 linecache.checkcache() call to try to prevent inspect.py from
1282 linecache.checkcache() call to try to prevent inspect.py from
1267 crashing under python 2.3. I think this fixes
1283 crashing under python 2.3. I think this fixes
1268 http://www.scipy.net/roundup/ipython/issue17.
1284 http://www.scipy.net/roundup/ipython/issue17.
1269
1285
1270 2004-07-26 *** Released version 0.6.2
1286 2004-07-26 *** Released version 0.6.2
1271
1287
1272 2004-07-26 Fernando Perez <fperez@colorado.edu>
1288 2004-07-26 Fernando Perez <fperez@colorado.edu>
1273
1289
1274 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1290 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1275 fail for any number.
1291 fail for any number.
1276 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1292 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1277 empty bookmarks.
1293 empty bookmarks.
1278
1294
1279 2004-07-26 *** Released version 0.6.1
1295 2004-07-26 *** Released version 0.6.1
1280
1296
1281 2004-07-26 Fernando Perez <fperez@colorado.edu>
1297 2004-07-26 Fernando Perez <fperez@colorado.edu>
1282
1298
1283 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1299 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1284
1300
1285 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1301 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1286 escaping '()[]{}' in filenames.
1302 escaping '()[]{}' in filenames.
1287
1303
1288 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1304 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1289 Python 2.2 users who lack a proper shlex.split.
1305 Python 2.2 users who lack a proper shlex.split.
1290
1306
1291 2004-07-19 Fernando Perez <fperez@colorado.edu>
1307 2004-07-19 Fernando Perez <fperez@colorado.edu>
1292
1308
1293 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1309 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1294 for reading readline's init file. I follow the normal chain:
1310 for reading readline's init file. I follow the normal chain:
1295 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1311 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1296 report by Mike Heeter. This closes
1312 report by Mike Heeter. This closes
1297 http://www.scipy.net/roundup/ipython/issue16.
1313 http://www.scipy.net/roundup/ipython/issue16.
1298
1314
1299 2004-07-18 Fernando Perez <fperez@colorado.edu>
1315 2004-07-18 Fernando Perez <fperez@colorado.edu>
1300
1316
1301 * IPython/iplib.py (__init__): Add better handling of '\' under
1317 * IPython/iplib.py (__init__): Add better handling of '\' under
1302 Win32 for filenames. After a patch by Ville.
1318 Win32 for filenames. After a patch by Ville.
1303
1319
1304 2004-07-17 Fernando Perez <fperez@colorado.edu>
1320 2004-07-17 Fernando Perez <fperez@colorado.edu>
1305
1321
1306 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1322 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1307 autocalling would be triggered for 'foo is bar' if foo is
1323 autocalling would be triggered for 'foo is bar' if foo is
1308 callable. I also cleaned up the autocall detection code to use a
1324 callable. I also cleaned up the autocall detection code to use a
1309 regexp, which is faster. Bug reported by Alexander Schmolck.
1325 regexp, which is faster. Bug reported by Alexander Schmolck.
1310
1326
1311 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1327 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1312 '?' in them would confuse the help system. Reported by Alex
1328 '?' in them would confuse the help system. Reported by Alex
1313 Schmolck.
1329 Schmolck.
1314
1330
1315 2004-07-16 Fernando Perez <fperez@colorado.edu>
1331 2004-07-16 Fernando Perez <fperez@colorado.edu>
1316
1332
1317 * IPython/GnuplotInteractive.py (__all__): added plot2.
1333 * IPython/GnuplotInteractive.py (__all__): added plot2.
1318
1334
1319 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1335 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1320 plotting dictionaries, lists or tuples of 1d arrays.
1336 plotting dictionaries, lists or tuples of 1d arrays.
1321
1337
1322 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1338 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1323 optimizations.
1339 optimizations.
1324
1340
1325 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1341 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1326 the information which was there from Janko's original IPP code:
1342 the information which was there from Janko's original IPP code:
1327
1343
1328 03.05.99 20:53 porto.ifm.uni-kiel.de
1344 03.05.99 20:53 porto.ifm.uni-kiel.de
1329 --Started changelog.
1345 --Started changelog.
1330 --make clear do what it say it does
1346 --make clear do what it say it does
1331 --added pretty output of lines from inputcache
1347 --added pretty output of lines from inputcache
1332 --Made Logger a mixin class, simplifies handling of switches
1348 --Made Logger a mixin class, simplifies handling of switches
1333 --Added own completer class. .string<TAB> expands to last history
1349 --Added own completer class. .string<TAB> expands to last history
1334 line which starts with string. The new expansion is also present
1350 line which starts with string. The new expansion is also present
1335 with Ctrl-r from the readline library. But this shows, who this
1351 with Ctrl-r from the readline library. But this shows, who this
1336 can be done for other cases.
1352 can be done for other cases.
1337 --Added convention that all shell functions should accept a
1353 --Added convention that all shell functions should accept a
1338 parameter_string This opens the door for different behaviour for
1354 parameter_string This opens the door for different behaviour for
1339 each function. @cd is a good example of this.
1355 each function. @cd is a good example of this.
1340
1356
1341 04.05.99 12:12 porto.ifm.uni-kiel.de
1357 04.05.99 12:12 porto.ifm.uni-kiel.de
1342 --added logfile rotation
1358 --added logfile rotation
1343 --added new mainloop method which freezes first the namespace
1359 --added new mainloop method which freezes first the namespace
1344
1360
1345 07.05.99 21:24 porto.ifm.uni-kiel.de
1361 07.05.99 21:24 porto.ifm.uni-kiel.de
1346 --added the docreader classes. Now there is a help system.
1362 --added the docreader classes. Now there is a help system.
1347 -This is only a first try. Currently it's not easy to put new
1363 -This is only a first try. Currently it's not easy to put new
1348 stuff in the indices. But this is the way to go. Info would be
1364 stuff in the indices. But this is the way to go. Info would be
1349 better, but HTML is every where and not everybody has an info
1365 better, but HTML is every where and not everybody has an info
1350 system installed and it's not so easy to change html-docs to info.
1366 system installed and it's not so easy to change html-docs to info.
1351 --added global logfile option
1367 --added global logfile option
1352 --there is now a hook for object inspection method pinfo needs to
1368 --there is now a hook for object inspection method pinfo needs to
1353 be provided for this. Can be reached by two '??'.
1369 be provided for this. Can be reached by two '??'.
1354
1370
1355 08.05.99 20:51 porto.ifm.uni-kiel.de
1371 08.05.99 20:51 porto.ifm.uni-kiel.de
1356 --added a README
1372 --added a README
1357 --bug in rc file. Something has changed so functions in the rc
1373 --bug in rc file. Something has changed so functions in the rc
1358 file need to reference the shell and not self. Not clear if it's a
1374 file need to reference the shell and not self. Not clear if it's a
1359 bug or feature.
1375 bug or feature.
1360 --changed rc file for new behavior
1376 --changed rc file for new behavior
1361
1377
1362 2004-07-15 Fernando Perez <fperez@colorado.edu>
1378 2004-07-15 Fernando Perez <fperez@colorado.edu>
1363
1379
1364 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1380 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1365 cache was falling out of sync in bizarre manners when multi-line
1381 cache was falling out of sync in bizarre manners when multi-line
1366 input was present. Minor optimizations and cleanup.
1382 input was present. Minor optimizations and cleanup.
1367
1383
1368 (Logger): Remove old Changelog info for cleanup. This is the
1384 (Logger): Remove old Changelog info for cleanup. This is the
1369 information which was there from Janko's original code:
1385 information which was there from Janko's original code:
1370
1386
1371 Changes to Logger: - made the default log filename a parameter
1387 Changes to Logger: - made the default log filename a parameter
1372
1388
1373 - put a check for lines beginning with !@? in log(). Needed
1389 - put a check for lines beginning with !@? in log(). Needed
1374 (even if the handlers properly log their lines) for mid-session
1390 (even if the handlers properly log their lines) for mid-session
1375 logging activation to work properly. Without this, lines logged
1391 logging activation to work properly. Without this, lines logged
1376 in mid session, which get read from the cache, would end up
1392 in mid session, which get read from the cache, would end up
1377 'bare' (with !@? in the open) in the log. Now they are caught
1393 'bare' (with !@? in the open) in the log. Now they are caught
1378 and prepended with a #.
1394 and prepended with a #.
1379
1395
1380 * IPython/iplib.py (InteractiveShell.init_readline): added check
1396 * IPython/iplib.py (InteractiveShell.init_readline): added check
1381 in case MagicCompleter fails to be defined, so we don't crash.
1397 in case MagicCompleter fails to be defined, so we don't crash.
1382
1398
1383 2004-07-13 Fernando Perez <fperez@colorado.edu>
1399 2004-07-13 Fernando Perez <fperez@colorado.edu>
1384
1400
1385 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1401 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1386 of EPS if the requested filename ends in '.eps'.
1402 of EPS if the requested filename ends in '.eps'.
1387
1403
1388 2004-07-04 Fernando Perez <fperez@colorado.edu>
1404 2004-07-04 Fernando Perez <fperez@colorado.edu>
1389
1405
1390 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1406 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1391 escaping of quotes when calling the shell.
1407 escaping of quotes when calling the shell.
1392
1408
1393 2004-07-02 Fernando Perez <fperez@colorado.edu>
1409 2004-07-02 Fernando Perez <fperez@colorado.edu>
1394
1410
1395 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1411 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1396 gettext not working because we were clobbering '_'. Fixes
1412 gettext not working because we were clobbering '_'. Fixes
1397 http://www.scipy.net/roundup/ipython/issue6.
1413 http://www.scipy.net/roundup/ipython/issue6.
1398
1414
1399 2004-07-01 Fernando Perez <fperez@colorado.edu>
1415 2004-07-01 Fernando Perez <fperez@colorado.edu>
1400
1416
1401 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1417 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1402 into @cd. Patch by Ville.
1418 into @cd. Patch by Ville.
1403
1419
1404 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1420 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1405 new function to store things after ipmaker runs. Patch by Ville.
1421 new function to store things after ipmaker runs. Patch by Ville.
1406 Eventually this will go away once ipmaker is removed and the class
1422 Eventually this will go away once ipmaker is removed and the class
1407 gets cleaned up, but for now it's ok. Key functionality here is
1423 gets cleaned up, but for now it's ok. Key functionality here is
1408 the addition of the persistent storage mechanism, a dict for
1424 the addition of the persistent storage mechanism, a dict for
1409 keeping data across sessions (for now just bookmarks, but more can
1425 keeping data across sessions (for now just bookmarks, but more can
1410 be implemented later).
1426 be implemented later).
1411
1427
1412 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1428 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1413 persistent across sections. Patch by Ville, I modified it
1429 persistent across sections. Patch by Ville, I modified it
1414 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1430 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1415 added a '-l' option to list all bookmarks.
1431 added a '-l' option to list all bookmarks.
1416
1432
1417 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1433 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1418 center for cleanup. Registered with atexit.register(). I moved
1434 center for cleanup. Registered with atexit.register(). I moved
1419 here the old exit_cleanup(). After a patch by Ville.
1435 here the old exit_cleanup(). After a patch by Ville.
1420
1436
1421 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1437 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1422 characters in the hacked shlex_split for python 2.2.
1438 characters in the hacked shlex_split for python 2.2.
1423
1439
1424 * IPython/iplib.py (file_matches): more fixes to filenames with
1440 * IPython/iplib.py (file_matches): more fixes to filenames with
1425 whitespace in them. It's not perfect, but limitations in python's
1441 whitespace in them. It's not perfect, but limitations in python's
1426 readline make it impossible to go further.
1442 readline make it impossible to go further.
1427
1443
1428 2004-06-29 Fernando Perez <fperez@colorado.edu>
1444 2004-06-29 Fernando Perez <fperez@colorado.edu>
1429
1445
1430 * IPython/iplib.py (file_matches): escape whitespace correctly in
1446 * IPython/iplib.py (file_matches): escape whitespace correctly in
1431 filename completions. Bug reported by Ville.
1447 filename completions. Bug reported by Ville.
1432
1448
1433 2004-06-28 Fernando Perez <fperez@colorado.edu>
1449 2004-06-28 Fernando Perez <fperez@colorado.edu>
1434
1450
1435 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1451 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1436 the history file will be called 'history-PROFNAME' (or just
1452 the history file will be called 'history-PROFNAME' (or just
1437 'history' if no profile is loaded). I was getting annoyed at
1453 'history' if no profile is loaded). I was getting annoyed at
1438 getting my Numerical work history clobbered by pysh sessions.
1454 getting my Numerical work history clobbered by pysh sessions.
1439
1455
1440 * IPython/iplib.py (InteractiveShell.__init__): Internal
1456 * IPython/iplib.py (InteractiveShell.__init__): Internal
1441 getoutputerror() function so that we can honor the system_verbose
1457 getoutputerror() function so that we can honor the system_verbose
1442 flag for _all_ system calls. I also added escaping of #
1458 flag for _all_ system calls. I also added escaping of #
1443 characters here to avoid confusing Itpl.
1459 characters here to avoid confusing Itpl.
1444
1460
1445 * IPython/Magic.py (shlex_split): removed call to shell in
1461 * IPython/Magic.py (shlex_split): removed call to shell in
1446 parse_options and replaced it with shlex.split(). The annoying
1462 parse_options and replaced it with shlex.split(). The annoying
1447 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1463 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1448 to backport it from 2.3, with several frail hacks (the shlex
1464 to backport it from 2.3, with several frail hacks (the shlex
1449 module is rather limited in 2.2). Thanks to a suggestion by Ville
1465 module is rather limited in 2.2). Thanks to a suggestion by Ville
1450 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1466 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1451 problem.
1467 problem.
1452
1468
1453 (Magic.magic_system_verbose): new toggle to print the actual
1469 (Magic.magic_system_verbose): new toggle to print the actual
1454 system calls made by ipython. Mainly for debugging purposes.
1470 system calls made by ipython. Mainly for debugging purposes.
1455
1471
1456 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1472 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1457 doesn't support persistence. Reported (and fix suggested) by
1473 doesn't support persistence. Reported (and fix suggested) by
1458 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1474 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1459
1475
1460 2004-06-26 Fernando Perez <fperez@colorado.edu>
1476 2004-06-26 Fernando Perez <fperez@colorado.edu>
1461
1477
1462 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1478 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1463 continue prompts.
1479 continue prompts.
1464
1480
1465 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1481 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1466 function (basically a big docstring) and a few more things here to
1482 function (basically a big docstring) and a few more things here to
1467 speedup startup. pysh.py is now very lightweight. We want because
1483 speedup startup. pysh.py is now very lightweight. We want because
1468 it gets execfile'd, while InterpreterExec gets imported, so
1484 it gets execfile'd, while InterpreterExec gets imported, so
1469 byte-compilation saves time.
1485 byte-compilation saves time.
1470
1486
1471 2004-06-25 Fernando Perez <fperez@colorado.edu>
1487 2004-06-25 Fernando Perez <fperez@colorado.edu>
1472
1488
1473 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1489 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1474 -NUM', which was recently broken.
1490 -NUM', which was recently broken.
1475
1491
1476 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1492 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1477 in multi-line input (but not !!, which doesn't make sense there).
1493 in multi-line input (but not !!, which doesn't make sense there).
1478
1494
1479 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1495 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1480 It's just too useful, and people can turn it off in the less
1496 It's just too useful, and people can turn it off in the less
1481 common cases where it's a problem.
1497 common cases where it's a problem.
1482
1498
1483 2004-06-24 Fernando Perez <fperez@colorado.edu>
1499 2004-06-24 Fernando Perez <fperez@colorado.edu>
1484
1500
1485 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1501 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1486 special syntaxes (like alias calling) is now allied in multi-line
1502 special syntaxes (like alias calling) is now allied in multi-line
1487 input. This is still _very_ experimental, but it's necessary for
1503 input. This is still _very_ experimental, but it's necessary for
1488 efficient shell usage combining python looping syntax with system
1504 efficient shell usage combining python looping syntax with system
1489 calls. For now it's restricted to aliases, I don't think it
1505 calls. For now it's restricted to aliases, I don't think it
1490 really even makes sense to have this for magics.
1506 really even makes sense to have this for magics.
1491
1507
1492 2004-06-23 Fernando Perez <fperez@colorado.edu>
1508 2004-06-23 Fernando Perez <fperez@colorado.edu>
1493
1509
1494 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1510 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1495 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1511 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1496
1512
1497 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1513 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1498 extensions under Windows (after code sent by Gary Bishop). The
1514 extensions under Windows (after code sent by Gary Bishop). The
1499 extensions considered 'executable' are stored in IPython's rc
1515 extensions considered 'executable' are stored in IPython's rc
1500 structure as win_exec_ext.
1516 structure as win_exec_ext.
1501
1517
1502 * IPython/genutils.py (shell): new function, like system() but
1518 * IPython/genutils.py (shell): new function, like system() but
1503 without return value. Very useful for interactive shell work.
1519 without return value. Very useful for interactive shell work.
1504
1520
1505 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1521 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1506 delete aliases.
1522 delete aliases.
1507
1523
1508 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1524 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1509 sure that the alias table doesn't contain python keywords.
1525 sure that the alias table doesn't contain python keywords.
1510
1526
1511 2004-06-21 Fernando Perez <fperez@colorado.edu>
1527 2004-06-21 Fernando Perez <fperez@colorado.edu>
1512
1528
1513 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1529 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1514 non-existent items are found in $PATH. Reported by Thorsten.
1530 non-existent items are found in $PATH. Reported by Thorsten.
1515
1531
1516 2004-06-20 Fernando Perez <fperez@colorado.edu>
1532 2004-06-20 Fernando Perez <fperez@colorado.edu>
1517
1533
1518 * IPython/iplib.py (complete): modified the completer so that the
1534 * IPython/iplib.py (complete): modified the completer so that the
1519 order of priorities can be easily changed at runtime.
1535 order of priorities can be easily changed at runtime.
1520
1536
1521 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1537 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1522 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1538 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1523
1539
1524 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1540 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1525 expand Python variables prepended with $ in all system calls. The
1541 expand Python variables prepended with $ in all system calls. The
1526 same was done to InteractiveShell.handle_shell_escape. Now all
1542 same was done to InteractiveShell.handle_shell_escape. Now all
1527 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1543 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1528 expansion of python variables and expressions according to the
1544 expansion of python variables and expressions according to the
1529 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1545 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1530
1546
1531 Though PEP-215 has been rejected, a similar (but simpler) one
1547 Though PEP-215 has been rejected, a similar (but simpler) one
1532 seems like it will go into Python 2.4, PEP-292 -
1548 seems like it will go into Python 2.4, PEP-292 -
1533 http://www.python.org/peps/pep-0292.html.
1549 http://www.python.org/peps/pep-0292.html.
1534
1550
1535 I'll keep the full syntax of PEP-215, since IPython has since the
1551 I'll keep the full syntax of PEP-215, since IPython has since the
1536 start used Ka-Ping Yee's reference implementation discussed there
1552 start used Ka-Ping Yee's reference implementation discussed there
1537 (Itpl), and I actually like the powerful semantics it offers.
1553 (Itpl), and I actually like the powerful semantics it offers.
1538
1554
1539 In order to access normal shell variables, the $ has to be escaped
1555 In order to access normal shell variables, the $ has to be escaped
1540 via an extra $. For example:
1556 via an extra $. For example:
1541
1557
1542 In [7]: PATH='a python variable'
1558 In [7]: PATH='a python variable'
1543
1559
1544 In [8]: !echo $PATH
1560 In [8]: !echo $PATH
1545 a python variable
1561 a python variable
1546
1562
1547 In [9]: !echo $$PATH
1563 In [9]: !echo $$PATH
1548 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1564 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1549
1565
1550 (Magic.parse_options): escape $ so the shell doesn't evaluate
1566 (Magic.parse_options): escape $ so the shell doesn't evaluate
1551 things prematurely.
1567 things prematurely.
1552
1568
1553 * IPython/iplib.py (InteractiveShell.call_alias): added the
1569 * IPython/iplib.py (InteractiveShell.call_alias): added the
1554 ability for aliases to expand python variables via $.
1570 ability for aliases to expand python variables via $.
1555
1571
1556 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1572 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1557 system, now there's a @rehash/@rehashx pair of magics. These work
1573 system, now there's a @rehash/@rehashx pair of magics. These work
1558 like the csh rehash command, and can be invoked at any time. They
1574 like the csh rehash command, and can be invoked at any time. They
1559 build a table of aliases to everything in the user's $PATH
1575 build a table of aliases to everything in the user's $PATH
1560 (@rehash uses everything, @rehashx is slower but only adds
1576 (@rehash uses everything, @rehashx is slower but only adds
1561 executable files). With this, the pysh.py-based shell profile can
1577 executable files). With this, the pysh.py-based shell profile can
1562 now simply call rehash upon startup, and full access to all
1578 now simply call rehash upon startup, and full access to all
1563 programs in the user's path is obtained.
1579 programs in the user's path is obtained.
1564
1580
1565 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1581 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1566 functionality is now fully in place. I removed the old dynamic
1582 functionality is now fully in place. I removed the old dynamic
1567 code generation based approach, in favor of a much lighter one
1583 code generation based approach, in favor of a much lighter one
1568 based on a simple dict. The advantage is that this allows me to
1584 based on a simple dict. The advantage is that this allows me to
1569 now have thousands of aliases with negligible cost (unthinkable
1585 now have thousands of aliases with negligible cost (unthinkable
1570 with the old system).
1586 with the old system).
1571
1587
1572 2004-06-19 Fernando Perez <fperez@colorado.edu>
1588 2004-06-19 Fernando Perez <fperez@colorado.edu>
1573
1589
1574 * IPython/iplib.py (__init__): extended MagicCompleter class to
1590 * IPython/iplib.py (__init__): extended MagicCompleter class to
1575 also complete (last in priority) on user aliases.
1591 also complete (last in priority) on user aliases.
1576
1592
1577 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1593 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1578 call to eval.
1594 call to eval.
1579 (ItplNS.__init__): Added a new class which functions like Itpl,
1595 (ItplNS.__init__): Added a new class which functions like Itpl,
1580 but allows configuring the namespace for the evaluation to occur
1596 but allows configuring the namespace for the evaluation to occur
1581 in.
1597 in.
1582
1598
1583 2004-06-18 Fernando Perez <fperez@colorado.edu>
1599 2004-06-18 Fernando Perez <fperez@colorado.edu>
1584
1600
1585 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1601 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1586 better message when 'exit' or 'quit' are typed (a common newbie
1602 better message when 'exit' or 'quit' are typed (a common newbie
1587 confusion).
1603 confusion).
1588
1604
1589 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1605 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1590 check for Windows users.
1606 check for Windows users.
1591
1607
1592 * IPython/iplib.py (InteractiveShell.user_setup): removed
1608 * IPython/iplib.py (InteractiveShell.user_setup): removed
1593 disabling of colors for Windows. I'll test at runtime and issue a
1609 disabling of colors for Windows. I'll test at runtime and issue a
1594 warning if Gary's readline isn't found, as to nudge users to
1610 warning if Gary's readline isn't found, as to nudge users to
1595 download it.
1611 download it.
1596
1612
1597 2004-06-16 Fernando Perez <fperez@colorado.edu>
1613 2004-06-16 Fernando Perez <fperez@colorado.edu>
1598
1614
1599 * IPython/genutils.py (Stream.__init__): changed to print errors
1615 * IPython/genutils.py (Stream.__init__): changed to print errors
1600 to sys.stderr. I had a circular dependency here. Now it's
1616 to sys.stderr. I had a circular dependency here. Now it's
1601 possible to run ipython as IDLE's shell (consider this pre-alpha,
1617 possible to run ipython as IDLE's shell (consider this pre-alpha,
1602 since true stdout things end up in the starting terminal instead
1618 since true stdout things end up in the starting terminal instead
1603 of IDLE's out).
1619 of IDLE's out).
1604
1620
1605 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1621 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1606 users who haven't # updated their prompt_in2 definitions. Remove
1622 users who haven't # updated their prompt_in2 definitions. Remove
1607 eventually.
1623 eventually.
1608 (multiple_replace): added credit to original ASPN recipe.
1624 (multiple_replace): added credit to original ASPN recipe.
1609
1625
1610 2004-06-15 Fernando Perez <fperez@colorado.edu>
1626 2004-06-15 Fernando Perez <fperez@colorado.edu>
1611
1627
1612 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1628 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1613 list of auto-defined aliases.
1629 list of auto-defined aliases.
1614
1630
1615 2004-06-13 Fernando Perez <fperez@colorado.edu>
1631 2004-06-13 Fernando Perez <fperez@colorado.edu>
1616
1632
1617 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1633 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1618 install was really requested (so setup.py can be used for other
1634 install was really requested (so setup.py can be used for other
1619 things under Windows).
1635 things under Windows).
1620
1636
1621 2004-06-10 Fernando Perez <fperez@colorado.edu>
1637 2004-06-10 Fernando Perez <fperez@colorado.edu>
1622
1638
1623 * IPython/Logger.py (Logger.create_log): Manually remove any old
1639 * IPython/Logger.py (Logger.create_log): Manually remove any old
1624 backup, since os.remove may fail under Windows. Fixes bug
1640 backup, since os.remove may fail under Windows. Fixes bug
1625 reported by Thorsten.
1641 reported by Thorsten.
1626
1642
1627 2004-06-09 Fernando Perez <fperez@colorado.edu>
1643 2004-06-09 Fernando Perez <fperez@colorado.edu>
1628
1644
1629 * examples/example-embed.py: fixed all references to %n (replaced
1645 * examples/example-embed.py: fixed all references to %n (replaced
1630 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1646 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1631 for all examples and the manual as well.
1647 for all examples and the manual as well.
1632
1648
1633 2004-06-08 Fernando Perez <fperez@colorado.edu>
1649 2004-06-08 Fernando Perez <fperez@colorado.edu>
1634
1650
1635 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1651 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1636 alignment and color management. All 3 prompt subsystems now
1652 alignment and color management. All 3 prompt subsystems now
1637 inherit from BasePrompt.
1653 inherit from BasePrompt.
1638
1654
1639 * tools/release: updates for windows installer build and tag rpms
1655 * tools/release: updates for windows installer build and tag rpms
1640 with python version (since paths are fixed).
1656 with python version (since paths are fixed).
1641
1657
1642 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1658 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1643 which will become eventually obsolete. Also fixed the default
1659 which will become eventually obsolete. Also fixed the default
1644 prompt_in2 to use \D, so at least new users start with the correct
1660 prompt_in2 to use \D, so at least new users start with the correct
1645 defaults.
1661 defaults.
1646 WARNING: Users with existing ipythonrc files will need to apply
1662 WARNING: Users with existing ipythonrc files will need to apply
1647 this fix manually!
1663 this fix manually!
1648
1664
1649 * setup.py: make windows installer (.exe). This is finally the
1665 * setup.py: make windows installer (.exe). This is finally the
1650 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1666 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1651 which I hadn't included because it required Python 2.3 (or recent
1667 which I hadn't included because it required Python 2.3 (or recent
1652 distutils).
1668 distutils).
1653
1669
1654 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1670 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1655 usage of new '\D' escape.
1671 usage of new '\D' escape.
1656
1672
1657 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1673 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1658 lacks os.getuid())
1674 lacks os.getuid())
1659 (CachedOutput.set_colors): Added the ability to turn coloring
1675 (CachedOutput.set_colors): Added the ability to turn coloring
1660 on/off with @colors even for manually defined prompt colors. It
1676 on/off with @colors even for manually defined prompt colors. It
1661 uses a nasty global, but it works safely and via the generic color
1677 uses a nasty global, but it works safely and via the generic color
1662 handling mechanism.
1678 handling mechanism.
1663 (Prompt2.__init__): Introduced new escape '\D' for continuation
1679 (Prompt2.__init__): Introduced new escape '\D' for continuation
1664 prompts. It represents the counter ('\#') as dots.
1680 prompts. It represents the counter ('\#') as dots.
1665 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1681 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1666 need to update their ipythonrc files and replace '%n' with '\D' in
1682 need to update their ipythonrc files and replace '%n' with '\D' in
1667 their prompt_in2 settings everywhere. Sorry, but there's
1683 their prompt_in2 settings everywhere. Sorry, but there's
1668 otherwise no clean way to get all prompts to properly align. The
1684 otherwise no clean way to get all prompts to properly align. The
1669 ipythonrc shipped with IPython has been updated.
1685 ipythonrc shipped with IPython has been updated.
1670
1686
1671 2004-06-07 Fernando Perez <fperez@colorado.edu>
1687 2004-06-07 Fernando Perez <fperez@colorado.edu>
1672
1688
1673 * setup.py (isfile): Pass local_icons option to latex2html, so the
1689 * setup.py (isfile): Pass local_icons option to latex2html, so the
1674 resulting HTML file is self-contained. Thanks to
1690 resulting HTML file is self-contained. Thanks to
1675 dryice-AT-liu.com.cn for the tip.
1691 dryice-AT-liu.com.cn for the tip.
1676
1692
1677 * pysh.py: I created a new profile 'shell', which implements a
1693 * pysh.py: I created a new profile 'shell', which implements a
1678 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1694 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1679 system shell, nor will it become one anytime soon. It's mainly
1695 system shell, nor will it become one anytime soon. It's mainly
1680 meant to illustrate the use of the new flexible bash-like prompts.
1696 meant to illustrate the use of the new flexible bash-like prompts.
1681 I guess it could be used by hardy souls for true shell management,
1697 I guess it could be used by hardy souls for true shell management,
1682 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1698 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1683 profile. This uses the InterpreterExec extension provided by
1699 profile. This uses the InterpreterExec extension provided by
1684 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1700 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1685
1701
1686 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1702 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1687 auto-align itself with the length of the previous input prompt
1703 auto-align itself with the length of the previous input prompt
1688 (taking into account the invisible color escapes).
1704 (taking into account the invisible color escapes).
1689 (CachedOutput.__init__): Large restructuring of this class. Now
1705 (CachedOutput.__init__): Large restructuring of this class. Now
1690 all three prompts (primary1, primary2, output) are proper objects,
1706 all three prompts (primary1, primary2, output) are proper objects,
1691 managed by the 'parent' CachedOutput class. The code is still a
1707 managed by the 'parent' CachedOutput class. The code is still a
1692 bit hackish (all prompts share state via a pointer to the cache),
1708 bit hackish (all prompts share state via a pointer to the cache),
1693 but it's overall far cleaner than before.
1709 but it's overall far cleaner than before.
1694
1710
1695 * IPython/genutils.py (getoutputerror): modified to add verbose,
1711 * IPython/genutils.py (getoutputerror): modified to add verbose,
1696 debug and header options. This makes the interface of all getout*
1712 debug and header options. This makes the interface of all getout*
1697 functions uniform.
1713 functions uniform.
1698 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1714 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1699
1715
1700 * IPython/Magic.py (Magic.default_option): added a function to
1716 * IPython/Magic.py (Magic.default_option): added a function to
1701 allow registering default options for any magic command. This
1717 allow registering default options for any magic command. This
1702 makes it easy to have profiles which customize the magics globally
1718 makes it easy to have profiles which customize the magics globally
1703 for a certain use. The values set through this function are
1719 for a certain use. The values set through this function are
1704 picked up by the parse_options() method, which all magics should
1720 picked up by the parse_options() method, which all magics should
1705 use to parse their options.
1721 use to parse their options.
1706
1722
1707 * IPython/genutils.py (warn): modified the warnings framework to
1723 * IPython/genutils.py (warn): modified the warnings framework to
1708 use the Term I/O class. I'm trying to slowly unify all of
1724 use the Term I/O class. I'm trying to slowly unify all of
1709 IPython's I/O operations to pass through Term.
1725 IPython's I/O operations to pass through Term.
1710
1726
1711 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1727 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1712 the secondary prompt to correctly match the length of the primary
1728 the secondary prompt to correctly match the length of the primary
1713 one for any prompt. Now multi-line code will properly line up
1729 one for any prompt. Now multi-line code will properly line up
1714 even for path dependent prompts, such as the new ones available
1730 even for path dependent prompts, such as the new ones available
1715 via the prompt_specials.
1731 via the prompt_specials.
1716
1732
1717 2004-06-06 Fernando Perez <fperez@colorado.edu>
1733 2004-06-06 Fernando Perez <fperez@colorado.edu>
1718
1734
1719 * IPython/Prompts.py (prompt_specials): Added the ability to have
1735 * IPython/Prompts.py (prompt_specials): Added the ability to have
1720 bash-like special sequences in the prompts, which get
1736 bash-like special sequences in the prompts, which get
1721 automatically expanded. Things like hostname, current working
1737 automatically expanded. Things like hostname, current working
1722 directory and username are implemented already, but it's easy to
1738 directory and username are implemented already, but it's easy to
1723 add more in the future. Thanks to a patch by W.J. van der Laan
1739 add more in the future. Thanks to a patch by W.J. van der Laan
1724 <gnufnork-AT-hetdigitalegat.nl>
1740 <gnufnork-AT-hetdigitalegat.nl>
1725 (prompt_specials): Added color support for prompt strings, so
1741 (prompt_specials): Added color support for prompt strings, so
1726 users can define arbitrary color setups for their prompts.
1742 users can define arbitrary color setups for their prompts.
1727
1743
1728 2004-06-05 Fernando Perez <fperez@colorado.edu>
1744 2004-06-05 Fernando Perez <fperez@colorado.edu>
1729
1745
1730 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1746 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1731 code to load Gary Bishop's readline and configure it
1747 code to load Gary Bishop's readline and configure it
1732 automatically. Thanks to Gary for help on this.
1748 automatically. Thanks to Gary for help on this.
1733
1749
1734 2004-06-01 Fernando Perez <fperez@colorado.edu>
1750 2004-06-01 Fernando Perez <fperez@colorado.edu>
1735
1751
1736 * IPython/Logger.py (Logger.create_log): fix bug for logging
1752 * IPython/Logger.py (Logger.create_log): fix bug for logging
1737 with no filename (previous fix was incomplete).
1753 with no filename (previous fix was incomplete).
1738
1754
1739 2004-05-25 Fernando Perez <fperez@colorado.edu>
1755 2004-05-25 Fernando Perez <fperez@colorado.edu>
1740
1756
1741 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1757 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1742 parens would get passed to the shell.
1758 parens would get passed to the shell.
1743
1759
1744 2004-05-20 Fernando Perez <fperez@colorado.edu>
1760 2004-05-20 Fernando Perez <fperez@colorado.edu>
1745
1761
1746 * IPython/Magic.py (Magic.magic_prun): changed default profile
1762 * IPython/Magic.py (Magic.magic_prun): changed default profile
1747 sort order to 'time' (the more common profiling need).
1763 sort order to 'time' (the more common profiling need).
1748
1764
1749 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1765 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1750 so that source code shown is guaranteed in sync with the file on
1766 so that source code shown is guaranteed in sync with the file on
1751 disk (also changed in psource). Similar fix to the one for
1767 disk (also changed in psource). Similar fix to the one for
1752 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1768 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1753 <yann.ledu-AT-noos.fr>.
1769 <yann.ledu-AT-noos.fr>.
1754
1770
1755 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1771 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1756 with a single option would not be correctly parsed. Closes
1772 with a single option would not be correctly parsed. Closes
1757 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1773 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1758 introduced in 0.6.0 (on 2004-05-06).
1774 introduced in 0.6.0 (on 2004-05-06).
1759
1775
1760 2004-05-13 *** Released version 0.6.0
1776 2004-05-13 *** Released version 0.6.0
1761
1777
1762 2004-05-13 Fernando Perez <fperez@colorado.edu>
1778 2004-05-13 Fernando Perez <fperez@colorado.edu>
1763
1779
1764 * debian/: Added debian/ directory to CVS, so that debian support
1780 * debian/: Added debian/ directory to CVS, so that debian support
1765 is publicly accessible. The debian package is maintained by Jack
1781 is publicly accessible. The debian package is maintained by Jack
1766 Moffit <jack-AT-xiph.org>.
1782 Moffit <jack-AT-xiph.org>.
1767
1783
1768 * Documentation: included the notes about an ipython-based system
1784 * Documentation: included the notes about an ipython-based system
1769 shell (the hypothetical 'pysh') into the new_design.pdf document,
1785 shell (the hypothetical 'pysh') into the new_design.pdf document,
1770 so that these ideas get distributed to users along with the
1786 so that these ideas get distributed to users along with the
1771 official documentation.
1787 official documentation.
1772
1788
1773 2004-05-10 Fernando Perez <fperez@colorado.edu>
1789 2004-05-10 Fernando Perez <fperez@colorado.edu>
1774
1790
1775 * IPython/Logger.py (Logger.create_log): fix recently introduced
1791 * IPython/Logger.py (Logger.create_log): fix recently introduced
1776 bug (misindented line) where logstart would fail when not given an
1792 bug (misindented line) where logstart would fail when not given an
1777 explicit filename.
1793 explicit filename.
1778
1794
1779 2004-05-09 Fernando Perez <fperez@colorado.edu>
1795 2004-05-09 Fernando Perez <fperez@colorado.edu>
1780
1796
1781 * IPython/Magic.py (Magic.parse_options): skip system call when
1797 * IPython/Magic.py (Magic.parse_options): skip system call when
1782 there are no options to look for. Faster, cleaner for the common
1798 there are no options to look for. Faster, cleaner for the common
1783 case.
1799 case.
1784
1800
1785 * Documentation: many updates to the manual: describing Windows
1801 * Documentation: many updates to the manual: describing Windows
1786 support better, Gnuplot updates, credits, misc small stuff. Also
1802 support better, Gnuplot updates, credits, misc small stuff. Also
1787 updated the new_design doc a bit.
1803 updated the new_design doc a bit.
1788
1804
1789 2004-05-06 *** Released version 0.6.0.rc1
1805 2004-05-06 *** Released version 0.6.0.rc1
1790
1806
1791 2004-05-06 Fernando Perez <fperez@colorado.edu>
1807 2004-05-06 Fernando Perez <fperez@colorado.edu>
1792
1808
1793 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1809 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1794 operations to use the vastly more efficient list/''.join() method.
1810 operations to use the vastly more efficient list/''.join() method.
1795 (FormattedTB.text): Fix
1811 (FormattedTB.text): Fix
1796 http://www.scipy.net/roundup/ipython/issue12 - exception source
1812 http://www.scipy.net/roundup/ipython/issue12 - exception source
1797 extract not updated after reload. Thanks to Mike Salib
1813 extract not updated after reload. Thanks to Mike Salib
1798 <msalib-AT-mit.edu> for pinning the source of the problem.
1814 <msalib-AT-mit.edu> for pinning the source of the problem.
1799 Fortunately, the solution works inside ipython and doesn't require
1815 Fortunately, the solution works inside ipython and doesn't require
1800 any changes to python proper.
1816 any changes to python proper.
1801
1817
1802 * IPython/Magic.py (Magic.parse_options): Improved to process the
1818 * IPython/Magic.py (Magic.parse_options): Improved to process the
1803 argument list as a true shell would (by actually using the
1819 argument list as a true shell would (by actually using the
1804 underlying system shell). This way, all @magics automatically get
1820 underlying system shell). This way, all @magics automatically get
1805 shell expansion for variables. Thanks to a comment by Alex
1821 shell expansion for variables. Thanks to a comment by Alex
1806 Schmolck.
1822 Schmolck.
1807
1823
1808 2004-04-04 Fernando Perez <fperez@colorado.edu>
1824 2004-04-04 Fernando Perez <fperez@colorado.edu>
1809
1825
1810 * IPython/iplib.py (InteractiveShell.interact): Added a special
1826 * IPython/iplib.py (InteractiveShell.interact): Added a special
1811 trap for a debugger quit exception, which is basically impossible
1827 trap for a debugger quit exception, which is basically impossible
1812 to handle by normal mechanisms, given what pdb does to the stack.
1828 to handle by normal mechanisms, given what pdb does to the stack.
1813 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1829 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1814
1830
1815 2004-04-03 Fernando Perez <fperez@colorado.edu>
1831 2004-04-03 Fernando Perez <fperez@colorado.edu>
1816
1832
1817 * IPython/genutils.py (Term): Standardized the names of the Term
1833 * IPython/genutils.py (Term): Standardized the names of the Term
1818 class streams to cin/cout/cerr, following C++ naming conventions
1834 class streams to cin/cout/cerr, following C++ naming conventions
1819 (I can't use in/out/err because 'in' is not a valid attribute
1835 (I can't use in/out/err because 'in' is not a valid attribute
1820 name).
1836 name).
1821
1837
1822 * IPython/iplib.py (InteractiveShell.interact): don't increment
1838 * IPython/iplib.py (InteractiveShell.interact): don't increment
1823 the prompt if there's no user input. By Daniel 'Dang' Griffith
1839 the prompt if there's no user input. By Daniel 'Dang' Griffith
1824 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1840 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1825 Francois Pinard.
1841 Francois Pinard.
1826
1842
1827 2004-04-02 Fernando Perez <fperez@colorado.edu>
1843 2004-04-02 Fernando Perez <fperez@colorado.edu>
1828
1844
1829 * IPython/genutils.py (Stream.__init__): Modified to survive at
1845 * IPython/genutils.py (Stream.__init__): Modified to survive at
1830 least importing in contexts where stdin/out/err aren't true file
1846 least importing in contexts where stdin/out/err aren't true file
1831 objects, such as PyCrust (they lack fileno() and mode). However,
1847 objects, such as PyCrust (they lack fileno() and mode). However,
1832 the recovery facilities which rely on these things existing will
1848 the recovery facilities which rely on these things existing will
1833 not work.
1849 not work.
1834
1850
1835 2004-04-01 Fernando Perez <fperez@colorado.edu>
1851 2004-04-01 Fernando Perez <fperez@colorado.edu>
1836
1852
1837 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
1853 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
1838 use the new getoutputerror() function, so it properly
1854 use the new getoutputerror() function, so it properly
1839 distinguishes stdout/err.
1855 distinguishes stdout/err.
1840
1856
1841 * IPython/genutils.py (getoutputerror): added a function to
1857 * IPython/genutils.py (getoutputerror): added a function to
1842 capture separately the standard output and error of a command.
1858 capture separately the standard output and error of a command.
1843 After a comment from dang on the mailing lists. This code is
1859 After a comment from dang on the mailing lists. This code is
1844 basically a modified version of commands.getstatusoutput(), from
1860 basically a modified version of commands.getstatusoutput(), from
1845 the standard library.
1861 the standard library.
1846
1862
1847 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
1863 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
1848 '!!' as a special syntax (shorthand) to access @sx.
1864 '!!' as a special syntax (shorthand) to access @sx.
1849
1865
1850 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
1866 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
1851 command and return its output as a list split on '\n'.
1867 command and return its output as a list split on '\n'.
1852
1868
1853 2004-03-31 Fernando Perez <fperez@colorado.edu>
1869 2004-03-31 Fernando Perez <fperez@colorado.edu>
1854
1870
1855 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
1871 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
1856 method to dictionaries used as FakeModule instances if they lack
1872 method to dictionaries used as FakeModule instances if they lack
1857 it. At least pydoc in python2.3 breaks for runtime-defined
1873 it. At least pydoc in python2.3 breaks for runtime-defined
1858 functions without this hack. At some point I need to _really_
1874 functions without this hack. At some point I need to _really_
1859 understand what FakeModule is doing, because it's a gross hack.
1875 understand what FakeModule is doing, because it's a gross hack.
1860 But it solves Arnd's problem for now...
1876 But it solves Arnd's problem for now...
1861
1877
1862 2004-02-27 Fernando Perez <fperez@colorado.edu>
1878 2004-02-27 Fernando Perez <fperez@colorado.edu>
1863
1879
1864 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
1880 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
1865 mode would behave erratically. Also increased the number of
1881 mode would behave erratically. Also increased the number of
1866 possible logs in rotate mod to 999. Thanks to Rod Holland
1882 possible logs in rotate mod to 999. Thanks to Rod Holland
1867 <rhh@StructureLABS.com> for the report and fixes.
1883 <rhh@StructureLABS.com> for the report and fixes.
1868
1884
1869 2004-02-26 Fernando Perez <fperez@colorado.edu>
1885 2004-02-26 Fernando Perez <fperez@colorado.edu>
1870
1886
1871 * IPython/genutils.py (page): Check that the curses module really
1887 * IPython/genutils.py (page): Check that the curses module really
1872 has the initscr attribute before trying to use it. For some
1888 has the initscr attribute before trying to use it. For some
1873 reason, the Solaris curses module is missing this. I think this
1889 reason, the Solaris curses module is missing this. I think this
1874 should be considered a Solaris python bug, but I'm not sure.
1890 should be considered a Solaris python bug, but I'm not sure.
1875
1891
1876 2004-01-17 Fernando Perez <fperez@colorado.edu>
1892 2004-01-17 Fernando Perez <fperez@colorado.edu>
1877
1893
1878 * IPython/genutils.py (Stream.__init__): Changes to try to make
1894 * IPython/genutils.py (Stream.__init__): Changes to try to make
1879 ipython robust against stdin/out/err being closed by the user.
1895 ipython robust against stdin/out/err being closed by the user.
1880 This is 'user error' (and blocks a normal python session, at least
1896 This is 'user error' (and blocks a normal python session, at least
1881 the stdout case). However, Ipython should be able to survive such
1897 the stdout case). However, Ipython should be able to survive such
1882 instances of abuse as gracefully as possible. To simplify the
1898 instances of abuse as gracefully as possible. To simplify the
1883 coding and maintain compatibility with Gary Bishop's Term
1899 coding and maintain compatibility with Gary Bishop's Term
1884 contributions, I've made use of classmethods for this. I think
1900 contributions, I've made use of classmethods for this. I think
1885 this introduces a dependency on python 2.2.
1901 this introduces a dependency on python 2.2.
1886
1902
1887 2004-01-13 Fernando Perez <fperez@colorado.edu>
1903 2004-01-13 Fernando Perez <fperez@colorado.edu>
1888
1904
1889 * IPython/numutils.py (exp_safe): simplified the code a bit and
1905 * IPython/numutils.py (exp_safe): simplified the code a bit and
1890 removed the need for importing the kinds module altogether.
1906 removed the need for importing the kinds module altogether.
1891
1907
1892 2004-01-06 Fernando Perez <fperez@colorado.edu>
1908 2004-01-06 Fernando Perez <fperez@colorado.edu>
1893
1909
1894 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
1910 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
1895 a magic function instead, after some community feedback. No
1911 a magic function instead, after some community feedback. No
1896 special syntax will exist for it, but its name is deliberately
1912 special syntax will exist for it, but its name is deliberately
1897 very short.
1913 very short.
1898
1914
1899 2003-12-20 Fernando Perez <fperez@colorado.edu>
1915 2003-12-20 Fernando Perez <fperez@colorado.edu>
1900
1916
1901 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
1917 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
1902 new functionality, to automagically assign the result of a shell
1918 new functionality, to automagically assign the result of a shell
1903 command to a variable. I'll solicit some community feedback on
1919 command to a variable. I'll solicit some community feedback on
1904 this before making it permanent.
1920 this before making it permanent.
1905
1921
1906 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
1922 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
1907 requested about callables for which inspect couldn't obtain a
1923 requested about callables for which inspect couldn't obtain a
1908 proper argspec. Thanks to a crash report sent by Etienne
1924 proper argspec. Thanks to a crash report sent by Etienne
1909 Posthumus <etienne-AT-apple01.cs.vu.nl>.
1925 Posthumus <etienne-AT-apple01.cs.vu.nl>.
1910
1926
1911 2003-12-09 Fernando Perez <fperez@colorado.edu>
1927 2003-12-09 Fernando Perez <fperez@colorado.edu>
1912
1928
1913 * IPython/genutils.py (page): patch for the pager to work across
1929 * IPython/genutils.py (page): patch for the pager to work across
1914 various versions of Windows. By Gary Bishop.
1930 various versions of Windows. By Gary Bishop.
1915
1931
1916 2003-12-04 Fernando Perez <fperez@colorado.edu>
1932 2003-12-04 Fernando Perez <fperez@colorado.edu>
1917
1933
1918 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
1934 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
1919 Gnuplot.py version 1.7, whose internal names changed quite a bit.
1935 Gnuplot.py version 1.7, whose internal names changed quite a bit.
1920 While I tested this and it looks ok, there may still be corner
1936 While I tested this and it looks ok, there may still be corner
1921 cases I've missed.
1937 cases I've missed.
1922
1938
1923 2003-12-01 Fernando Perez <fperez@colorado.edu>
1939 2003-12-01 Fernando Perez <fperez@colorado.edu>
1924
1940
1925 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
1941 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
1926 where a line like 'p,q=1,2' would fail because the automagic
1942 where a line like 'p,q=1,2' would fail because the automagic
1927 system would be triggered for @p.
1943 system would be triggered for @p.
1928
1944
1929 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
1945 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
1930 cleanups, code unmodified.
1946 cleanups, code unmodified.
1931
1947
1932 * IPython/genutils.py (Term): added a class for IPython to handle
1948 * IPython/genutils.py (Term): added a class for IPython to handle
1933 output. In most cases it will just be a proxy for stdout/err, but
1949 output. In most cases it will just be a proxy for stdout/err, but
1934 having this allows modifications to be made for some platforms,
1950 having this allows modifications to be made for some platforms,
1935 such as handling color escapes under Windows. All of this code
1951 such as handling color escapes under Windows. All of this code
1936 was contributed by Gary Bishop, with minor modifications by me.
1952 was contributed by Gary Bishop, with minor modifications by me.
1937 The actual changes affect many files.
1953 The actual changes affect many files.
1938
1954
1939 2003-11-30 Fernando Perez <fperez@colorado.edu>
1955 2003-11-30 Fernando Perez <fperez@colorado.edu>
1940
1956
1941 * IPython/iplib.py (file_matches): new completion code, courtesy
1957 * IPython/iplib.py (file_matches): new completion code, courtesy
1942 of Jeff Collins. This enables filename completion again under
1958 of Jeff Collins. This enables filename completion again under
1943 python 2.3, which disabled it at the C level.
1959 python 2.3, which disabled it at the C level.
1944
1960
1945 2003-11-11 Fernando Perez <fperez@colorado.edu>
1961 2003-11-11 Fernando Perez <fperez@colorado.edu>
1946
1962
1947 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
1963 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
1948 for Numeric.array(map(...)), but often convenient.
1964 for Numeric.array(map(...)), but often convenient.
1949
1965
1950 2003-11-05 Fernando Perez <fperez@colorado.edu>
1966 2003-11-05 Fernando Perez <fperez@colorado.edu>
1951
1967
1952 * IPython/numutils.py (frange): Changed a call from int() to
1968 * IPython/numutils.py (frange): Changed a call from int() to
1953 int(round()) to prevent a problem reported with arange() in the
1969 int(round()) to prevent a problem reported with arange() in the
1954 numpy list.
1970 numpy list.
1955
1971
1956 2003-10-06 Fernando Perez <fperez@colorado.edu>
1972 2003-10-06 Fernando Perez <fperez@colorado.edu>
1957
1973
1958 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
1974 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
1959 prevent crashes if sys lacks an argv attribute (it happens with
1975 prevent crashes if sys lacks an argv attribute (it happens with
1960 embedded interpreters which build a bare-bones sys module).
1976 embedded interpreters which build a bare-bones sys module).
1961 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
1977 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
1962
1978
1963 2003-09-24 Fernando Perez <fperez@colorado.edu>
1979 2003-09-24 Fernando Perez <fperez@colorado.edu>
1964
1980
1965 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
1981 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
1966 to protect against poorly written user objects where __getattr__
1982 to protect against poorly written user objects where __getattr__
1967 raises exceptions other than AttributeError. Thanks to a bug
1983 raises exceptions other than AttributeError. Thanks to a bug
1968 report by Oliver Sander <osander-AT-gmx.de>.
1984 report by Oliver Sander <osander-AT-gmx.de>.
1969
1985
1970 * IPython/FakeModule.py (FakeModule.__repr__): this method was
1986 * IPython/FakeModule.py (FakeModule.__repr__): this method was
1971 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
1987 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
1972
1988
1973 2003-09-09 Fernando Perez <fperez@colorado.edu>
1989 2003-09-09 Fernando Perez <fperez@colorado.edu>
1974
1990
1975 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1991 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1976 unpacking a list whith a callable as first element would
1992 unpacking a list whith a callable as first element would
1977 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
1993 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
1978 Collins.
1994 Collins.
1979
1995
1980 2003-08-25 *** Released version 0.5.0
1996 2003-08-25 *** Released version 0.5.0
1981
1997
1982 2003-08-22 Fernando Perez <fperez@colorado.edu>
1998 2003-08-22 Fernando Perez <fperez@colorado.edu>
1983
1999
1984 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2000 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
1985 improperly defined user exceptions. Thanks to feedback from Mark
2001 improperly defined user exceptions. Thanks to feedback from Mark
1986 Russell <mrussell-AT-verio.net>.
2002 Russell <mrussell-AT-verio.net>.
1987
2003
1988 2003-08-20 Fernando Perez <fperez@colorado.edu>
2004 2003-08-20 Fernando Perez <fperez@colorado.edu>
1989
2005
1990 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2006 * IPython/OInspect.py (Inspector.pinfo): changed String Form
1991 printing so that it would print multi-line string forms starting
2007 printing so that it would print multi-line string forms starting
1992 with a new line. This way the formatting is better respected for
2008 with a new line. This way the formatting is better respected for
1993 objects which work hard to make nice string forms.
2009 objects which work hard to make nice string forms.
1994
2010
1995 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2011 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
1996 autocall would overtake data access for objects with both
2012 autocall would overtake data access for objects with both
1997 __getitem__ and __call__.
2013 __getitem__ and __call__.
1998
2014
1999 2003-08-19 *** Released version 0.5.0-rc1
2015 2003-08-19 *** Released version 0.5.0-rc1
2000
2016
2001 2003-08-19 Fernando Perez <fperez@colorado.edu>
2017 2003-08-19 Fernando Perez <fperez@colorado.edu>
2002
2018
2003 * IPython/deep_reload.py (load_tail): single tiny change here
2019 * IPython/deep_reload.py (load_tail): single tiny change here
2004 seems to fix the long-standing bug of dreload() failing to work
2020 seems to fix the long-standing bug of dreload() failing to work
2005 for dotted names. But this module is pretty tricky, so I may have
2021 for dotted names. But this module is pretty tricky, so I may have
2006 missed some subtlety. Needs more testing!.
2022 missed some subtlety. Needs more testing!.
2007
2023
2008 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2024 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2009 exceptions which have badly implemented __str__ methods.
2025 exceptions which have badly implemented __str__ methods.
2010 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2026 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2011 which I've been getting reports about from Python 2.3 users. I
2027 which I've been getting reports about from Python 2.3 users. I
2012 wish I had a simple test case to reproduce the problem, so I could
2028 wish I had a simple test case to reproduce the problem, so I could
2013 either write a cleaner workaround or file a bug report if
2029 either write a cleaner workaround or file a bug report if
2014 necessary.
2030 necessary.
2015
2031
2016 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2032 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2017 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2033 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2018 a bug report by Tjabo Kloppenburg.
2034 a bug report by Tjabo Kloppenburg.
2019
2035
2020 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2036 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2021 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2037 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2022 seems rather unstable. Thanks to a bug report by Tjabo
2038 seems rather unstable. Thanks to a bug report by Tjabo
2023 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2039 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2024
2040
2025 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2041 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2026 this out soon because of the critical fixes in the inner loop for
2042 this out soon because of the critical fixes in the inner loop for
2027 generators.
2043 generators.
2028
2044
2029 * IPython/Magic.py (Magic.getargspec): removed. This (and
2045 * IPython/Magic.py (Magic.getargspec): removed. This (and
2030 _get_def) have been obsoleted by OInspect for a long time, I
2046 _get_def) have been obsoleted by OInspect for a long time, I
2031 hadn't noticed that they were dead code.
2047 hadn't noticed that they were dead code.
2032 (Magic._ofind): restored _ofind functionality for a few literals
2048 (Magic._ofind): restored _ofind functionality for a few literals
2033 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2049 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2034 for things like "hello".capitalize?, since that would require a
2050 for things like "hello".capitalize?, since that would require a
2035 potentially dangerous eval() again.
2051 potentially dangerous eval() again.
2036
2052
2037 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2053 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2038 logic a bit more to clean up the escapes handling and minimize the
2054 logic a bit more to clean up the escapes handling and minimize the
2039 use of _ofind to only necessary cases. The interactive 'feel' of
2055 use of _ofind to only necessary cases. The interactive 'feel' of
2040 IPython should have improved quite a bit with the changes in
2056 IPython should have improved quite a bit with the changes in
2041 _prefilter and _ofind (besides being far safer than before).
2057 _prefilter and _ofind (besides being far safer than before).
2042
2058
2043 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2059 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2044 obscure, never reported). Edit would fail to find the object to
2060 obscure, never reported). Edit would fail to find the object to
2045 edit under some circumstances.
2061 edit under some circumstances.
2046 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2062 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2047 which were causing double-calling of generators. Those eval calls
2063 which were causing double-calling of generators. Those eval calls
2048 were _very_ dangerous, since code with side effects could be
2064 were _very_ dangerous, since code with side effects could be
2049 triggered. As they say, 'eval is evil'... These were the
2065 triggered. As they say, 'eval is evil'... These were the
2050 nastiest evals in IPython. Besides, _ofind is now far simpler,
2066 nastiest evals in IPython. Besides, _ofind is now far simpler,
2051 and it should also be quite a bit faster. Its use of inspect is
2067 and it should also be quite a bit faster. Its use of inspect is
2052 also safer, so perhaps some of the inspect-related crashes I've
2068 also safer, so perhaps some of the inspect-related crashes I've
2053 seen lately with Python 2.3 might be taken care of. That will
2069 seen lately with Python 2.3 might be taken care of. That will
2054 need more testing.
2070 need more testing.
2055
2071
2056 2003-08-17 Fernando Perez <fperez@colorado.edu>
2072 2003-08-17 Fernando Perez <fperez@colorado.edu>
2057
2073
2058 * IPython/iplib.py (InteractiveShell._prefilter): significant
2074 * IPython/iplib.py (InteractiveShell._prefilter): significant
2059 simplifications to the logic for handling user escapes. Faster
2075 simplifications to the logic for handling user escapes. Faster
2060 and simpler code.
2076 and simpler code.
2061
2077
2062 2003-08-14 Fernando Perez <fperez@colorado.edu>
2078 2003-08-14 Fernando Perez <fperez@colorado.edu>
2063
2079
2064 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2080 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2065 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2081 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2066 but it should be quite a bit faster. And the recursive version
2082 but it should be quite a bit faster. And the recursive version
2067 generated O(log N) intermediate storage for all rank>1 arrays,
2083 generated O(log N) intermediate storage for all rank>1 arrays,
2068 even if they were contiguous.
2084 even if they were contiguous.
2069 (l1norm): Added this function.
2085 (l1norm): Added this function.
2070 (norm): Added this function for arbitrary norms (including
2086 (norm): Added this function for arbitrary norms (including
2071 l-infinity). l1 and l2 are still special cases for convenience
2087 l-infinity). l1 and l2 are still special cases for convenience
2072 and speed.
2088 and speed.
2073
2089
2074 2003-08-03 Fernando Perez <fperez@colorado.edu>
2090 2003-08-03 Fernando Perez <fperez@colorado.edu>
2075
2091
2076 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2092 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2077 exceptions, which now raise PendingDeprecationWarnings in Python
2093 exceptions, which now raise PendingDeprecationWarnings in Python
2078 2.3. There were some in Magic and some in Gnuplot2.
2094 2.3. There were some in Magic and some in Gnuplot2.
2079
2095
2080 2003-06-30 Fernando Perez <fperez@colorado.edu>
2096 2003-06-30 Fernando Perez <fperez@colorado.edu>
2081
2097
2082 * IPython/genutils.py (page): modified to call curses only for
2098 * IPython/genutils.py (page): modified to call curses only for
2083 terminals where TERM=='xterm'. After problems under many other
2099 terminals where TERM=='xterm'. After problems under many other
2084 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2100 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2085
2101
2086 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2102 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2087 would be triggered when readline was absent. This was just an old
2103 would be triggered when readline was absent. This was just an old
2088 debugging statement I'd forgotten to take out.
2104 debugging statement I'd forgotten to take out.
2089
2105
2090 2003-06-20 Fernando Perez <fperez@colorado.edu>
2106 2003-06-20 Fernando Perez <fperez@colorado.edu>
2091
2107
2092 * IPython/genutils.py (clock): modified to return only user time
2108 * IPython/genutils.py (clock): modified to return only user time
2093 (not counting system time), after a discussion on scipy. While
2109 (not counting system time), after a discussion on scipy. While
2094 system time may be a useful quantity occasionally, it may much
2110 system time may be a useful quantity occasionally, it may much
2095 more easily be skewed by occasional swapping or other similar
2111 more easily be skewed by occasional swapping or other similar
2096 activity.
2112 activity.
2097
2113
2098 2003-06-05 Fernando Perez <fperez@colorado.edu>
2114 2003-06-05 Fernando Perez <fperez@colorado.edu>
2099
2115
2100 * IPython/numutils.py (identity): new function, for building
2116 * IPython/numutils.py (identity): new function, for building
2101 arbitrary rank Kronecker deltas (mostly backwards compatible with
2117 arbitrary rank Kronecker deltas (mostly backwards compatible with
2102 Numeric.identity)
2118 Numeric.identity)
2103
2119
2104 2003-06-03 Fernando Perez <fperez@colorado.edu>
2120 2003-06-03 Fernando Perez <fperez@colorado.edu>
2105
2121
2106 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2122 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2107 arguments passed to magics with spaces, to allow trailing '\' to
2123 arguments passed to magics with spaces, to allow trailing '\' to
2108 work normally (mainly for Windows users).
2124 work normally (mainly for Windows users).
2109
2125
2110 2003-05-29 Fernando Perez <fperez@colorado.edu>
2126 2003-05-29 Fernando Perez <fperez@colorado.edu>
2111
2127
2112 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2128 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2113 instead of pydoc.help. This fixes a bizarre behavior where
2129 instead of pydoc.help. This fixes a bizarre behavior where
2114 printing '%s' % locals() would trigger the help system. Now
2130 printing '%s' % locals() would trigger the help system. Now
2115 ipython behaves like normal python does.
2131 ipython behaves like normal python does.
2116
2132
2117 Note that if one does 'from pydoc import help', the bizarre
2133 Note that if one does 'from pydoc import help', the bizarre
2118 behavior returns, but this will also happen in normal python, so
2134 behavior returns, but this will also happen in normal python, so
2119 it's not an ipython bug anymore (it has to do with how pydoc.help
2135 it's not an ipython bug anymore (it has to do with how pydoc.help
2120 is implemented).
2136 is implemented).
2121
2137
2122 2003-05-22 Fernando Perez <fperez@colorado.edu>
2138 2003-05-22 Fernando Perez <fperez@colorado.edu>
2123
2139
2124 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2140 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2125 return [] instead of None when nothing matches, also match to end
2141 return [] instead of None when nothing matches, also match to end
2126 of line. Patch by Gary Bishop.
2142 of line. Patch by Gary Bishop.
2127
2143
2128 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2144 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2129 protection as before, for files passed on the command line. This
2145 protection as before, for files passed on the command line. This
2130 prevents the CrashHandler from kicking in if user files call into
2146 prevents the CrashHandler from kicking in if user files call into
2131 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2147 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2132 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2148 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2133
2149
2134 2003-05-20 *** Released version 0.4.0
2150 2003-05-20 *** Released version 0.4.0
2135
2151
2136 2003-05-20 Fernando Perez <fperez@colorado.edu>
2152 2003-05-20 Fernando Perez <fperez@colorado.edu>
2137
2153
2138 * setup.py: added support for manpages. It's a bit hackish b/c of
2154 * setup.py: added support for manpages. It's a bit hackish b/c of
2139 a bug in the way the bdist_rpm distutils target handles gzipped
2155 a bug in the way the bdist_rpm distutils target handles gzipped
2140 manpages, but it works. After a patch by Jack.
2156 manpages, but it works. After a patch by Jack.
2141
2157
2142 2003-05-19 Fernando Perez <fperez@colorado.edu>
2158 2003-05-19 Fernando Perez <fperez@colorado.edu>
2143
2159
2144 * IPython/numutils.py: added a mockup of the kinds module, since
2160 * IPython/numutils.py: added a mockup of the kinds module, since
2145 it was recently removed from Numeric. This way, numutils will
2161 it was recently removed from Numeric. This way, numutils will
2146 work for all users even if they are missing kinds.
2162 work for all users even if they are missing kinds.
2147
2163
2148 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2164 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2149 failure, which can occur with SWIG-wrapped extensions. After a
2165 failure, which can occur with SWIG-wrapped extensions. After a
2150 crash report from Prabhu.
2166 crash report from Prabhu.
2151
2167
2152 2003-05-16 Fernando Perez <fperez@colorado.edu>
2168 2003-05-16 Fernando Perez <fperez@colorado.edu>
2153
2169
2154 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2170 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2155 protect ipython from user code which may call directly
2171 protect ipython from user code which may call directly
2156 sys.excepthook (this looks like an ipython crash to the user, even
2172 sys.excepthook (this looks like an ipython crash to the user, even
2157 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2173 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2158 This is especially important to help users of WxWindows, but may
2174 This is especially important to help users of WxWindows, but may
2159 also be useful in other cases.
2175 also be useful in other cases.
2160
2176
2161 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2177 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2162 an optional tb_offset to be specified, and to preserve exception
2178 an optional tb_offset to be specified, and to preserve exception
2163 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2179 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2164
2180
2165 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2181 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2166
2182
2167 2003-05-15 Fernando Perez <fperez@colorado.edu>
2183 2003-05-15 Fernando Perez <fperez@colorado.edu>
2168
2184
2169 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2185 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2170 installing for a new user under Windows.
2186 installing for a new user under Windows.
2171
2187
2172 2003-05-12 Fernando Perez <fperez@colorado.edu>
2188 2003-05-12 Fernando Perez <fperez@colorado.edu>
2173
2189
2174 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2190 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2175 handler for Emacs comint-based lines. Currently it doesn't do
2191 handler for Emacs comint-based lines. Currently it doesn't do
2176 much (but importantly, it doesn't update the history cache). In
2192 much (but importantly, it doesn't update the history cache). In
2177 the future it may be expanded if Alex needs more functionality
2193 the future it may be expanded if Alex needs more functionality
2178 there.
2194 there.
2179
2195
2180 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2196 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2181 info to crash reports.
2197 info to crash reports.
2182
2198
2183 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2199 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2184 just like Python's -c. Also fixed crash with invalid -color
2200 just like Python's -c. Also fixed crash with invalid -color
2185 option value at startup. Thanks to Will French
2201 option value at startup. Thanks to Will French
2186 <wfrench-AT-bestweb.net> for the bug report.
2202 <wfrench-AT-bestweb.net> for the bug report.
2187
2203
2188 2003-05-09 Fernando Perez <fperez@colorado.edu>
2204 2003-05-09 Fernando Perez <fperez@colorado.edu>
2189
2205
2190 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2206 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2191 to EvalDict (it's a mapping, after all) and simplified its code
2207 to EvalDict (it's a mapping, after all) and simplified its code
2192 quite a bit, after a nice discussion on c.l.py where Gustavo
2208 quite a bit, after a nice discussion on c.l.py where Gustavo
2193 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2209 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2194
2210
2195 2003-04-30 Fernando Perez <fperez@colorado.edu>
2211 2003-04-30 Fernando Perez <fperez@colorado.edu>
2196
2212
2197 * IPython/genutils.py (timings_out): modified it to reduce its
2213 * IPython/genutils.py (timings_out): modified it to reduce its
2198 overhead in the common reps==1 case.
2214 overhead in the common reps==1 case.
2199
2215
2200 2003-04-29 Fernando Perez <fperez@colorado.edu>
2216 2003-04-29 Fernando Perez <fperez@colorado.edu>
2201
2217
2202 * IPython/genutils.py (timings_out): Modified to use the resource
2218 * IPython/genutils.py (timings_out): Modified to use the resource
2203 module, which avoids the wraparound problems of time.clock().
2219 module, which avoids the wraparound problems of time.clock().
2204
2220
2205 2003-04-17 *** Released version 0.2.15pre4
2221 2003-04-17 *** Released version 0.2.15pre4
2206
2222
2207 2003-04-17 Fernando Perez <fperez@colorado.edu>
2223 2003-04-17 Fernando Perez <fperez@colorado.edu>
2208
2224
2209 * setup.py (scriptfiles): Split windows-specific stuff over to a
2225 * setup.py (scriptfiles): Split windows-specific stuff over to a
2210 separate file, in an attempt to have a Windows GUI installer.
2226 separate file, in an attempt to have a Windows GUI installer.
2211 That didn't work, but part of the groundwork is done.
2227 That didn't work, but part of the groundwork is done.
2212
2228
2213 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2229 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2214 indent/unindent with 4 spaces. Particularly useful in combination
2230 indent/unindent with 4 spaces. Particularly useful in combination
2215 with the new auto-indent option.
2231 with the new auto-indent option.
2216
2232
2217 2003-04-16 Fernando Perez <fperez@colorado.edu>
2233 2003-04-16 Fernando Perez <fperez@colorado.edu>
2218
2234
2219 * IPython/Magic.py: various replacements of self.rc for
2235 * IPython/Magic.py: various replacements of self.rc for
2220 self.shell.rc. A lot more remains to be done to fully disentangle
2236 self.shell.rc. A lot more remains to be done to fully disentangle
2221 this class from the main Shell class.
2237 this class from the main Shell class.
2222
2238
2223 * IPython/GnuplotRuntime.py: added checks for mouse support so
2239 * IPython/GnuplotRuntime.py: added checks for mouse support so
2224 that we don't try to enable it if the current gnuplot doesn't
2240 that we don't try to enable it if the current gnuplot doesn't
2225 really support it. Also added checks so that we don't try to
2241 really support it. Also added checks so that we don't try to
2226 enable persist under Windows (where Gnuplot doesn't recognize the
2242 enable persist under Windows (where Gnuplot doesn't recognize the
2227 option).
2243 option).
2228
2244
2229 * IPython/iplib.py (InteractiveShell.interact): Added optional
2245 * IPython/iplib.py (InteractiveShell.interact): Added optional
2230 auto-indenting code, after a patch by King C. Shu
2246 auto-indenting code, after a patch by King C. Shu
2231 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2247 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2232 get along well with pasting indented code. If I ever figure out
2248 get along well with pasting indented code. If I ever figure out
2233 how to make that part go well, it will become on by default.
2249 how to make that part go well, it will become on by default.
2234
2250
2235 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2251 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2236 crash ipython if there was an unmatched '%' in the user's prompt
2252 crash ipython if there was an unmatched '%' in the user's prompt
2237 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2253 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2238
2254
2239 * IPython/iplib.py (InteractiveShell.interact): removed the
2255 * IPython/iplib.py (InteractiveShell.interact): removed the
2240 ability to ask the user whether he wants to crash or not at the
2256 ability to ask the user whether he wants to crash or not at the
2241 'last line' exception handler. Calling functions at that point
2257 'last line' exception handler. Calling functions at that point
2242 changes the stack, and the error reports would have incorrect
2258 changes the stack, and the error reports would have incorrect
2243 tracebacks.
2259 tracebacks.
2244
2260
2245 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2261 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2246 pass through a peger a pretty-printed form of any object. After a
2262 pass through a peger a pretty-printed form of any object. After a
2247 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2263 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2248
2264
2249 2003-04-14 Fernando Perez <fperez@colorado.edu>
2265 2003-04-14 Fernando Perez <fperez@colorado.edu>
2250
2266
2251 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2267 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2252 all files in ~ would be modified at first install (instead of
2268 all files in ~ would be modified at first install (instead of
2253 ~/.ipython). This could be potentially disastrous, as the
2269 ~/.ipython). This could be potentially disastrous, as the
2254 modification (make line-endings native) could damage binary files.
2270 modification (make line-endings native) could damage binary files.
2255
2271
2256 2003-04-10 Fernando Perez <fperez@colorado.edu>
2272 2003-04-10 Fernando Perez <fperez@colorado.edu>
2257
2273
2258 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2274 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2259 handle only lines which are invalid python. This now means that
2275 handle only lines which are invalid python. This now means that
2260 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2276 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2261 for the bug report.
2277 for the bug report.
2262
2278
2263 2003-04-01 Fernando Perez <fperez@colorado.edu>
2279 2003-04-01 Fernando Perez <fperez@colorado.edu>
2264
2280
2265 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2281 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2266 where failing to set sys.last_traceback would crash pdb.pm().
2282 where failing to set sys.last_traceback would crash pdb.pm().
2267 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2283 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2268 report.
2284 report.
2269
2285
2270 2003-03-25 Fernando Perez <fperez@colorado.edu>
2286 2003-03-25 Fernando Perez <fperez@colorado.edu>
2271
2287
2272 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2288 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2273 before printing it (it had a lot of spurious blank lines at the
2289 before printing it (it had a lot of spurious blank lines at the
2274 end).
2290 end).
2275
2291
2276 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2292 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2277 output would be sent 21 times! Obviously people don't use this
2293 output would be sent 21 times! Obviously people don't use this
2278 too often, or I would have heard about it.
2294 too often, or I would have heard about it.
2279
2295
2280 2003-03-24 Fernando Perez <fperez@colorado.edu>
2296 2003-03-24 Fernando Perez <fperez@colorado.edu>
2281
2297
2282 * setup.py (scriptfiles): renamed the data_files parameter from
2298 * setup.py (scriptfiles): renamed the data_files parameter from
2283 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2299 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2284 for the patch.
2300 for the patch.
2285
2301
2286 2003-03-20 Fernando Perez <fperez@colorado.edu>
2302 2003-03-20 Fernando Perez <fperez@colorado.edu>
2287
2303
2288 * IPython/genutils.py (error): added error() and fatal()
2304 * IPython/genutils.py (error): added error() and fatal()
2289 functions.
2305 functions.
2290
2306
2291 2003-03-18 *** Released version 0.2.15pre3
2307 2003-03-18 *** Released version 0.2.15pre3
2292
2308
2293 2003-03-18 Fernando Perez <fperez@colorado.edu>
2309 2003-03-18 Fernando Perez <fperez@colorado.edu>
2294
2310
2295 * setupext/install_data_ext.py
2311 * setupext/install_data_ext.py
2296 (install_data_ext.initialize_options): Class contributed by Jack
2312 (install_data_ext.initialize_options): Class contributed by Jack
2297 Moffit for fixing the old distutils hack. He is sending this to
2313 Moffit for fixing the old distutils hack. He is sending this to
2298 the distutils folks so in the future we may not need it as a
2314 the distutils folks so in the future we may not need it as a
2299 private fix.
2315 private fix.
2300
2316
2301 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2317 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2302 changes for Debian packaging. See his patch for full details.
2318 changes for Debian packaging. See his patch for full details.
2303 The old distutils hack of making the ipythonrc* files carry a
2319 The old distutils hack of making the ipythonrc* files carry a
2304 bogus .py extension is gone, at last. Examples were moved to a
2320 bogus .py extension is gone, at last. Examples were moved to a
2305 separate subdir under doc/, and the separate executable scripts
2321 separate subdir under doc/, and the separate executable scripts
2306 now live in their own directory. Overall a great cleanup. The
2322 now live in their own directory. Overall a great cleanup. The
2307 manual was updated to use the new files, and setup.py has been
2323 manual was updated to use the new files, and setup.py has been
2308 fixed for this setup.
2324 fixed for this setup.
2309
2325
2310 * IPython/PyColorize.py (Parser.usage): made non-executable and
2326 * IPython/PyColorize.py (Parser.usage): made non-executable and
2311 created a pycolor wrapper around it to be included as a script.
2327 created a pycolor wrapper around it to be included as a script.
2312
2328
2313 2003-03-12 *** Released version 0.2.15pre2
2329 2003-03-12 *** Released version 0.2.15pre2
2314
2330
2315 2003-03-12 Fernando Perez <fperez@colorado.edu>
2331 2003-03-12 Fernando Perez <fperez@colorado.edu>
2316
2332
2317 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2333 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2318 long-standing problem with garbage characters in some terminals.
2334 long-standing problem with garbage characters in some terminals.
2319 The issue was really that the \001 and \002 escapes must _only_ be
2335 The issue was really that the \001 and \002 escapes must _only_ be
2320 passed to input prompts (which call readline), but _never_ to
2336 passed to input prompts (which call readline), but _never_ to
2321 normal text to be printed on screen. I changed ColorANSI to have
2337 normal text to be printed on screen. I changed ColorANSI to have
2322 two classes: TermColors and InputTermColors, each with the
2338 two classes: TermColors and InputTermColors, each with the
2323 appropriate escapes for input prompts or normal text. The code in
2339 appropriate escapes for input prompts or normal text. The code in
2324 Prompts.py got slightly more complicated, but this very old and
2340 Prompts.py got slightly more complicated, but this very old and
2325 annoying bug is finally fixed.
2341 annoying bug is finally fixed.
2326
2342
2327 All the credit for nailing down the real origin of this problem
2343 All the credit for nailing down the real origin of this problem
2328 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2344 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2329 *Many* thanks to him for spending quite a bit of effort on this.
2345 *Many* thanks to him for spending quite a bit of effort on this.
2330
2346
2331 2003-03-05 *** Released version 0.2.15pre1
2347 2003-03-05 *** Released version 0.2.15pre1
2332
2348
2333 2003-03-03 Fernando Perez <fperez@colorado.edu>
2349 2003-03-03 Fernando Perez <fperez@colorado.edu>
2334
2350
2335 * IPython/FakeModule.py: Moved the former _FakeModule to a
2351 * IPython/FakeModule.py: Moved the former _FakeModule to a
2336 separate file, because it's also needed by Magic (to fix a similar
2352 separate file, because it's also needed by Magic (to fix a similar
2337 pickle-related issue in @run).
2353 pickle-related issue in @run).
2338
2354
2339 2003-03-02 Fernando Perez <fperez@colorado.edu>
2355 2003-03-02 Fernando Perez <fperez@colorado.edu>
2340
2356
2341 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2357 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2342 the autocall option at runtime.
2358 the autocall option at runtime.
2343 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2359 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2344 across Magic.py to start separating Magic from InteractiveShell.
2360 across Magic.py to start separating Magic from InteractiveShell.
2345 (Magic._ofind): Fixed to return proper namespace for dotted
2361 (Magic._ofind): Fixed to return proper namespace for dotted
2346 names. Before, a dotted name would always return 'not currently
2362 names. Before, a dotted name would always return 'not currently
2347 defined', because it would find the 'parent'. s.x would be found,
2363 defined', because it would find the 'parent'. s.x would be found,
2348 but since 'x' isn't defined by itself, it would get confused.
2364 but since 'x' isn't defined by itself, it would get confused.
2349 (Magic.magic_run): Fixed pickling problems reported by Ralf
2365 (Magic.magic_run): Fixed pickling problems reported by Ralf
2350 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2366 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2351 that I'd used when Mike Heeter reported similar issues at the
2367 that I'd used when Mike Heeter reported similar issues at the
2352 top-level, but now for @run. It boils down to injecting the
2368 top-level, but now for @run. It boils down to injecting the
2353 namespace where code is being executed with something that looks
2369 namespace where code is being executed with something that looks
2354 enough like a module to fool pickle.dump(). Since a pickle stores
2370 enough like a module to fool pickle.dump(). Since a pickle stores
2355 a named reference to the importing module, we need this for
2371 a named reference to the importing module, we need this for
2356 pickles to save something sensible.
2372 pickles to save something sensible.
2357
2373
2358 * IPython/ipmaker.py (make_IPython): added an autocall option.
2374 * IPython/ipmaker.py (make_IPython): added an autocall option.
2359
2375
2360 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2376 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2361 the auto-eval code. Now autocalling is an option, and the code is
2377 the auto-eval code. Now autocalling is an option, and the code is
2362 also vastly safer. There is no more eval() involved at all.
2378 also vastly safer. There is no more eval() involved at all.
2363
2379
2364 2003-03-01 Fernando Perez <fperez@colorado.edu>
2380 2003-03-01 Fernando Perez <fperez@colorado.edu>
2365
2381
2366 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2382 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2367 dict with named keys instead of a tuple.
2383 dict with named keys instead of a tuple.
2368
2384
2369 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2385 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2370
2386
2371 * setup.py (make_shortcut): Fixed message about directories
2387 * setup.py (make_shortcut): Fixed message about directories
2372 created during Windows installation (the directories were ok, just
2388 created during Windows installation (the directories were ok, just
2373 the printed message was misleading). Thanks to Chris Liechti
2389 the printed message was misleading). Thanks to Chris Liechti
2374 <cliechti-AT-gmx.net> for the heads up.
2390 <cliechti-AT-gmx.net> for the heads up.
2375
2391
2376 2003-02-21 Fernando Perez <fperez@colorado.edu>
2392 2003-02-21 Fernando Perez <fperez@colorado.edu>
2377
2393
2378 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2394 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2379 of ValueError exception when checking for auto-execution. This
2395 of ValueError exception when checking for auto-execution. This
2380 one is raised by things like Numeric arrays arr.flat when the
2396 one is raised by things like Numeric arrays arr.flat when the
2381 array is non-contiguous.
2397 array is non-contiguous.
2382
2398
2383 2003-01-31 Fernando Perez <fperez@colorado.edu>
2399 2003-01-31 Fernando Perez <fperez@colorado.edu>
2384
2400
2385 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2401 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2386 not return any value at all (even though the command would get
2402 not return any value at all (even though the command would get
2387 executed).
2403 executed).
2388 (xsys): Flush stdout right after printing the command to ensure
2404 (xsys): Flush stdout right after printing the command to ensure
2389 proper ordering of commands and command output in the total
2405 proper ordering of commands and command output in the total
2390 output.
2406 output.
2391 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2407 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2392 system/getoutput as defaults. The old ones are kept for
2408 system/getoutput as defaults. The old ones are kept for
2393 compatibility reasons, so no code which uses this library needs
2409 compatibility reasons, so no code which uses this library needs
2394 changing.
2410 changing.
2395
2411
2396 2003-01-27 *** Released version 0.2.14
2412 2003-01-27 *** Released version 0.2.14
2397
2413
2398 2003-01-25 Fernando Perez <fperez@colorado.edu>
2414 2003-01-25 Fernando Perez <fperez@colorado.edu>
2399
2415
2400 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2416 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2401 functions defined in previous edit sessions could not be re-edited
2417 functions defined in previous edit sessions could not be re-edited
2402 (because the temp files were immediately removed). Now temp files
2418 (because the temp files were immediately removed). Now temp files
2403 are removed only at IPython's exit.
2419 are removed only at IPython's exit.
2404 (Magic.magic_run): Improved @run to perform shell-like expansions
2420 (Magic.magic_run): Improved @run to perform shell-like expansions
2405 on its arguments (~users and $VARS). With this, @run becomes more
2421 on its arguments (~users and $VARS). With this, @run becomes more
2406 like a normal command-line.
2422 like a normal command-line.
2407
2423
2408 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2424 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2409 bugs related to embedding and cleaned up that code. A fairly
2425 bugs related to embedding and cleaned up that code. A fairly
2410 important one was the impossibility to access the global namespace
2426 important one was the impossibility to access the global namespace
2411 through the embedded IPython (only local variables were visible).
2427 through the embedded IPython (only local variables were visible).
2412
2428
2413 2003-01-14 Fernando Perez <fperez@colorado.edu>
2429 2003-01-14 Fernando Perez <fperez@colorado.edu>
2414
2430
2415 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2431 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2416 auto-calling to be a bit more conservative. Now it doesn't get
2432 auto-calling to be a bit more conservative. Now it doesn't get
2417 triggered if any of '!=()<>' are in the rest of the input line, to
2433 triggered if any of '!=()<>' are in the rest of the input line, to
2418 allow comparing callables. Thanks to Alex for the heads up.
2434 allow comparing callables. Thanks to Alex for the heads up.
2419
2435
2420 2003-01-07 Fernando Perez <fperez@colorado.edu>
2436 2003-01-07 Fernando Perez <fperez@colorado.edu>
2421
2437
2422 * IPython/genutils.py (page): fixed estimation of the number of
2438 * IPython/genutils.py (page): fixed estimation of the number of
2423 lines in a string to be paged to simply count newlines. This
2439 lines in a string to be paged to simply count newlines. This
2424 prevents over-guessing due to embedded escape sequences. A better
2440 prevents over-guessing due to embedded escape sequences. A better
2425 long-term solution would involve stripping out the control chars
2441 long-term solution would involve stripping out the control chars
2426 for the count, but it's potentially so expensive I just don't
2442 for the count, but it's potentially so expensive I just don't
2427 think it's worth doing.
2443 think it's worth doing.
2428
2444
2429 2002-12-19 *** Released version 0.2.14pre50
2445 2002-12-19 *** Released version 0.2.14pre50
2430
2446
2431 2002-12-19 Fernando Perez <fperez@colorado.edu>
2447 2002-12-19 Fernando Perez <fperez@colorado.edu>
2432
2448
2433 * tools/release (version): Changed release scripts to inform
2449 * tools/release (version): Changed release scripts to inform
2434 Andrea and build a NEWS file with a list of recent changes.
2450 Andrea and build a NEWS file with a list of recent changes.
2435
2451
2436 * IPython/ColorANSI.py (__all__): changed terminal detection
2452 * IPython/ColorANSI.py (__all__): changed terminal detection
2437 code. Seems to work better for xterms without breaking
2453 code. Seems to work better for xterms without breaking
2438 konsole. Will need more testing to determine if WinXP and Mac OSX
2454 konsole. Will need more testing to determine if WinXP and Mac OSX
2439 also work ok.
2455 also work ok.
2440
2456
2441 2002-12-18 *** Released version 0.2.14pre49
2457 2002-12-18 *** Released version 0.2.14pre49
2442
2458
2443 2002-12-18 Fernando Perez <fperez@colorado.edu>
2459 2002-12-18 Fernando Perez <fperez@colorado.edu>
2444
2460
2445 * Docs: added new info about Mac OSX, from Andrea.
2461 * Docs: added new info about Mac OSX, from Andrea.
2446
2462
2447 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2463 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2448 allow direct plotting of python strings whose format is the same
2464 allow direct plotting of python strings whose format is the same
2449 of gnuplot data files.
2465 of gnuplot data files.
2450
2466
2451 2002-12-16 Fernando Perez <fperez@colorado.edu>
2467 2002-12-16 Fernando Perez <fperez@colorado.edu>
2452
2468
2453 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2469 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2454 value of exit question to be acknowledged.
2470 value of exit question to be acknowledged.
2455
2471
2456 2002-12-03 Fernando Perez <fperez@colorado.edu>
2472 2002-12-03 Fernando Perez <fperez@colorado.edu>
2457
2473
2458 * IPython/ipmaker.py: removed generators, which had been added
2474 * IPython/ipmaker.py: removed generators, which had been added
2459 by mistake in an earlier debugging run. This was causing trouble
2475 by mistake in an earlier debugging run. This was causing trouble
2460 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2476 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2461 for pointing this out.
2477 for pointing this out.
2462
2478
2463 2002-11-17 Fernando Perez <fperez@colorado.edu>
2479 2002-11-17 Fernando Perez <fperez@colorado.edu>
2464
2480
2465 * Manual: updated the Gnuplot section.
2481 * Manual: updated the Gnuplot section.
2466
2482
2467 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2483 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2468 a much better split of what goes in Runtime and what goes in
2484 a much better split of what goes in Runtime and what goes in
2469 Interactive.
2485 Interactive.
2470
2486
2471 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2487 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2472 being imported from iplib.
2488 being imported from iplib.
2473
2489
2474 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2490 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2475 for command-passing. Now the global Gnuplot instance is called
2491 for command-passing. Now the global Gnuplot instance is called
2476 'gp' instead of 'g', which was really a far too fragile and
2492 'gp' instead of 'g', which was really a far too fragile and
2477 common name.
2493 common name.
2478
2494
2479 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2495 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2480 bounding boxes generated by Gnuplot for square plots.
2496 bounding boxes generated by Gnuplot for square plots.
2481
2497
2482 * IPython/genutils.py (popkey): new function added. I should
2498 * IPython/genutils.py (popkey): new function added. I should
2483 suggest this on c.l.py as a dict method, it seems useful.
2499 suggest this on c.l.py as a dict method, it seems useful.
2484
2500
2485 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2501 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2486 to transparently handle PostScript generation. MUCH better than
2502 to transparently handle PostScript generation. MUCH better than
2487 the previous plot_eps/replot_eps (which I removed now). The code
2503 the previous plot_eps/replot_eps (which I removed now). The code
2488 is also fairly clean and well documented now (including
2504 is also fairly clean and well documented now (including
2489 docstrings).
2505 docstrings).
2490
2506
2491 2002-11-13 Fernando Perez <fperez@colorado.edu>
2507 2002-11-13 Fernando Perez <fperez@colorado.edu>
2492
2508
2493 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2509 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2494 (inconsistent with options).
2510 (inconsistent with options).
2495
2511
2496 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2512 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2497 manually disabled, I don't know why. Fixed it.
2513 manually disabled, I don't know why. Fixed it.
2498 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2514 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2499 eps output.
2515 eps output.
2500
2516
2501 2002-11-12 Fernando Perez <fperez@colorado.edu>
2517 2002-11-12 Fernando Perez <fperez@colorado.edu>
2502
2518
2503 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2519 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2504 don't propagate up to caller. Fixes crash reported by François
2520 don't propagate up to caller. Fixes crash reported by François
2505 Pinard.
2521 Pinard.
2506
2522
2507 2002-11-09 Fernando Perez <fperez@colorado.edu>
2523 2002-11-09 Fernando Perez <fperez@colorado.edu>
2508
2524
2509 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2525 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2510 history file for new users.
2526 history file for new users.
2511 (make_IPython): fixed bug where initial install would leave the
2527 (make_IPython): fixed bug where initial install would leave the
2512 user running in the .ipython dir.
2528 user running in the .ipython dir.
2513 (make_IPython): fixed bug where config dir .ipython would be
2529 (make_IPython): fixed bug where config dir .ipython would be
2514 created regardless of the given -ipythondir option. Thanks to Cory
2530 created regardless of the given -ipythondir option. Thanks to Cory
2515 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2531 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2516
2532
2517 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2533 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2518 type confirmations. Will need to use it in all of IPython's code
2534 type confirmations. Will need to use it in all of IPython's code
2519 consistently.
2535 consistently.
2520
2536
2521 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2537 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2522 context to print 31 lines instead of the default 5. This will make
2538 context to print 31 lines instead of the default 5. This will make
2523 the crash reports extremely detailed in case the problem is in
2539 the crash reports extremely detailed in case the problem is in
2524 libraries I don't have access to.
2540 libraries I don't have access to.
2525
2541
2526 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2542 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2527 line of defense' code to still crash, but giving users fair
2543 line of defense' code to still crash, but giving users fair
2528 warning. I don't want internal errors to go unreported: if there's
2544 warning. I don't want internal errors to go unreported: if there's
2529 an internal problem, IPython should crash and generate a full
2545 an internal problem, IPython should crash and generate a full
2530 report.
2546 report.
2531
2547
2532 2002-11-08 Fernando Perez <fperez@colorado.edu>
2548 2002-11-08 Fernando Perez <fperez@colorado.edu>
2533
2549
2534 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2550 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2535 otherwise uncaught exceptions which can appear if people set
2551 otherwise uncaught exceptions which can appear if people set
2536 sys.stdout to something badly broken. Thanks to a crash report
2552 sys.stdout to something badly broken. Thanks to a crash report
2537 from henni-AT-mail.brainbot.com.
2553 from henni-AT-mail.brainbot.com.
2538
2554
2539 2002-11-04 Fernando Perez <fperez@colorado.edu>
2555 2002-11-04 Fernando Perez <fperez@colorado.edu>
2540
2556
2541 * IPython/iplib.py (InteractiveShell.interact): added
2557 * IPython/iplib.py (InteractiveShell.interact): added
2542 __IPYTHON__active to the builtins. It's a flag which goes on when
2558 __IPYTHON__active to the builtins. It's a flag which goes on when
2543 the interaction starts and goes off again when it stops. This
2559 the interaction starts and goes off again when it stops. This
2544 allows embedding code to detect being inside IPython. Before this
2560 allows embedding code to detect being inside IPython. Before this
2545 was done via __IPYTHON__, but that only shows that an IPython
2561 was done via __IPYTHON__, but that only shows that an IPython
2546 instance has been created.
2562 instance has been created.
2547
2563
2548 * IPython/Magic.py (Magic.magic_env): I realized that in a
2564 * IPython/Magic.py (Magic.magic_env): I realized that in a
2549 UserDict, instance.data holds the data as a normal dict. So I
2565 UserDict, instance.data holds the data as a normal dict. So I
2550 modified @env to return os.environ.data instead of rebuilding a
2566 modified @env to return os.environ.data instead of rebuilding a
2551 dict by hand.
2567 dict by hand.
2552
2568
2553 2002-11-02 Fernando Perez <fperez@colorado.edu>
2569 2002-11-02 Fernando Perez <fperez@colorado.edu>
2554
2570
2555 * IPython/genutils.py (warn): changed so that level 1 prints no
2571 * IPython/genutils.py (warn): changed so that level 1 prints no
2556 header. Level 2 is now the default (with 'WARNING' header, as
2572 header. Level 2 is now the default (with 'WARNING' header, as
2557 before). I think I tracked all places where changes were needed in
2573 before). I think I tracked all places where changes were needed in
2558 IPython, but outside code using the old level numbering may have
2574 IPython, but outside code using the old level numbering may have
2559 broken.
2575 broken.
2560
2576
2561 * IPython/iplib.py (InteractiveShell.runcode): added this to
2577 * IPython/iplib.py (InteractiveShell.runcode): added this to
2562 handle the tracebacks in SystemExit traps correctly. The previous
2578 handle the tracebacks in SystemExit traps correctly. The previous
2563 code (through interact) was printing more of the stack than
2579 code (through interact) was printing more of the stack than
2564 necessary, showing IPython internal code to the user.
2580 necessary, showing IPython internal code to the user.
2565
2581
2566 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2582 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2567 default. Now that the default at the confirmation prompt is yes,
2583 default. Now that the default at the confirmation prompt is yes,
2568 it's not so intrusive. François' argument that ipython sessions
2584 it's not so intrusive. François' argument that ipython sessions
2569 tend to be complex enough not to lose them from an accidental C-d,
2585 tend to be complex enough not to lose them from an accidental C-d,
2570 is a valid one.
2586 is a valid one.
2571
2587
2572 * IPython/iplib.py (InteractiveShell.interact): added a
2588 * IPython/iplib.py (InteractiveShell.interact): added a
2573 showtraceback() call to the SystemExit trap, and modified the exit
2589 showtraceback() call to the SystemExit trap, and modified the exit
2574 confirmation to have yes as the default.
2590 confirmation to have yes as the default.
2575
2591
2576 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2592 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2577 this file. It's been gone from the code for a long time, this was
2593 this file. It's been gone from the code for a long time, this was
2578 simply leftover junk.
2594 simply leftover junk.
2579
2595
2580 2002-11-01 Fernando Perez <fperez@colorado.edu>
2596 2002-11-01 Fernando Perez <fperez@colorado.edu>
2581
2597
2582 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2598 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2583 added. If set, IPython now traps EOF and asks for
2599 added. If set, IPython now traps EOF and asks for
2584 confirmation. After a request by François Pinard.
2600 confirmation. After a request by François Pinard.
2585
2601
2586 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2602 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2587 of @abort, and with a new (better) mechanism for handling the
2603 of @abort, and with a new (better) mechanism for handling the
2588 exceptions.
2604 exceptions.
2589
2605
2590 2002-10-27 Fernando Perez <fperez@colorado.edu>
2606 2002-10-27 Fernando Perez <fperez@colorado.edu>
2591
2607
2592 * IPython/usage.py (__doc__): updated the --help information and
2608 * IPython/usage.py (__doc__): updated the --help information and
2593 the ipythonrc file to indicate that -log generates
2609 the ipythonrc file to indicate that -log generates
2594 ./ipython.log. Also fixed the corresponding info in @logstart.
2610 ./ipython.log. Also fixed the corresponding info in @logstart.
2595 This and several other fixes in the manuals thanks to reports by
2611 This and several other fixes in the manuals thanks to reports by
2596 François Pinard <pinard-AT-iro.umontreal.ca>.
2612 François Pinard <pinard-AT-iro.umontreal.ca>.
2597
2613
2598 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2614 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2599 refer to @logstart (instead of @log, which doesn't exist).
2615 refer to @logstart (instead of @log, which doesn't exist).
2600
2616
2601 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2617 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2602 AttributeError crash. Thanks to Christopher Armstrong
2618 AttributeError crash. Thanks to Christopher Armstrong
2603 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2619 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2604 introduced recently (in 0.2.14pre37) with the fix to the eval
2620 introduced recently (in 0.2.14pre37) with the fix to the eval
2605 problem mentioned below.
2621 problem mentioned below.
2606
2622
2607 2002-10-17 Fernando Perez <fperez@colorado.edu>
2623 2002-10-17 Fernando Perez <fperez@colorado.edu>
2608
2624
2609 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2625 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2610 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2626 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2611
2627
2612 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2628 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2613 this function to fix a problem reported by Alex Schmolck. He saw
2629 this function to fix a problem reported by Alex Schmolck. He saw
2614 it with list comprehensions and generators, which were getting
2630 it with list comprehensions and generators, which were getting
2615 called twice. The real problem was an 'eval' call in testing for
2631 called twice. The real problem was an 'eval' call in testing for
2616 automagic which was evaluating the input line silently.
2632 automagic which was evaluating the input line silently.
2617
2633
2618 This is a potentially very nasty bug, if the input has side
2634 This is a potentially very nasty bug, if the input has side
2619 effects which must not be repeated. The code is much cleaner now,
2635 effects which must not be repeated. The code is much cleaner now,
2620 without any blanket 'except' left and with a regexp test for
2636 without any blanket 'except' left and with a regexp test for
2621 actual function names.
2637 actual function names.
2622
2638
2623 But an eval remains, which I'm not fully comfortable with. I just
2639 But an eval remains, which I'm not fully comfortable with. I just
2624 don't know how to find out if an expression could be a callable in
2640 don't know how to find out if an expression could be a callable in
2625 the user's namespace without doing an eval on the string. However
2641 the user's namespace without doing an eval on the string. However
2626 that string is now much more strictly checked so that no code
2642 that string is now much more strictly checked so that no code
2627 slips by, so the eval should only happen for things that can
2643 slips by, so the eval should only happen for things that can
2628 really be only function/method names.
2644 really be only function/method names.
2629
2645
2630 2002-10-15 Fernando Perez <fperez@colorado.edu>
2646 2002-10-15 Fernando Perez <fperez@colorado.edu>
2631
2647
2632 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2648 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2633 OSX information to main manual, removed README_Mac_OSX file from
2649 OSX information to main manual, removed README_Mac_OSX file from
2634 distribution. Also updated credits for recent additions.
2650 distribution. Also updated credits for recent additions.
2635
2651
2636 2002-10-10 Fernando Perez <fperez@colorado.edu>
2652 2002-10-10 Fernando Perez <fperez@colorado.edu>
2637
2653
2638 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2654 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2639 terminal-related issues. Many thanks to Andrea Riciputi
2655 terminal-related issues. Many thanks to Andrea Riciputi
2640 <andrea.riciputi-AT-libero.it> for writing it.
2656 <andrea.riciputi-AT-libero.it> for writing it.
2641
2657
2642 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2658 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2643 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2659 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2644
2660
2645 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2661 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2646 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2662 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2647 <syver-en-AT-online.no> who both submitted patches for this problem.
2663 <syver-en-AT-online.no> who both submitted patches for this problem.
2648
2664
2649 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2665 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2650 global embedding to make sure that things don't overwrite user
2666 global embedding to make sure that things don't overwrite user
2651 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2667 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2652
2668
2653 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2669 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2654 compatibility. Thanks to Hayden Callow
2670 compatibility. Thanks to Hayden Callow
2655 <h.callow-AT-elec.canterbury.ac.nz>
2671 <h.callow-AT-elec.canterbury.ac.nz>
2656
2672
2657 2002-10-04 Fernando Perez <fperez@colorado.edu>
2673 2002-10-04 Fernando Perez <fperez@colorado.edu>
2658
2674
2659 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2675 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2660 Gnuplot.File objects.
2676 Gnuplot.File objects.
2661
2677
2662 2002-07-23 Fernando Perez <fperez@colorado.edu>
2678 2002-07-23 Fernando Perez <fperez@colorado.edu>
2663
2679
2664 * IPython/genutils.py (timing): Added timings() and timing() for
2680 * IPython/genutils.py (timing): Added timings() and timing() for
2665 quick access to the most commonly needed data, the execution
2681 quick access to the most commonly needed data, the execution
2666 times. Old timing() renamed to timings_out().
2682 times. Old timing() renamed to timings_out().
2667
2683
2668 2002-07-18 Fernando Perez <fperez@colorado.edu>
2684 2002-07-18 Fernando Perez <fperez@colorado.edu>
2669
2685
2670 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2686 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2671 bug with nested instances disrupting the parent's tab completion.
2687 bug with nested instances disrupting the parent's tab completion.
2672
2688
2673 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2689 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2674 all_completions code to begin the emacs integration.
2690 all_completions code to begin the emacs integration.
2675
2691
2676 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2692 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2677 argument to allow titling individual arrays when plotting.
2693 argument to allow titling individual arrays when plotting.
2678
2694
2679 2002-07-15 Fernando Perez <fperez@colorado.edu>
2695 2002-07-15 Fernando Perez <fperez@colorado.edu>
2680
2696
2681 * setup.py (make_shortcut): changed to retrieve the value of
2697 * setup.py (make_shortcut): changed to retrieve the value of
2682 'Program Files' directory from the registry (this value changes in
2698 'Program Files' directory from the registry (this value changes in
2683 non-english versions of Windows). Thanks to Thomas Fanslau
2699 non-english versions of Windows). Thanks to Thomas Fanslau
2684 <tfanslau-AT-gmx.de> for the report.
2700 <tfanslau-AT-gmx.de> for the report.
2685
2701
2686 2002-07-10 Fernando Perez <fperez@colorado.edu>
2702 2002-07-10 Fernando Perez <fperez@colorado.edu>
2687
2703
2688 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2704 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2689 a bug in pdb, which crashes if a line with only whitespace is
2705 a bug in pdb, which crashes if a line with only whitespace is
2690 entered. Bug report submitted to sourceforge.
2706 entered. Bug report submitted to sourceforge.
2691
2707
2692 2002-07-09 Fernando Perez <fperez@colorado.edu>
2708 2002-07-09 Fernando Perez <fperez@colorado.edu>
2693
2709
2694 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2710 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2695 reporting exceptions (it's a bug in inspect.py, I just set a
2711 reporting exceptions (it's a bug in inspect.py, I just set a
2696 workaround).
2712 workaround).
2697
2713
2698 2002-07-08 Fernando Perez <fperez@colorado.edu>
2714 2002-07-08 Fernando Perez <fperez@colorado.edu>
2699
2715
2700 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2716 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2701 __IPYTHON__ in __builtins__ to show up in user_ns.
2717 __IPYTHON__ in __builtins__ to show up in user_ns.
2702
2718
2703 2002-07-03 Fernando Perez <fperez@colorado.edu>
2719 2002-07-03 Fernando Perez <fperez@colorado.edu>
2704
2720
2705 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2721 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2706 name from @gp_set_instance to @gp_set_default.
2722 name from @gp_set_instance to @gp_set_default.
2707
2723
2708 * IPython/ipmaker.py (make_IPython): default editor value set to
2724 * IPython/ipmaker.py (make_IPython): default editor value set to
2709 '0' (a string), to match the rc file. Otherwise will crash when
2725 '0' (a string), to match the rc file. Otherwise will crash when
2710 .strip() is called on it.
2726 .strip() is called on it.
2711
2727
2712
2728
2713 2002-06-28 Fernando Perez <fperez@colorado.edu>
2729 2002-06-28 Fernando Perez <fperez@colorado.edu>
2714
2730
2715 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2731 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2716 of files in current directory when a file is executed via
2732 of files in current directory when a file is executed via
2717 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2733 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2718
2734
2719 * setup.py (manfiles): fix for rpm builds, submitted by RA
2735 * setup.py (manfiles): fix for rpm builds, submitted by RA
2720 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2736 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2721
2737
2722 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2738 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2723 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2739 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2724 string!). A. Schmolck caught this one.
2740 string!). A. Schmolck caught this one.
2725
2741
2726 2002-06-27 Fernando Perez <fperez@colorado.edu>
2742 2002-06-27 Fernando Perez <fperez@colorado.edu>
2727
2743
2728 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2744 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2729 defined files at the cmd line. __name__ wasn't being set to
2745 defined files at the cmd line. __name__ wasn't being set to
2730 __main__.
2746 __main__.
2731
2747
2732 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2748 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2733 regular lists and tuples besides Numeric arrays.
2749 regular lists and tuples besides Numeric arrays.
2734
2750
2735 * IPython/Prompts.py (CachedOutput.__call__): Added output
2751 * IPython/Prompts.py (CachedOutput.__call__): Added output
2736 supression for input ending with ';'. Similar to Mathematica and
2752 supression for input ending with ';'. Similar to Mathematica and
2737 Matlab. The _* vars and Out[] list are still updated, just like
2753 Matlab. The _* vars and Out[] list are still updated, just like
2738 Mathematica behaves.
2754 Mathematica behaves.
2739
2755
2740 2002-06-25 Fernando Perez <fperez@colorado.edu>
2756 2002-06-25 Fernando Perez <fperez@colorado.edu>
2741
2757
2742 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2758 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2743 .ini extensions for profiels under Windows.
2759 .ini extensions for profiels under Windows.
2744
2760
2745 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2761 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2746 string form. Fix contributed by Alexander Schmolck
2762 string form. Fix contributed by Alexander Schmolck
2747 <a.schmolck-AT-gmx.net>
2763 <a.schmolck-AT-gmx.net>
2748
2764
2749 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2765 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2750 pre-configured Gnuplot instance.
2766 pre-configured Gnuplot instance.
2751
2767
2752 2002-06-21 Fernando Perez <fperez@colorado.edu>
2768 2002-06-21 Fernando Perez <fperez@colorado.edu>
2753
2769
2754 * IPython/numutils.py (exp_safe): new function, works around the
2770 * IPython/numutils.py (exp_safe): new function, works around the
2755 underflow problems in Numeric.
2771 underflow problems in Numeric.
2756 (log2): New fn. Safe log in base 2: returns exact integer answer
2772 (log2): New fn. Safe log in base 2: returns exact integer answer
2757 for exact integer powers of 2.
2773 for exact integer powers of 2.
2758
2774
2759 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2775 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2760 properly.
2776 properly.
2761
2777
2762 2002-06-20 Fernando Perez <fperez@colorado.edu>
2778 2002-06-20 Fernando Perez <fperez@colorado.edu>
2763
2779
2764 * IPython/genutils.py (timing): new function like
2780 * IPython/genutils.py (timing): new function like
2765 Mathematica's. Similar to time_test, but returns more info.
2781 Mathematica's. Similar to time_test, but returns more info.
2766
2782
2767 2002-06-18 Fernando Perez <fperez@colorado.edu>
2783 2002-06-18 Fernando Perez <fperez@colorado.edu>
2768
2784
2769 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2785 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2770 according to Mike Heeter's suggestions.
2786 according to Mike Heeter's suggestions.
2771
2787
2772 2002-06-16 Fernando Perez <fperez@colorado.edu>
2788 2002-06-16 Fernando Perez <fperez@colorado.edu>
2773
2789
2774 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2790 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2775 system. GnuplotMagic is gone as a user-directory option. New files
2791 system. GnuplotMagic is gone as a user-directory option. New files
2776 make it easier to use all the gnuplot stuff both from external
2792 make it easier to use all the gnuplot stuff both from external
2777 programs as well as from IPython. Had to rewrite part of
2793 programs as well as from IPython. Had to rewrite part of
2778 hardcopy() b/c of a strange bug: often the ps files simply don't
2794 hardcopy() b/c of a strange bug: often the ps files simply don't
2779 get created, and require a repeat of the command (often several
2795 get created, and require a repeat of the command (often several
2780 times).
2796 times).
2781
2797
2782 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2798 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2783 resolve output channel at call time, so that if sys.stderr has
2799 resolve output channel at call time, so that if sys.stderr has
2784 been redirected by user this gets honored.
2800 been redirected by user this gets honored.
2785
2801
2786 2002-06-13 Fernando Perez <fperez@colorado.edu>
2802 2002-06-13 Fernando Perez <fperez@colorado.edu>
2787
2803
2788 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2804 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2789 IPShell. Kept a copy with the old names to avoid breaking people's
2805 IPShell. Kept a copy with the old names to avoid breaking people's
2790 embedded code.
2806 embedded code.
2791
2807
2792 * IPython/ipython: simplified it to the bare minimum after
2808 * IPython/ipython: simplified it to the bare minimum after
2793 Holger's suggestions. Added info about how to use it in
2809 Holger's suggestions. Added info about how to use it in
2794 PYTHONSTARTUP.
2810 PYTHONSTARTUP.
2795
2811
2796 * IPython/Shell.py (IPythonShell): changed the options passing
2812 * IPython/Shell.py (IPythonShell): changed the options passing
2797 from a string with funky %s replacements to a straight list. Maybe
2813 from a string with funky %s replacements to a straight list. Maybe
2798 a bit more typing, but it follows sys.argv conventions, so there's
2814 a bit more typing, but it follows sys.argv conventions, so there's
2799 less special-casing to remember.
2815 less special-casing to remember.
2800
2816
2801 2002-06-12 Fernando Perez <fperez@colorado.edu>
2817 2002-06-12 Fernando Perez <fperez@colorado.edu>
2802
2818
2803 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2819 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2804 command. Thanks to a suggestion by Mike Heeter.
2820 command. Thanks to a suggestion by Mike Heeter.
2805 (Magic.magic_pfile): added behavior to look at filenames if given
2821 (Magic.magic_pfile): added behavior to look at filenames if given
2806 arg is not a defined object.
2822 arg is not a defined object.
2807 (Magic.magic_save): New @save function to save code snippets. Also
2823 (Magic.magic_save): New @save function to save code snippets. Also
2808 a Mike Heeter idea.
2824 a Mike Heeter idea.
2809
2825
2810 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2826 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2811 plot() and replot(). Much more convenient now, especially for
2827 plot() and replot(). Much more convenient now, especially for
2812 interactive use.
2828 interactive use.
2813
2829
2814 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2830 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2815 filenames.
2831 filenames.
2816
2832
2817 2002-06-02 Fernando Perez <fperez@colorado.edu>
2833 2002-06-02 Fernando Perez <fperez@colorado.edu>
2818
2834
2819 * IPython/Struct.py (Struct.__init__): modified to admit
2835 * IPython/Struct.py (Struct.__init__): modified to admit
2820 initialization via another struct.
2836 initialization via another struct.
2821
2837
2822 * IPython/genutils.py (SystemExec.__init__): New stateful
2838 * IPython/genutils.py (SystemExec.__init__): New stateful
2823 interface to xsys and bq. Useful for writing system scripts.
2839 interface to xsys and bq. Useful for writing system scripts.
2824
2840
2825 2002-05-30 Fernando Perez <fperez@colorado.edu>
2841 2002-05-30 Fernando Perez <fperez@colorado.edu>
2826
2842
2827 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2843 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2828 documents. This will make the user download smaller (it's getting
2844 documents. This will make the user download smaller (it's getting
2829 too big).
2845 too big).
2830
2846
2831 2002-05-29 Fernando Perez <fperez@colorado.edu>
2847 2002-05-29 Fernando Perez <fperez@colorado.edu>
2832
2848
2833 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2849 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2834 fix problems with shelve and pickle. Seems to work, but I don't
2850 fix problems with shelve and pickle. Seems to work, but I don't
2835 know if corner cases break it. Thanks to Mike Heeter
2851 know if corner cases break it. Thanks to Mike Heeter
2836 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
2852 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
2837
2853
2838 2002-05-24 Fernando Perez <fperez@colorado.edu>
2854 2002-05-24 Fernando Perez <fperez@colorado.edu>
2839
2855
2840 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
2856 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
2841 macros having broken.
2857 macros having broken.
2842
2858
2843 2002-05-21 Fernando Perez <fperez@colorado.edu>
2859 2002-05-21 Fernando Perez <fperez@colorado.edu>
2844
2860
2845 * IPython/Magic.py (Magic.magic_logstart): fixed recently
2861 * IPython/Magic.py (Magic.magic_logstart): fixed recently
2846 introduced logging bug: all history before logging started was
2862 introduced logging bug: all history before logging started was
2847 being written one character per line! This came from the redesign
2863 being written one character per line! This came from the redesign
2848 of the input history as a special list which slices to strings,
2864 of the input history as a special list which slices to strings,
2849 not to lists.
2865 not to lists.
2850
2866
2851 2002-05-20 Fernando Perez <fperez@colorado.edu>
2867 2002-05-20 Fernando Perez <fperez@colorado.edu>
2852
2868
2853 * IPython/Prompts.py (CachedOutput.__init__): made the color table
2869 * IPython/Prompts.py (CachedOutput.__init__): made the color table
2854 be an attribute of all classes in this module. The design of these
2870 be an attribute of all classes in this module. The design of these
2855 classes needs some serious overhauling.
2871 classes needs some serious overhauling.
2856
2872
2857 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
2873 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
2858 which was ignoring '_' in option names.
2874 which was ignoring '_' in option names.
2859
2875
2860 * IPython/ultraTB.py (FormattedTB.__init__): Changed
2876 * IPython/ultraTB.py (FormattedTB.__init__): Changed
2861 'Verbose_novars' to 'Context' and made it the new default. It's a
2877 'Verbose_novars' to 'Context' and made it the new default. It's a
2862 bit more readable and also safer than verbose.
2878 bit more readable and also safer than verbose.
2863
2879
2864 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
2880 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
2865 triple-quoted strings.
2881 triple-quoted strings.
2866
2882
2867 * IPython/OInspect.py (__all__): new module exposing the object
2883 * IPython/OInspect.py (__all__): new module exposing the object
2868 introspection facilities. Now the corresponding magics are dummy
2884 introspection facilities. Now the corresponding magics are dummy
2869 wrappers around this. Having this module will make it much easier
2885 wrappers around this. Having this module will make it much easier
2870 to put these functions into our modified pdb.
2886 to put these functions into our modified pdb.
2871 This new object inspector system uses the new colorizing module,
2887 This new object inspector system uses the new colorizing module,
2872 so source code and other things are nicely syntax highlighted.
2888 so source code and other things are nicely syntax highlighted.
2873
2889
2874 2002-05-18 Fernando Perez <fperez@colorado.edu>
2890 2002-05-18 Fernando Perez <fperez@colorado.edu>
2875
2891
2876 * IPython/ColorANSI.py: Split the coloring tools into a separate
2892 * IPython/ColorANSI.py: Split the coloring tools into a separate
2877 module so I can use them in other code easier (they were part of
2893 module so I can use them in other code easier (they were part of
2878 ultraTB).
2894 ultraTB).
2879
2895
2880 2002-05-17 Fernando Perez <fperez@colorado.edu>
2896 2002-05-17 Fernando Perez <fperez@colorado.edu>
2881
2897
2882 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2898 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2883 fixed it to set the global 'g' also to the called instance, as
2899 fixed it to set the global 'g' also to the called instance, as
2884 long as 'g' was still a gnuplot instance (so it doesn't overwrite
2900 long as 'g' was still a gnuplot instance (so it doesn't overwrite
2885 user's 'g' variables).
2901 user's 'g' variables).
2886
2902
2887 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
2903 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
2888 global variables (aliases to _ih,_oh) so that users which expect
2904 global variables (aliases to _ih,_oh) so that users which expect
2889 In[5] or Out[7] to work aren't unpleasantly surprised.
2905 In[5] or Out[7] to work aren't unpleasantly surprised.
2890 (InputList.__getslice__): new class to allow executing slices of
2906 (InputList.__getslice__): new class to allow executing slices of
2891 input history directly. Very simple class, complements the use of
2907 input history directly. Very simple class, complements the use of
2892 macros.
2908 macros.
2893
2909
2894 2002-05-16 Fernando Perez <fperez@colorado.edu>
2910 2002-05-16 Fernando Perez <fperez@colorado.edu>
2895
2911
2896 * setup.py (docdirbase): make doc directory be just doc/IPython
2912 * setup.py (docdirbase): make doc directory be just doc/IPython
2897 without version numbers, it will reduce clutter for users.
2913 without version numbers, it will reduce clutter for users.
2898
2914
2899 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
2915 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
2900 execfile call to prevent possible memory leak. See for details:
2916 execfile call to prevent possible memory leak. See for details:
2901 http://mail.python.org/pipermail/python-list/2002-February/088476.html
2917 http://mail.python.org/pipermail/python-list/2002-February/088476.html
2902
2918
2903 2002-05-15 Fernando Perez <fperez@colorado.edu>
2919 2002-05-15 Fernando Perez <fperez@colorado.edu>
2904
2920
2905 * IPython/Magic.py (Magic.magic_psource): made the object
2921 * IPython/Magic.py (Magic.magic_psource): made the object
2906 introspection names be more standard: pdoc, pdef, pfile and
2922 introspection names be more standard: pdoc, pdef, pfile and
2907 psource. They all print/page their output, and it makes
2923 psource. They all print/page their output, and it makes
2908 remembering them easier. Kept old names for compatibility as
2924 remembering them easier. Kept old names for compatibility as
2909 aliases.
2925 aliases.
2910
2926
2911 2002-05-14 Fernando Perez <fperez@colorado.edu>
2927 2002-05-14 Fernando Perez <fperez@colorado.edu>
2912
2928
2913 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
2929 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
2914 what the mouse problem was. The trick is to use gnuplot with temp
2930 what the mouse problem was. The trick is to use gnuplot with temp
2915 files and NOT with pipes (for data communication), because having
2931 files and NOT with pipes (for data communication), because having
2916 both pipes and the mouse on is bad news.
2932 both pipes and the mouse on is bad news.
2917
2933
2918 2002-05-13 Fernando Perez <fperez@colorado.edu>
2934 2002-05-13 Fernando Perez <fperez@colorado.edu>
2919
2935
2920 * IPython/Magic.py (Magic._ofind): fixed namespace order search
2936 * IPython/Magic.py (Magic._ofind): fixed namespace order search
2921 bug. Information would be reported about builtins even when
2937 bug. Information would be reported about builtins even when
2922 user-defined functions overrode them.
2938 user-defined functions overrode them.
2923
2939
2924 2002-05-11 Fernando Perez <fperez@colorado.edu>
2940 2002-05-11 Fernando Perez <fperez@colorado.edu>
2925
2941
2926 * IPython/__init__.py (__all__): removed FlexCompleter from
2942 * IPython/__init__.py (__all__): removed FlexCompleter from
2927 __all__ so that things don't fail in platforms without readline.
2943 __all__ so that things don't fail in platforms without readline.
2928
2944
2929 2002-05-10 Fernando Perez <fperez@colorado.edu>
2945 2002-05-10 Fernando Perez <fperez@colorado.edu>
2930
2946
2931 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
2947 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
2932 it requires Numeric, effectively making Numeric a dependency for
2948 it requires Numeric, effectively making Numeric a dependency for
2933 IPython.
2949 IPython.
2934
2950
2935 * Released 0.2.13
2951 * Released 0.2.13
2936
2952
2937 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
2953 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
2938 profiler interface. Now all the major options from the profiler
2954 profiler interface. Now all the major options from the profiler
2939 module are directly supported in IPython, both for single
2955 module are directly supported in IPython, both for single
2940 expressions (@prun) and for full programs (@run -p).
2956 expressions (@prun) and for full programs (@run -p).
2941
2957
2942 2002-05-09 Fernando Perez <fperez@colorado.edu>
2958 2002-05-09 Fernando Perez <fperez@colorado.edu>
2943
2959
2944 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
2960 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
2945 magic properly formatted for screen.
2961 magic properly formatted for screen.
2946
2962
2947 * setup.py (make_shortcut): Changed things to put pdf version in
2963 * setup.py (make_shortcut): Changed things to put pdf version in
2948 doc/ instead of doc/manual (had to change lyxport a bit).
2964 doc/ instead of doc/manual (had to change lyxport a bit).
2949
2965
2950 * IPython/Magic.py (Profile.string_stats): made profile runs go
2966 * IPython/Magic.py (Profile.string_stats): made profile runs go
2951 through pager (they are long and a pager allows searching, saving,
2967 through pager (they are long and a pager allows searching, saving,
2952 etc.)
2968 etc.)
2953
2969
2954 2002-05-08 Fernando Perez <fperez@colorado.edu>
2970 2002-05-08 Fernando Perez <fperez@colorado.edu>
2955
2971
2956 * Released 0.2.12
2972 * Released 0.2.12
2957
2973
2958 2002-05-06 Fernando Perez <fperez@colorado.edu>
2974 2002-05-06 Fernando Perez <fperez@colorado.edu>
2959
2975
2960 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
2976 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
2961 introduced); 'hist n1 n2' was broken.
2977 introduced); 'hist n1 n2' was broken.
2962 (Magic.magic_pdb): added optional on/off arguments to @pdb
2978 (Magic.magic_pdb): added optional on/off arguments to @pdb
2963 (Magic.magic_run): added option -i to @run, which executes code in
2979 (Magic.magic_run): added option -i to @run, which executes code in
2964 the IPython namespace instead of a clean one. Also added @irun as
2980 the IPython namespace instead of a clean one. Also added @irun as
2965 an alias to @run -i.
2981 an alias to @run -i.
2966
2982
2967 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2983 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2968 fixed (it didn't really do anything, the namespaces were wrong).
2984 fixed (it didn't really do anything, the namespaces were wrong).
2969
2985
2970 * IPython/Debugger.py (__init__): Added workaround for python 2.1
2986 * IPython/Debugger.py (__init__): Added workaround for python 2.1
2971
2987
2972 * IPython/__init__.py (__all__): Fixed package namespace, now
2988 * IPython/__init__.py (__all__): Fixed package namespace, now
2973 'import IPython' does give access to IPython.<all> as
2989 'import IPython' does give access to IPython.<all> as
2974 expected. Also renamed __release__ to Release.
2990 expected. Also renamed __release__ to Release.
2975
2991
2976 * IPython/Debugger.py (__license__): created new Pdb class which
2992 * IPython/Debugger.py (__license__): created new Pdb class which
2977 functions like a drop-in for the normal pdb.Pdb but does NOT
2993 functions like a drop-in for the normal pdb.Pdb but does NOT
2978 import readline by default. This way it doesn't muck up IPython's
2994 import readline by default. This way it doesn't muck up IPython's
2979 readline handling, and now tab-completion finally works in the
2995 readline handling, and now tab-completion finally works in the
2980 debugger -- sort of. It completes things globally visible, but the
2996 debugger -- sort of. It completes things globally visible, but the
2981 completer doesn't track the stack as pdb walks it. That's a bit
2997 completer doesn't track the stack as pdb walks it. That's a bit
2982 tricky, and I'll have to implement it later.
2998 tricky, and I'll have to implement it later.
2983
2999
2984 2002-05-05 Fernando Perez <fperez@colorado.edu>
3000 2002-05-05 Fernando Perez <fperez@colorado.edu>
2985
3001
2986 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3002 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
2987 magic docstrings when printed via ? (explicit \'s were being
3003 magic docstrings when printed via ? (explicit \'s were being
2988 printed).
3004 printed).
2989
3005
2990 * IPython/ipmaker.py (make_IPython): fixed namespace
3006 * IPython/ipmaker.py (make_IPython): fixed namespace
2991 identification bug. Now variables loaded via logs or command-line
3007 identification bug. Now variables loaded via logs or command-line
2992 files are recognized in the interactive namespace by @who.
3008 files are recognized in the interactive namespace by @who.
2993
3009
2994 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3010 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
2995 log replay system stemming from the string form of Structs.
3011 log replay system stemming from the string form of Structs.
2996
3012
2997 * IPython/Magic.py (Macro.__init__): improved macros to properly
3013 * IPython/Magic.py (Macro.__init__): improved macros to properly
2998 handle magic commands in them.
3014 handle magic commands in them.
2999 (Magic.magic_logstart): usernames are now expanded so 'logstart
3015 (Magic.magic_logstart): usernames are now expanded so 'logstart
3000 ~/mylog' now works.
3016 ~/mylog' now works.
3001
3017
3002 * IPython/iplib.py (complete): fixed bug where paths starting with
3018 * IPython/iplib.py (complete): fixed bug where paths starting with
3003 '/' would be completed as magic names.
3019 '/' would be completed as magic names.
3004
3020
3005 2002-05-04 Fernando Perez <fperez@colorado.edu>
3021 2002-05-04 Fernando Perez <fperez@colorado.edu>
3006
3022
3007 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3023 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3008 allow running full programs under the profiler's control.
3024 allow running full programs under the profiler's control.
3009
3025
3010 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3026 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3011 mode to report exceptions verbosely but without formatting
3027 mode to report exceptions verbosely but without formatting
3012 variables. This addresses the issue of ipython 'freezing' (it's
3028 variables. This addresses the issue of ipython 'freezing' (it's
3013 not frozen, but caught in an expensive formatting loop) when huge
3029 not frozen, but caught in an expensive formatting loop) when huge
3014 variables are in the context of an exception.
3030 variables are in the context of an exception.
3015 (VerboseTB.text): Added '--->' markers at line where exception was
3031 (VerboseTB.text): Added '--->' markers at line where exception was
3016 triggered. Much clearer to read, especially in NoColor modes.
3032 triggered. Much clearer to read, especially in NoColor modes.
3017
3033
3018 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3034 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3019 implemented in reverse when changing to the new parse_options().
3035 implemented in reverse when changing to the new parse_options().
3020
3036
3021 2002-05-03 Fernando Perez <fperez@colorado.edu>
3037 2002-05-03 Fernando Perez <fperez@colorado.edu>
3022
3038
3023 * IPython/Magic.py (Magic.parse_options): new function so that
3039 * IPython/Magic.py (Magic.parse_options): new function so that
3024 magics can parse options easier.
3040 magics can parse options easier.
3025 (Magic.magic_prun): new function similar to profile.run(),
3041 (Magic.magic_prun): new function similar to profile.run(),
3026 suggested by Chris Hart.
3042 suggested by Chris Hart.
3027 (Magic.magic_cd): fixed behavior so that it only changes if
3043 (Magic.magic_cd): fixed behavior so that it only changes if
3028 directory actually is in history.
3044 directory actually is in history.
3029
3045
3030 * IPython/usage.py (__doc__): added information about potential
3046 * IPython/usage.py (__doc__): added information about potential
3031 slowness of Verbose exception mode when there are huge data
3047 slowness of Verbose exception mode when there are huge data
3032 structures to be formatted (thanks to Archie Paulson).
3048 structures to be formatted (thanks to Archie Paulson).
3033
3049
3034 * IPython/ipmaker.py (make_IPython): Changed default logging
3050 * IPython/ipmaker.py (make_IPython): Changed default logging
3035 (when simply called with -log) to use curr_dir/ipython.log in
3051 (when simply called with -log) to use curr_dir/ipython.log in
3036 rotate mode. Fixed crash which was occuring with -log before
3052 rotate mode. Fixed crash which was occuring with -log before
3037 (thanks to Jim Boyle).
3053 (thanks to Jim Boyle).
3038
3054
3039 2002-05-01 Fernando Perez <fperez@colorado.edu>
3055 2002-05-01 Fernando Perez <fperez@colorado.edu>
3040
3056
3041 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3057 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3042 was nasty -- though somewhat of a corner case).
3058 was nasty -- though somewhat of a corner case).
3043
3059
3044 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3060 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3045 text (was a bug).
3061 text (was a bug).
3046
3062
3047 2002-04-30 Fernando Perez <fperez@colorado.edu>
3063 2002-04-30 Fernando Perez <fperez@colorado.edu>
3048
3064
3049 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3065 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3050 a print after ^D or ^C from the user so that the In[] prompt
3066 a print after ^D or ^C from the user so that the In[] prompt
3051 doesn't over-run the gnuplot one.
3067 doesn't over-run the gnuplot one.
3052
3068
3053 2002-04-29 Fernando Perez <fperez@colorado.edu>
3069 2002-04-29 Fernando Perez <fperez@colorado.edu>
3054
3070
3055 * Released 0.2.10
3071 * Released 0.2.10
3056
3072
3057 * IPython/__release__.py (version): get date dynamically.
3073 * IPython/__release__.py (version): get date dynamically.
3058
3074
3059 * Misc. documentation updates thanks to Arnd's comments. Also ran
3075 * Misc. documentation updates thanks to Arnd's comments. Also ran
3060 a full spellcheck on the manual (hadn't been done in a while).
3076 a full spellcheck on the manual (hadn't been done in a while).
3061
3077
3062 2002-04-27 Fernando Perez <fperez@colorado.edu>
3078 2002-04-27 Fernando Perez <fperez@colorado.edu>
3063
3079
3064 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3080 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3065 starting a log in mid-session would reset the input history list.
3081 starting a log in mid-session would reset the input history list.
3066
3082
3067 2002-04-26 Fernando Perez <fperez@colorado.edu>
3083 2002-04-26 Fernando Perez <fperez@colorado.edu>
3068
3084
3069 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3085 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3070 all files were being included in an update. Now anything in
3086 all files were being included in an update. Now anything in
3071 UserConfig that matches [A-Za-z]*.py will go (this excludes
3087 UserConfig that matches [A-Za-z]*.py will go (this excludes
3072 __init__.py)
3088 __init__.py)
3073
3089
3074 2002-04-25 Fernando Perez <fperez@colorado.edu>
3090 2002-04-25 Fernando Perez <fperez@colorado.edu>
3075
3091
3076 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3092 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3077 to __builtins__ so that any form of embedded or imported code can
3093 to __builtins__ so that any form of embedded or imported code can
3078 test for being inside IPython.
3094 test for being inside IPython.
3079
3095
3080 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3096 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3081 changed to GnuplotMagic because it's now an importable module,
3097 changed to GnuplotMagic because it's now an importable module,
3082 this makes the name follow that of the standard Gnuplot module.
3098 this makes the name follow that of the standard Gnuplot module.
3083 GnuplotMagic can now be loaded at any time in mid-session.
3099 GnuplotMagic can now be loaded at any time in mid-session.
3084
3100
3085 2002-04-24 Fernando Perez <fperez@colorado.edu>
3101 2002-04-24 Fernando Perez <fperez@colorado.edu>
3086
3102
3087 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3103 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3088 the globals (IPython has its own namespace) and the
3104 the globals (IPython has its own namespace) and the
3089 PhysicalQuantity stuff is much better anyway.
3105 PhysicalQuantity stuff is much better anyway.
3090
3106
3091 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3107 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3092 embedding example to standard user directory for
3108 embedding example to standard user directory for
3093 distribution. Also put it in the manual.
3109 distribution. Also put it in the manual.
3094
3110
3095 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3111 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3096 instance as first argument (so it doesn't rely on some obscure
3112 instance as first argument (so it doesn't rely on some obscure
3097 hidden global).
3113 hidden global).
3098
3114
3099 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3115 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3100 delimiters. While it prevents ().TAB from working, it allows
3116 delimiters. While it prevents ().TAB from working, it allows
3101 completions in open (... expressions. This is by far a more common
3117 completions in open (... expressions. This is by far a more common
3102 case.
3118 case.
3103
3119
3104 2002-04-23 Fernando Perez <fperez@colorado.edu>
3120 2002-04-23 Fernando Perez <fperez@colorado.edu>
3105
3121
3106 * IPython/Extensions/InterpreterPasteInput.py: new
3122 * IPython/Extensions/InterpreterPasteInput.py: new
3107 syntax-processing module for pasting lines with >>> or ... at the
3123 syntax-processing module for pasting lines with >>> or ... at the
3108 start.
3124 start.
3109
3125
3110 * IPython/Extensions/PhysicalQ_Interactive.py
3126 * IPython/Extensions/PhysicalQ_Interactive.py
3111 (PhysicalQuantityInteractive.__int__): fixed to work with either
3127 (PhysicalQuantityInteractive.__int__): fixed to work with either
3112 Numeric or math.
3128 Numeric or math.
3113
3129
3114 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3130 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3115 provided profiles. Now we have:
3131 provided profiles. Now we have:
3116 -math -> math module as * and cmath with its own namespace.
3132 -math -> math module as * and cmath with its own namespace.
3117 -numeric -> Numeric as *, plus gnuplot & grace
3133 -numeric -> Numeric as *, plus gnuplot & grace
3118 -physics -> same as before
3134 -physics -> same as before
3119
3135
3120 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3136 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3121 user-defined magics wouldn't be found by @magic if they were
3137 user-defined magics wouldn't be found by @magic if they were
3122 defined as class methods. Also cleaned up the namespace search
3138 defined as class methods. Also cleaned up the namespace search
3123 logic and the string building (to use %s instead of many repeated
3139 logic and the string building (to use %s instead of many repeated
3124 string adds).
3140 string adds).
3125
3141
3126 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3142 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3127 of user-defined magics to operate with class methods (cleaner, in
3143 of user-defined magics to operate with class methods (cleaner, in
3128 line with the gnuplot code).
3144 line with the gnuplot code).
3129
3145
3130 2002-04-22 Fernando Perez <fperez@colorado.edu>
3146 2002-04-22 Fernando Perez <fperez@colorado.edu>
3131
3147
3132 * setup.py: updated dependency list so that manual is updated when
3148 * setup.py: updated dependency list so that manual is updated when
3133 all included files change.
3149 all included files change.
3134
3150
3135 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3151 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3136 the delimiter removal option (the fix is ugly right now).
3152 the delimiter removal option (the fix is ugly right now).
3137
3153
3138 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3154 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3139 all of the math profile (quicker loading, no conflict between
3155 all of the math profile (quicker loading, no conflict between
3140 g-9.8 and g-gnuplot).
3156 g-9.8 and g-gnuplot).
3141
3157
3142 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3158 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3143 name of post-mortem files to IPython_crash_report.txt.
3159 name of post-mortem files to IPython_crash_report.txt.
3144
3160
3145 * Cleanup/update of the docs. Added all the new readline info and
3161 * Cleanup/update of the docs. Added all the new readline info and
3146 formatted all lists as 'real lists'.
3162 formatted all lists as 'real lists'.
3147
3163
3148 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3164 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3149 tab-completion options, since the full readline parse_and_bind is
3165 tab-completion options, since the full readline parse_and_bind is
3150 now accessible.
3166 now accessible.
3151
3167
3152 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3168 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3153 handling of readline options. Now users can specify any string to
3169 handling of readline options. Now users can specify any string to
3154 be passed to parse_and_bind(), as well as the delimiters to be
3170 be passed to parse_and_bind(), as well as the delimiters to be
3155 removed.
3171 removed.
3156 (InteractiveShell.__init__): Added __name__ to the global
3172 (InteractiveShell.__init__): Added __name__ to the global
3157 namespace so that things like Itpl which rely on its existence
3173 namespace so that things like Itpl which rely on its existence
3158 don't crash.
3174 don't crash.
3159 (InteractiveShell._prefilter): Defined the default with a _ so
3175 (InteractiveShell._prefilter): Defined the default with a _ so
3160 that prefilter() is easier to override, while the default one
3176 that prefilter() is easier to override, while the default one
3161 remains available.
3177 remains available.
3162
3178
3163 2002-04-18 Fernando Perez <fperez@colorado.edu>
3179 2002-04-18 Fernando Perez <fperez@colorado.edu>
3164
3180
3165 * Added information about pdb in the docs.
3181 * Added information about pdb in the docs.
3166
3182
3167 2002-04-17 Fernando Perez <fperez@colorado.edu>
3183 2002-04-17 Fernando Perez <fperez@colorado.edu>
3168
3184
3169 * IPython/ipmaker.py (make_IPython): added rc_override option to
3185 * IPython/ipmaker.py (make_IPython): added rc_override option to
3170 allow passing config options at creation time which may override
3186 allow passing config options at creation time which may override
3171 anything set in the config files or command line. This is
3187 anything set in the config files or command line. This is
3172 particularly useful for configuring embedded instances.
3188 particularly useful for configuring embedded instances.
3173
3189
3174 2002-04-15 Fernando Perez <fperez@colorado.edu>
3190 2002-04-15 Fernando Perez <fperez@colorado.edu>
3175
3191
3176 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3192 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3177 crash embedded instances because of the input cache falling out of
3193 crash embedded instances because of the input cache falling out of
3178 sync with the output counter.
3194 sync with the output counter.
3179
3195
3180 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3196 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3181 mode which calls pdb after an uncaught exception in IPython itself.
3197 mode which calls pdb after an uncaught exception in IPython itself.
3182
3198
3183 2002-04-14 Fernando Perez <fperez@colorado.edu>
3199 2002-04-14 Fernando Perez <fperez@colorado.edu>
3184
3200
3185 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3201 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3186 readline, fix it back after each call.
3202 readline, fix it back after each call.
3187
3203
3188 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3204 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3189 method to force all access via __call__(), which guarantees that
3205 method to force all access via __call__(), which guarantees that
3190 traceback references are properly deleted.
3206 traceback references are properly deleted.
3191
3207
3192 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3208 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3193 improve printing when pprint is in use.
3209 improve printing when pprint is in use.
3194
3210
3195 2002-04-13 Fernando Perez <fperez@colorado.edu>
3211 2002-04-13 Fernando Perez <fperez@colorado.edu>
3196
3212
3197 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3213 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3198 exceptions aren't caught anymore. If the user triggers one, he
3214 exceptions aren't caught anymore. If the user triggers one, he
3199 should know why he's doing it and it should go all the way up,
3215 should know why he's doing it and it should go all the way up,
3200 just like any other exception. So now @abort will fully kill the
3216 just like any other exception. So now @abort will fully kill the
3201 embedded interpreter and the embedding code (unless that happens
3217 embedded interpreter and the embedding code (unless that happens
3202 to catch SystemExit).
3218 to catch SystemExit).
3203
3219
3204 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3220 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3205 and a debugger() method to invoke the interactive pdb debugger
3221 and a debugger() method to invoke the interactive pdb debugger
3206 after printing exception information. Also added the corresponding
3222 after printing exception information. Also added the corresponding
3207 -pdb option and @pdb magic to control this feature, and updated
3223 -pdb option and @pdb magic to control this feature, and updated
3208 the docs. After a suggestion from Christopher Hart
3224 the docs. After a suggestion from Christopher Hart
3209 (hart-AT-caltech.edu).
3225 (hart-AT-caltech.edu).
3210
3226
3211 2002-04-12 Fernando Perez <fperez@colorado.edu>
3227 2002-04-12 Fernando Perez <fperez@colorado.edu>
3212
3228
3213 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3229 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3214 the exception handlers defined by the user (not the CrashHandler)
3230 the exception handlers defined by the user (not the CrashHandler)
3215 so that user exceptions don't trigger an ipython bug report.
3231 so that user exceptions don't trigger an ipython bug report.
3216
3232
3217 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3233 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3218 configurable (it should have always been so).
3234 configurable (it should have always been so).
3219
3235
3220 2002-03-26 Fernando Perez <fperez@colorado.edu>
3236 2002-03-26 Fernando Perez <fperez@colorado.edu>
3221
3237
3222 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3238 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3223 and there to fix embedding namespace issues. This should all be
3239 and there to fix embedding namespace issues. This should all be
3224 done in a more elegant way.
3240 done in a more elegant way.
3225
3241
3226 2002-03-25 Fernando Perez <fperez@colorado.edu>
3242 2002-03-25 Fernando Perez <fperez@colorado.edu>
3227
3243
3228 * IPython/genutils.py (get_home_dir): Try to make it work under
3244 * IPython/genutils.py (get_home_dir): Try to make it work under
3229 win9x also.
3245 win9x also.
3230
3246
3231 2002-03-20 Fernando Perez <fperez@colorado.edu>
3247 2002-03-20 Fernando Perez <fperez@colorado.edu>
3232
3248
3233 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3249 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3234 sys.displayhook untouched upon __init__.
3250 sys.displayhook untouched upon __init__.
3235
3251
3236 2002-03-19 Fernando Perez <fperez@colorado.edu>
3252 2002-03-19 Fernando Perez <fperez@colorado.edu>
3237
3253
3238 * Released 0.2.9 (for embedding bug, basically).
3254 * Released 0.2.9 (for embedding bug, basically).
3239
3255
3240 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3256 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3241 exceptions so that enclosing shell's state can be restored.
3257 exceptions so that enclosing shell's state can be restored.
3242
3258
3243 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3259 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3244 naming conventions in the .ipython/ dir.
3260 naming conventions in the .ipython/ dir.
3245
3261
3246 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3262 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3247 from delimiters list so filenames with - in them get expanded.
3263 from delimiters list so filenames with - in them get expanded.
3248
3264
3249 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3265 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3250 sys.displayhook not being properly restored after an embedded call.
3266 sys.displayhook not being properly restored after an embedded call.
3251
3267
3252 2002-03-18 Fernando Perez <fperez@colorado.edu>
3268 2002-03-18 Fernando Perez <fperez@colorado.edu>
3253
3269
3254 * Released 0.2.8
3270 * Released 0.2.8
3255
3271
3256 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3272 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3257 some files weren't being included in a -upgrade.
3273 some files weren't being included in a -upgrade.
3258 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3274 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3259 on' so that the first tab completes.
3275 on' so that the first tab completes.
3260 (InteractiveShell.handle_magic): fixed bug with spaces around
3276 (InteractiveShell.handle_magic): fixed bug with spaces around
3261 quotes breaking many magic commands.
3277 quotes breaking many magic commands.
3262
3278
3263 * setup.py: added note about ignoring the syntax error messages at
3279 * setup.py: added note about ignoring the syntax error messages at
3264 installation.
3280 installation.
3265
3281
3266 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3282 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3267 streamlining the gnuplot interface, now there's only one magic @gp.
3283 streamlining the gnuplot interface, now there's only one magic @gp.
3268
3284
3269 2002-03-17 Fernando Perez <fperez@colorado.edu>
3285 2002-03-17 Fernando Perez <fperez@colorado.edu>
3270
3286
3271 * IPython/UserConfig/magic_gnuplot.py: new name for the
3287 * IPython/UserConfig/magic_gnuplot.py: new name for the
3272 example-magic_pm.py file. Much enhanced system, now with a shell
3288 example-magic_pm.py file. Much enhanced system, now with a shell
3273 for communicating directly with gnuplot, one command at a time.
3289 for communicating directly with gnuplot, one command at a time.
3274
3290
3275 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3291 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3276 setting __name__=='__main__'.
3292 setting __name__=='__main__'.
3277
3293
3278 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3294 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3279 mini-shell for accessing gnuplot from inside ipython. Should
3295 mini-shell for accessing gnuplot from inside ipython. Should
3280 extend it later for grace access too. Inspired by Arnd's
3296 extend it later for grace access too. Inspired by Arnd's
3281 suggestion.
3297 suggestion.
3282
3298
3283 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3299 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3284 calling magic functions with () in their arguments. Thanks to Arnd
3300 calling magic functions with () in their arguments. Thanks to Arnd
3285 Baecker for pointing this to me.
3301 Baecker for pointing this to me.
3286
3302
3287 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3303 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3288 infinitely for integer or complex arrays (only worked with floats).
3304 infinitely for integer or complex arrays (only worked with floats).
3289
3305
3290 2002-03-16 Fernando Perez <fperez@colorado.edu>
3306 2002-03-16 Fernando Perez <fperez@colorado.edu>
3291
3307
3292 * setup.py: Merged setup and setup_windows into a single script
3308 * setup.py: Merged setup and setup_windows into a single script
3293 which properly handles things for windows users.
3309 which properly handles things for windows users.
3294
3310
3295 2002-03-15 Fernando Perez <fperez@colorado.edu>
3311 2002-03-15 Fernando Perez <fperez@colorado.edu>
3296
3312
3297 * Big change to the manual: now the magics are all automatically
3313 * Big change to the manual: now the magics are all automatically
3298 documented. This information is generated from their docstrings
3314 documented. This information is generated from their docstrings
3299 and put in a latex file included by the manual lyx file. This way
3315 and put in a latex file included by the manual lyx file. This way
3300 we get always up to date information for the magics. The manual
3316 we get always up to date information for the magics. The manual
3301 now also has proper version information, also auto-synced.
3317 now also has proper version information, also auto-synced.
3302
3318
3303 For this to work, an undocumented --magic_docstrings option was added.
3319 For this to work, an undocumented --magic_docstrings option was added.
3304
3320
3305 2002-03-13 Fernando Perez <fperez@colorado.edu>
3321 2002-03-13 Fernando Perez <fperez@colorado.edu>
3306
3322
3307 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3323 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3308 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3324 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3309
3325
3310 2002-03-12 Fernando Perez <fperez@colorado.edu>
3326 2002-03-12 Fernando Perez <fperez@colorado.edu>
3311
3327
3312 * IPython/ultraTB.py (TermColors): changed color escapes again to
3328 * IPython/ultraTB.py (TermColors): changed color escapes again to
3313 fix the (old, reintroduced) line-wrapping bug. Basically, if
3329 fix the (old, reintroduced) line-wrapping bug. Basically, if
3314 \001..\002 aren't given in the color escapes, lines get wrapped
3330 \001..\002 aren't given in the color escapes, lines get wrapped
3315 weirdly. But giving those screws up old xterms and emacs terms. So
3331 weirdly. But giving those screws up old xterms and emacs terms. So
3316 I added some logic for emacs terms to be ok, but I can't identify old
3332 I added some logic for emacs terms to be ok, but I can't identify old
3317 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3333 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3318
3334
3319 2002-03-10 Fernando Perez <fperez@colorado.edu>
3335 2002-03-10 Fernando Perez <fperez@colorado.edu>
3320
3336
3321 * IPython/usage.py (__doc__): Various documentation cleanups and
3337 * IPython/usage.py (__doc__): Various documentation cleanups and
3322 updates, both in usage docstrings and in the manual.
3338 updates, both in usage docstrings and in the manual.
3323
3339
3324 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3340 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3325 handling of caching. Set minimum acceptabe value for having a
3341 handling of caching. Set minimum acceptabe value for having a
3326 cache at 20 values.
3342 cache at 20 values.
3327
3343
3328 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3344 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3329 install_first_time function to a method, renamed it and added an
3345 install_first_time function to a method, renamed it and added an
3330 'upgrade' mode. Now people can update their config directory with
3346 'upgrade' mode. Now people can update their config directory with
3331 a simple command line switch (-upgrade, also new).
3347 a simple command line switch (-upgrade, also new).
3332
3348
3333 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3349 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3334 @file (convenient for automagic users under Python >= 2.2).
3350 @file (convenient for automagic users under Python >= 2.2).
3335 Removed @files (it seemed more like a plural than an abbrev. of
3351 Removed @files (it seemed more like a plural than an abbrev. of
3336 'file show').
3352 'file show').
3337
3353
3338 * IPython/iplib.py (install_first_time): Fixed crash if there were
3354 * IPython/iplib.py (install_first_time): Fixed crash if there were
3339 backup files ('~') in .ipython/ install directory.
3355 backup files ('~') in .ipython/ install directory.
3340
3356
3341 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3357 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3342 system. Things look fine, but these changes are fairly
3358 system. Things look fine, but these changes are fairly
3343 intrusive. Test them for a few days.
3359 intrusive. Test them for a few days.
3344
3360
3345 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3361 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3346 the prompts system. Now all in/out prompt strings are user
3362 the prompts system. Now all in/out prompt strings are user
3347 controllable. This is particularly useful for embedding, as one
3363 controllable. This is particularly useful for embedding, as one
3348 can tag embedded instances with particular prompts.
3364 can tag embedded instances with particular prompts.
3349
3365
3350 Also removed global use of sys.ps1/2, which now allows nested
3366 Also removed global use of sys.ps1/2, which now allows nested
3351 embeddings without any problems. Added command-line options for
3367 embeddings without any problems. Added command-line options for
3352 the prompt strings.
3368 the prompt strings.
3353
3369
3354 2002-03-08 Fernando Perez <fperez@colorado.edu>
3370 2002-03-08 Fernando Perez <fperez@colorado.edu>
3355
3371
3356 * IPython/UserConfig/example-embed-short.py (ipshell): added
3372 * IPython/UserConfig/example-embed-short.py (ipshell): added
3357 example file with the bare minimum code for embedding.
3373 example file with the bare minimum code for embedding.
3358
3374
3359 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3375 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3360 functionality for the embeddable shell to be activated/deactivated
3376 functionality for the embeddable shell to be activated/deactivated
3361 either globally or at each call.
3377 either globally or at each call.
3362
3378
3363 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3379 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3364 rewriting the prompt with '--->' for auto-inputs with proper
3380 rewriting the prompt with '--->' for auto-inputs with proper
3365 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3381 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3366 this is handled by the prompts class itself, as it should.
3382 this is handled by the prompts class itself, as it should.
3367
3383
3368 2002-03-05 Fernando Perez <fperez@colorado.edu>
3384 2002-03-05 Fernando Perez <fperez@colorado.edu>
3369
3385
3370 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3386 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3371 @logstart to avoid name clashes with the math log function.
3387 @logstart to avoid name clashes with the math log function.
3372
3388
3373 * Big updates to X/Emacs section of the manual.
3389 * Big updates to X/Emacs section of the manual.
3374
3390
3375 * Removed ipython_emacs. Milan explained to me how to pass
3391 * Removed ipython_emacs. Milan explained to me how to pass
3376 arguments to ipython through Emacs. Some day I'm going to end up
3392 arguments to ipython through Emacs. Some day I'm going to end up
3377 learning some lisp...
3393 learning some lisp...
3378
3394
3379 2002-03-04 Fernando Perez <fperez@colorado.edu>
3395 2002-03-04 Fernando Perez <fperez@colorado.edu>
3380
3396
3381 * IPython/ipython_emacs: Created script to be used as the
3397 * IPython/ipython_emacs: Created script to be used as the
3382 py-python-command Emacs variable so we can pass IPython
3398 py-python-command Emacs variable so we can pass IPython
3383 parameters. I can't figure out how to tell Emacs directly to pass
3399 parameters. I can't figure out how to tell Emacs directly to pass
3384 parameters to IPython, so a dummy shell script will do it.
3400 parameters to IPython, so a dummy shell script will do it.
3385
3401
3386 Other enhancements made for things to work better under Emacs'
3402 Other enhancements made for things to work better under Emacs'
3387 various types of terminals. Many thanks to Milan Zamazal
3403 various types of terminals. Many thanks to Milan Zamazal
3388 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3404 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3389
3405
3390 2002-03-01 Fernando Perez <fperez@colorado.edu>
3406 2002-03-01 Fernando Perez <fperez@colorado.edu>
3391
3407
3392 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3408 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3393 that loading of readline is now optional. This gives better
3409 that loading of readline is now optional. This gives better
3394 control to emacs users.
3410 control to emacs users.
3395
3411
3396 * IPython/ultraTB.py (__date__): Modified color escape sequences
3412 * IPython/ultraTB.py (__date__): Modified color escape sequences
3397 and now things work fine under xterm and in Emacs' term buffers
3413 and now things work fine under xterm and in Emacs' term buffers
3398 (though not shell ones). Well, in emacs you get colors, but all
3414 (though not shell ones). Well, in emacs you get colors, but all
3399 seem to be 'light' colors (no difference between dark and light
3415 seem to be 'light' colors (no difference between dark and light
3400 ones). But the garbage chars are gone, and also in xterms. It
3416 ones). But the garbage chars are gone, and also in xterms. It
3401 seems that now I'm using 'cleaner' ansi sequences.
3417 seems that now I'm using 'cleaner' ansi sequences.
3402
3418
3403 2002-02-21 Fernando Perez <fperez@colorado.edu>
3419 2002-02-21 Fernando Perez <fperez@colorado.edu>
3404
3420
3405 * Released 0.2.7 (mainly to publish the scoping fix).
3421 * Released 0.2.7 (mainly to publish the scoping fix).
3406
3422
3407 * IPython/Logger.py (Logger.logstate): added. A corresponding
3423 * IPython/Logger.py (Logger.logstate): added. A corresponding
3408 @logstate magic was created.
3424 @logstate magic was created.
3409
3425
3410 * IPython/Magic.py: fixed nested scoping problem under Python
3426 * IPython/Magic.py: fixed nested scoping problem under Python
3411 2.1.x (automagic wasn't working).
3427 2.1.x (automagic wasn't working).
3412
3428
3413 2002-02-20 Fernando Perez <fperez@colorado.edu>
3429 2002-02-20 Fernando Perez <fperez@colorado.edu>
3414
3430
3415 * Released 0.2.6.
3431 * Released 0.2.6.
3416
3432
3417 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3433 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3418 option so that logs can come out without any headers at all.
3434 option so that logs can come out without any headers at all.
3419
3435
3420 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3436 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3421 SciPy.
3437 SciPy.
3422
3438
3423 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3439 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3424 that embedded IPython calls don't require vars() to be explicitly
3440 that embedded IPython calls don't require vars() to be explicitly
3425 passed. Now they are extracted from the caller's frame (code
3441 passed. Now they are extracted from the caller's frame (code
3426 snatched from Eric Jones' weave). Added better documentation to
3442 snatched from Eric Jones' weave). Added better documentation to
3427 the section on embedding and the example file.
3443 the section on embedding and the example file.
3428
3444
3429 * IPython/genutils.py (page): Changed so that under emacs, it just
3445 * IPython/genutils.py (page): Changed so that under emacs, it just
3430 prints the string. You can then page up and down in the emacs
3446 prints the string. You can then page up and down in the emacs
3431 buffer itself. This is how the builtin help() works.
3447 buffer itself. This is how the builtin help() works.
3432
3448
3433 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3449 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3434 macro scoping: macros need to be executed in the user's namespace
3450 macro scoping: macros need to be executed in the user's namespace
3435 to work as if they had been typed by the user.
3451 to work as if they had been typed by the user.
3436
3452
3437 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3453 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3438 execute automatically (no need to type 'exec...'). They then
3454 execute automatically (no need to type 'exec...'). They then
3439 behave like 'true macros'. The printing system was also modified
3455 behave like 'true macros'. The printing system was also modified
3440 for this to work.
3456 for this to work.
3441
3457
3442 2002-02-19 Fernando Perez <fperez@colorado.edu>
3458 2002-02-19 Fernando Perez <fperez@colorado.edu>
3443
3459
3444 * IPython/genutils.py (page_file): new function for paging files
3460 * IPython/genutils.py (page_file): new function for paging files
3445 in an OS-independent way. Also necessary for file viewing to work
3461 in an OS-independent way. Also necessary for file viewing to work
3446 well inside Emacs buffers.
3462 well inside Emacs buffers.
3447 (page): Added checks for being in an emacs buffer.
3463 (page): Added checks for being in an emacs buffer.
3448 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3464 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3449 same bug in iplib.
3465 same bug in iplib.
3450
3466
3451 2002-02-18 Fernando Perez <fperez@colorado.edu>
3467 2002-02-18 Fernando Perez <fperez@colorado.edu>
3452
3468
3453 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3469 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3454 of readline so that IPython can work inside an Emacs buffer.
3470 of readline so that IPython can work inside an Emacs buffer.
3455
3471
3456 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3472 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3457 method signatures (they weren't really bugs, but it looks cleaner
3473 method signatures (they weren't really bugs, but it looks cleaner
3458 and keeps PyChecker happy).
3474 and keeps PyChecker happy).
3459
3475
3460 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3476 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3461 for implementing various user-defined hooks. Currently only
3477 for implementing various user-defined hooks. Currently only
3462 display is done.
3478 display is done.
3463
3479
3464 * IPython/Prompts.py (CachedOutput._display): changed display
3480 * IPython/Prompts.py (CachedOutput._display): changed display
3465 functions so that they can be dynamically changed by users easily.
3481 functions so that they can be dynamically changed by users easily.
3466
3482
3467 * IPython/Extensions/numeric_formats.py (num_display): added an
3483 * IPython/Extensions/numeric_formats.py (num_display): added an
3468 extension for printing NumPy arrays in flexible manners. It
3484 extension for printing NumPy arrays in flexible manners. It
3469 doesn't do anything yet, but all the structure is in
3485 doesn't do anything yet, but all the structure is in
3470 place. Ultimately the plan is to implement output format control
3486 place. Ultimately the plan is to implement output format control
3471 like in Octave.
3487 like in Octave.
3472
3488
3473 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3489 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3474 methods are found at run-time by all the automatic machinery.
3490 methods are found at run-time by all the automatic machinery.
3475
3491
3476 2002-02-17 Fernando Perez <fperez@colorado.edu>
3492 2002-02-17 Fernando Perez <fperez@colorado.edu>
3477
3493
3478 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3494 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3479 whole file a little.
3495 whole file a little.
3480
3496
3481 * ToDo: closed this document. Now there's a new_design.lyx
3497 * ToDo: closed this document. Now there's a new_design.lyx
3482 document for all new ideas. Added making a pdf of it for the
3498 document for all new ideas. Added making a pdf of it for the
3483 end-user distro.
3499 end-user distro.
3484
3500
3485 * IPython/Logger.py (Logger.switch_log): Created this to replace
3501 * IPython/Logger.py (Logger.switch_log): Created this to replace
3486 logon() and logoff(). It also fixes a nasty crash reported by
3502 logon() and logoff(). It also fixes a nasty crash reported by
3487 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3503 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3488
3504
3489 * IPython/iplib.py (complete): got auto-completion to work with
3505 * IPython/iplib.py (complete): got auto-completion to work with
3490 automagic (I had wanted this for a long time).
3506 automagic (I had wanted this for a long time).
3491
3507
3492 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3508 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3493 to @file, since file() is now a builtin and clashes with automagic
3509 to @file, since file() is now a builtin and clashes with automagic
3494 for @file.
3510 for @file.
3495
3511
3496 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3512 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3497 of this was previously in iplib, which had grown to more than 2000
3513 of this was previously in iplib, which had grown to more than 2000
3498 lines, way too long. No new functionality, but it makes managing
3514 lines, way too long. No new functionality, but it makes managing
3499 the code a bit easier.
3515 the code a bit easier.
3500
3516
3501 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3517 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3502 information to crash reports.
3518 information to crash reports.
3503
3519
3504 2002-02-12 Fernando Perez <fperez@colorado.edu>
3520 2002-02-12 Fernando Perez <fperez@colorado.edu>
3505
3521
3506 * Released 0.2.5.
3522 * Released 0.2.5.
3507
3523
3508 2002-02-11 Fernando Perez <fperez@colorado.edu>
3524 2002-02-11 Fernando Perez <fperez@colorado.edu>
3509
3525
3510 * Wrote a relatively complete Windows installer. It puts
3526 * Wrote a relatively complete Windows installer. It puts
3511 everything in place, creates Start Menu entries and fixes the
3527 everything in place, creates Start Menu entries and fixes the
3512 color issues. Nothing fancy, but it works.
3528 color issues. Nothing fancy, but it works.
3513
3529
3514 2002-02-10 Fernando Perez <fperez@colorado.edu>
3530 2002-02-10 Fernando Perez <fperez@colorado.edu>
3515
3531
3516 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3532 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3517 os.path.expanduser() call so that we can type @run ~/myfile.py and
3533 os.path.expanduser() call so that we can type @run ~/myfile.py and
3518 have thigs work as expected.
3534 have thigs work as expected.
3519
3535
3520 * IPython/genutils.py (page): fixed exception handling so things
3536 * IPython/genutils.py (page): fixed exception handling so things
3521 work both in Unix and Windows correctly. Quitting a pager triggers
3537 work both in Unix and Windows correctly. Quitting a pager triggers
3522 an IOError/broken pipe in Unix, and in windows not finding a pager
3538 an IOError/broken pipe in Unix, and in windows not finding a pager
3523 is also an IOError, so I had to actually look at the return value
3539 is also an IOError, so I had to actually look at the return value
3524 of the exception, not just the exception itself. Should be ok now.
3540 of the exception, not just the exception itself. Should be ok now.
3525
3541
3526 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3542 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3527 modified to allow case-insensitive color scheme changes.
3543 modified to allow case-insensitive color scheme changes.
3528
3544
3529 2002-02-09 Fernando Perez <fperez@colorado.edu>
3545 2002-02-09 Fernando Perez <fperez@colorado.edu>
3530
3546
3531 * IPython/genutils.py (native_line_ends): new function to leave
3547 * IPython/genutils.py (native_line_ends): new function to leave
3532 user config files with os-native line-endings.
3548 user config files with os-native line-endings.
3533
3549
3534 * README and manual updates.
3550 * README and manual updates.
3535
3551
3536 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3552 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3537 instead of StringType to catch Unicode strings.
3553 instead of StringType to catch Unicode strings.
3538
3554
3539 * IPython/genutils.py (filefind): fixed bug for paths with
3555 * IPython/genutils.py (filefind): fixed bug for paths with
3540 embedded spaces (very common in Windows).
3556 embedded spaces (very common in Windows).
3541
3557
3542 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3558 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3543 files under Windows, so that they get automatically associated
3559 files under Windows, so that they get automatically associated
3544 with a text editor. Windows makes it a pain to handle
3560 with a text editor. Windows makes it a pain to handle
3545 extension-less files.
3561 extension-less files.
3546
3562
3547 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3563 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3548 warning about readline only occur for Posix. In Windows there's no
3564 warning about readline only occur for Posix. In Windows there's no
3549 way to get readline, so why bother with the warning.
3565 way to get readline, so why bother with the warning.
3550
3566
3551 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3567 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3552 for __str__ instead of dir(self), since dir() changed in 2.2.
3568 for __str__ instead of dir(self), since dir() changed in 2.2.
3553
3569
3554 * Ported to Windows! Tested on XP, I suspect it should work fine
3570 * Ported to Windows! Tested on XP, I suspect it should work fine
3555 on NT/2000, but I don't think it will work on 98 et al. That
3571 on NT/2000, but I don't think it will work on 98 et al. That
3556 series of Windows is such a piece of junk anyway that I won't try
3572 series of Windows is such a piece of junk anyway that I won't try
3557 porting it there. The XP port was straightforward, showed a few
3573 porting it there. The XP port was straightforward, showed a few
3558 bugs here and there (fixed all), in particular some string
3574 bugs here and there (fixed all), in particular some string
3559 handling stuff which required considering Unicode strings (which
3575 handling stuff which required considering Unicode strings (which
3560 Windows uses). This is good, but hasn't been too tested :) No
3576 Windows uses). This is good, but hasn't been too tested :) No
3561 fancy installer yet, I'll put a note in the manual so people at
3577 fancy installer yet, I'll put a note in the manual so people at
3562 least make manually a shortcut.
3578 least make manually a shortcut.
3563
3579
3564 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3580 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3565 into a single one, "colors". This now controls both prompt and
3581 into a single one, "colors". This now controls both prompt and
3566 exception color schemes, and can be changed both at startup
3582 exception color schemes, and can be changed both at startup
3567 (either via command-line switches or via ipythonrc files) and at
3583 (either via command-line switches or via ipythonrc files) and at
3568 runtime, with @colors.
3584 runtime, with @colors.
3569 (Magic.magic_run): renamed @prun to @run and removed the old
3585 (Magic.magic_run): renamed @prun to @run and removed the old
3570 @run. The two were too similar to warrant keeping both.
3586 @run. The two were too similar to warrant keeping both.
3571
3587
3572 2002-02-03 Fernando Perez <fperez@colorado.edu>
3588 2002-02-03 Fernando Perez <fperez@colorado.edu>
3573
3589
3574 * IPython/iplib.py (install_first_time): Added comment on how to
3590 * IPython/iplib.py (install_first_time): Added comment on how to
3575 configure the color options for first-time users. Put a <return>
3591 configure the color options for first-time users. Put a <return>
3576 request at the end so that small-terminal users get a chance to
3592 request at the end so that small-terminal users get a chance to
3577 read the startup info.
3593 read the startup info.
3578
3594
3579 2002-01-23 Fernando Perez <fperez@colorado.edu>
3595 2002-01-23 Fernando Perez <fperez@colorado.edu>
3580
3596
3581 * IPython/iplib.py (CachedOutput.update): Changed output memory
3597 * IPython/iplib.py (CachedOutput.update): Changed output memory
3582 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3598 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3583 input history we still use _i. Did this b/c these variable are
3599 input history we still use _i. Did this b/c these variable are
3584 very commonly used in interactive work, so the less we need to
3600 very commonly used in interactive work, so the less we need to
3585 type the better off we are.
3601 type the better off we are.
3586 (Magic.magic_prun): updated @prun to better handle the namespaces
3602 (Magic.magic_prun): updated @prun to better handle the namespaces
3587 the file will run in, including a fix for __name__ not being set
3603 the file will run in, including a fix for __name__ not being set
3588 before.
3604 before.
3589
3605
3590 2002-01-20 Fernando Perez <fperez@colorado.edu>
3606 2002-01-20 Fernando Perez <fperez@colorado.edu>
3591
3607
3592 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3608 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3593 extra garbage for Python 2.2. Need to look more carefully into
3609 extra garbage for Python 2.2. Need to look more carefully into
3594 this later.
3610 this later.
3595
3611
3596 2002-01-19 Fernando Perez <fperez@colorado.edu>
3612 2002-01-19 Fernando Perez <fperez@colorado.edu>
3597
3613
3598 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3614 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3599 display SyntaxError exceptions properly formatted when they occur
3615 display SyntaxError exceptions properly formatted when they occur
3600 (they can be triggered by imported code).
3616 (they can be triggered by imported code).
3601
3617
3602 2002-01-18 Fernando Perez <fperez@colorado.edu>
3618 2002-01-18 Fernando Perez <fperez@colorado.edu>
3603
3619
3604 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3620 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3605 SyntaxError exceptions are reported nicely formatted, instead of
3621 SyntaxError exceptions are reported nicely formatted, instead of
3606 spitting out only offset information as before.
3622 spitting out only offset information as before.
3607 (Magic.magic_prun): Added the @prun function for executing
3623 (Magic.magic_prun): Added the @prun function for executing
3608 programs with command line args inside IPython.
3624 programs with command line args inside IPython.
3609
3625
3610 2002-01-16 Fernando Perez <fperez@colorado.edu>
3626 2002-01-16 Fernando Perez <fperez@colorado.edu>
3611
3627
3612 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3628 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3613 to *not* include the last item given in a range. This brings their
3629 to *not* include the last item given in a range. This brings their
3614 behavior in line with Python's slicing:
3630 behavior in line with Python's slicing:
3615 a[n1:n2] -> a[n1]...a[n2-1]
3631 a[n1:n2] -> a[n1]...a[n2-1]
3616 It may be a bit less convenient, but I prefer to stick to Python's
3632 It may be a bit less convenient, but I prefer to stick to Python's
3617 conventions *everywhere*, so users never have to wonder.
3633 conventions *everywhere*, so users never have to wonder.
3618 (Magic.magic_macro): Added @macro function to ease the creation of
3634 (Magic.magic_macro): Added @macro function to ease the creation of
3619 macros.
3635 macros.
3620
3636
3621 2002-01-05 Fernando Perez <fperez@colorado.edu>
3637 2002-01-05 Fernando Perez <fperez@colorado.edu>
3622
3638
3623 * Released 0.2.4.
3639 * Released 0.2.4.
3624
3640
3625 * IPython/iplib.py (Magic.magic_pdef):
3641 * IPython/iplib.py (Magic.magic_pdef):
3626 (InteractiveShell.safe_execfile): report magic lines and error
3642 (InteractiveShell.safe_execfile): report magic lines and error
3627 lines without line numbers so one can easily copy/paste them for
3643 lines without line numbers so one can easily copy/paste them for
3628 re-execution.
3644 re-execution.
3629
3645
3630 * Updated manual with recent changes.
3646 * Updated manual with recent changes.
3631
3647
3632 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3648 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3633 docstring printing when class? is called. Very handy for knowing
3649 docstring printing when class? is called. Very handy for knowing
3634 how to create class instances (as long as __init__ is well
3650 how to create class instances (as long as __init__ is well
3635 documented, of course :)
3651 documented, of course :)
3636 (Magic.magic_doc): print both class and constructor docstrings.
3652 (Magic.magic_doc): print both class and constructor docstrings.
3637 (Magic.magic_pdef): give constructor info if passed a class and
3653 (Magic.magic_pdef): give constructor info if passed a class and
3638 __call__ info for callable object instances.
3654 __call__ info for callable object instances.
3639
3655
3640 2002-01-04 Fernando Perez <fperez@colorado.edu>
3656 2002-01-04 Fernando Perez <fperez@colorado.edu>
3641
3657
3642 * Made deep_reload() off by default. It doesn't always work
3658 * Made deep_reload() off by default. It doesn't always work
3643 exactly as intended, so it's probably safer to have it off. It's
3659 exactly as intended, so it's probably safer to have it off. It's
3644 still available as dreload() anyway, so nothing is lost.
3660 still available as dreload() anyway, so nothing is lost.
3645
3661
3646 2002-01-02 Fernando Perez <fperez@colorado.edu>
3662 2002-01-02 Fernando Perez <fperez@colorado.edu>
3647
3663
3648 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3664 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3649 so I wanted an updated release).
3665 so I wanted an updated release).
3650
3666
3651 2001-12-27 Fernando Perez <fperez@colorado.edu>
3667 2001-12-27 Fernando Perez <fperez@colorado.edu>
3652
3668
3653 * IPython/iplib.py (InteractiveShell.interact): Added the original
3669 * IPython/iplib.py (InteractiveShell.interact): Added the original
3654 code from 'code.py' for this module in order to change the
3670 code from 'code.py' for this module in order to change the
3655 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3671 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3656 the history cache would break when the user hit Ctrl-C, and
3672 the history cache would break when the user hit Ctrl-C, and
3657 interact() offers no way to add any hooks to it.
3673 interact() offers no way to add any hooks to it.
3658
3674
3659 2001-12-23 Fernando Perez <fperez@colorado.edu>
3675 2001-12-23 Fernando Perez <fperez@colorado.edu>
3660
3676
3661 * setup.py: added check for 'MANIFEST' before trying to remove
3677 * setup.py: added check for 'MANIFEST' before trying to remove
3662 it. Thanks to Sean Reifschneider.
3678 it. Thanks to Sean Reifschneider.
3663
3679
3664 2001-12-22 Fernando Perez <fperez@colorado.edu>
3680 2001-12-22 Fernando Perez <fperez@colorado.edu>
3665
3681
3666 * Released 0.2.2.
3682 * Released 0.2.2.
3667
3683
3668 * Finished (reasonably) writing the manual. Later will add the
3684 * Finished (reasonably) writing the manual. Later will add the
3669 python-standard navigation stylesheets, but for the time being
3685 python-standard navigation stylesheets, but for the time being
3670 it's fairly complete. Distribution will include html and pdf
3686 it's fairly complete. Distribution will include html and pdf
3671 versions.
3687 versions.
3672
3688
3673 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3689 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3674 (MayaVi author).
3690 (MayaVi author).
3675
3691
3676 2001-12-21 Fernando Perez <fperez@colorado.edu>
3692 2001-12-21 Fernando Perez <fperez@colorado.edu>
3677
3693
3678 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3694 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3679 good public release, I think (with the manual and the distutils
3695 good public release, I think (with the manual and the distutils
3680 installer). The manual can use some work, but that can go
3696 installer). The manual can use some work, but that can go
3681 slowly. Otherwise I think it's quite nice for end users. Next
3697 slowly. Otherwise I think it's quite nice for end users. Next
3682 summer, rewrite the guts of it...
3698 summer, rewrite the guts of it...
3683
3699
3684 * Changed format of ipythonrc files to use whitespace as the
3700 * Changed format of ipythonrc files to use whitespace as the
3685 separator instead of an explicit '='. Cleaner.
3701 separator instead of an explicit '='. Cleaner.
3686
3702
3687 2001-12-20 Fernando Perez <fperez@colorado.edu>
3703 2001-12-20 Fernando Perez <fperez@colorado.edu>
3688
3704
3689 * Started a manual in LyX. For now it's just a quick merge of the
3705 * Started a manual in LyX. For now it's just a quick merge of the
3690 various internal docstrings and READMEs. Later it may grow into a
3706 various internal docstrings and READMEs. Later it may grow into a
3691 nice, full-blown manual.
3707 nice, full-blown manual.
3692
3708
3693 * Set up a distutils based installer. Installation should now be
3709 * Set up a distutils based installer. Installation should now be
3694 trivially simple for end-users.
3710 trivially simple for end-users.
3695
3711
3696 2001-12-11 Fernando Perez <fperez@colorado.edu>
3712 2001-12-11 Fernando Perez <fperez@colorado.edu>
3697
3713
3698 * Released 0.2.0. First public release, announced it at
3714 * Released 0.2.0. First public release, announced it at
3699 comp.lang.python. From now on, just bugfixes...
3715 comp.lang.python. From now on, just bugfixes...
3700
3716
3701 * Went through all the files, set copyright/license notices and
3717 * Went through all the files, set copyright/license notices and
3702 cleaned up things. Ready for release.
3718 cleaned up things. Ready for release.
3703
3719
3704 2001-12-10 Fernando Perez <fperez@colorado.edu>
3720 2001-12-10 Fernando Perez <fperez@colorado.edu>
3705
3721
3706 * Changed the first-time installer not to use tarfiles. It's more
3722 * Changed the first-time installer not to use tarfiles. It's more
3707 robust now and less unix-dependent. Also makes it easier for
3723 robust now and less unix-dependent. Also makes it easier for
3708 people to later upgrade versions.
3724 people to later upgrade versions.
3709
3725
3710 * Changed @exit to @abort to reflect the fact that it's pretty
3726 * Changed @exit to @abort to reflect the fact that it's pretty
3711 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3727 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3712 becomes significant only when IPyhton is embedded: in that case,
3728 becomes significant only when IPyhton is embedded: in that case,
3713 C-D closes IPython only, but @abort kills the enclosing program
3729 C-D closes IPython only, but @abort kills the enclosing program
3714 too (unless it had called IPython inside a try catching
3730 too (unless it had called IPython inside a try catching
3715 SystemExit).
3731 SystemExit).
3716
3732
3717 * Created Shell module which exposes the actuall IPython Shell
3733 * Created Shell module which exposes the actuall IPython Shell
3718 classes, currently the normal and the embeddable one. This at
3734 classes, currently the normal and the embeddable one. This at
3719 least offers a stable interface we won't need to change when
3735 least offers a stable interface we won't need to change when
3720 (later) the internals are rewritten. That rewrite will be confined
3736 (later) the internals are rewritten. That rewrite will be confined
3721 to iplib and ipmaker, but the Shell interface should remain as is.
3737 to iplib and ipmaker, but the Shell interface should remain as is.
3722
3738
3723 * Added embed module which offers an embeddable IPShell object,
3739 * Added embed module which offers an embeddable IPShell object,
3724 useful to fire up IPython *inside* a running program. Great for
3740 useful to fire up IPython *inside* a running program. Great for
3725 debugging or dynamical data analysis.
3741 debugging or dynamical data analysis.
3726
3742
3727 2001-12-08 Fernando Perez <fperez@colorado.edu>
3743 2001-12-08 Fernando Perez <fperez@colorado.edu>
3728
3744
3729 * Fixed small bug preventing seeing info from methods of defined
3745 * Fixed small bug preventing seeing info from methods of defined
3730 objects (incorrect namespace in _ofind()).
3746 objects (incorrect namespace in _ofind()).
3731
3747
3732 * Documentation cleanup. Moved the main usage docstrings to a
3748 * Documentation cleanup. Moved the main usage docstrings to a
3733 separate file, usage.py (cleaner to maintain, and hopefully in the
3749 separate file, usage.py (cleaner to maintain, and hopefully in the
3734 future some perlpod-like way of producing interactive, man and
3750 future some perlpod-like way of producing interactive, man and
3735 html docs out of it will be found).
3751 html docs out of it will be found).
3736
3752
3737 * Added @profile to see your profile at any time.
3753 * Added @profile to see your profile at any time.
3738
3754
3739 * Added @p as an alias for 'print'. It's especially convenient if
3755 * Added @p as an alias for 'print'. It's especially convenient if
3740 using automagic ('p x' prints x).
3756 using automagic ('p x' prints x).
3741
3757
3742 * Small cleanups and fixes after a pychecker run.
3758 * Small cleanups and fixes after a pychecker run.
3743
3759
3744 * Changed the @cd command to handle @cd - and @cd -<n> for
3760 * Changed the @cd command to handle @cd - and @cd -<n> for
3745 visiting any directory in _dh.
3761 visiting any directory in _dh.
3746
3762
3747 * Introduced _dh, a history of visited directories. @dhist prints
3763 * Introduced _dh, a history of visited directories. @dhist prints
3748 it out with numbers.
3764 it out with numbers.
3749
3765
3750 2001-12-07 Fernando Perez <fperez@colorado.edu>
3766 2001-12-07 Fernando Perez <fperez@colorado.edu>
3751
3767
3752 * Released 0.1.22
3768 * Released 0.1.22
3753
3769
3754 * Made initialization a bit more robust against invalid color
3770 * Made initialization a bit more robust against invalid color
3755 options in user input (exit, not traceback-crash).
3771 options in user input (exit, not traceback-crash).
3756
3772
3757 * Changed the bug crash reporter to write the report only in the
3773 * Changed the bug crash reporter to write the report only in the
3758 user's .ipython directory. That way IPython won't litter people's
3774 user's .ipython directory. That way IPython won't litter people's
3759 hard disks with crash files all over the place. Also print on
3775 hard disks with crash files all over the place. Also print on
3760 screen the necessary mail command.
3776 screen the necessary mail command.
3761
3777
3762 * With the new ultraTB, implemented LightBG color scheme for light
3778 * With the new ultraTB, implemented LightBG color scheme for light
3763 background terminals. A lot of people like white backgrounds, so I
3779 background terminals. A lot of people like white backgrounds, so I
3764 guess we should at least give them something readable.
3780 guess we should at least give them something readable.
3765
3781
3766 2001-12-06 Fernando Perez <fperez@colorado.edu>
3782 2001-12-06 Fernando Perez <fperez@colorado.edu>
3767
3783
3768 * Modified the structure of ultraTB. Now there's a proper class
3784 * Modified the structure of ultraTB. Now there's a proper class
3769 for tables of color schemes which allow adding schemes easily and
3785 for tables of color schemes which allow adding schemes easily and
3770 switching the active scheme without creating a new instance every
3786 switching the active scheme without creating a new instance every
3771 time (which was ridiculous). The syntax for creating new schemes
3787 time (which was ridiculous). The syntax for creating new schemes
3772 is also cleaner. I think ultraTB is finally done, with a clean
3788 is also cleaner. I think ultraTB is finally done, with a clean
3773 class structure. Names are also much cleaner (now there's proper
3789 class structure. Names are also much cleaner (now there's proper
3774 color tables, no need for every variable to also have 'color' in
3790 color tables, no need for every variable to also have 'color' in
3775 its name).
3791 its name).
3776
3792
3777 * Broke down genutils into separate files. Now genutils only
3793 * Broke down genutils into separate files. Now genutils only
3778 contains utility functions, and classes have been moved to their
3794 contains utility functions, and classes have been moved to their
3779 own files (they had enough independent functionality to warrant
3795 own files (they had enough independent functionality to warrant
3780 it): ConfigLoader, OutputTrap, Struct.
3796 it): ConfigLoader, OutputTrap, Struct.
3781
3797
3782 2001-12-05 Fernando Perez <fperez@colorado.edu>
3798 2001-12-05 Fernando Perez <fperez@colorado.edu>
3783
3799
3784 * IPython turns 21! Released version 0.1.21, as a candidate for
3800 * IPython turns 21! Released version 0.1.21, as a candidate for
3785 public consumption. If all goes well, release in a few days.
3801 public consumption. If all goes well, release in a few days.
3786
3802
3787 * Fixed path bug (files in Extensions/ directory wouldn't be found
3803 * Fixed path bug (files in Extensions/ directory wouldn't be found
3788 unless IPython/ was explicitly in sys.path).
3804 unless IPython/ was explicitly in sys.path).
3789
3805
3790 * Extended the FlexCompleter class as MagicCompleter to allow
3806 * Extended the FlexCompleter class as MagicCompleter to allow
3791 completion of @-starting lines.
3807 completion of @-starting lines.
3792
3808
3793 * Created __release__.py file as a central repository for release
3809 * Created __release__.py file as a central repository for release
3794 info that other files can read from.
3810 info that other files can read from.
3795
3811
3796 * Fixed small bug in logging: when logging was turned on in
3812 * Fixed small bug in logging: when logging was turned on in
3797 mid-session, old lines with special meanings (!@?) were being
3813 mid-session, old lines with special meanings (!@?) were being
3798 logged without the prepended comment, which is necessary since
3814 logged without the prepended comment, which is necessary since
3799 they are not truly valid python syntax. This should make session
3815 they are not truly valid python syntax. This should make session
3800 restores produce less errors.
3816 restores produce less errors.
3801
3817
3802 * The namespace cleanup forced me to make a FlexCompleter class
3818 * The namespace cleanup forced me to make a FlexCompleter class
3803 which is nothing but a ripoff of rlcompleter, but with selectable
3819 which is nothing but a ripoff of rlcompleter, but with selectable
3804 namespace (rlcompleter only works in __main__.__dict__). I'll try
3820 namespace (rlcompleter only works in __main__.__dict__). I'll try
3805 to submit a note to the authors to see if this change can be
3821 to submit a note to the authors to see if this change can be
3806 incorporated in future rlcompleter releases (Dec.6: done)
3822 incorporated in future rlcompleter releases (Dec.6: done)
3807
3823
3808 * More fixes to namespace handling. It was a mess! Now all
3824 * More fixes to namespace handling. It was a mess! Now all
3809 explicit references to __main__.__dict__ are gone (except when
3825 explicit references to __main__.__dict__ are gone (except when
3810 really needed) and everything is handled through the namespace
3826 really needed) and everything is handled through the namespace
3811 dicts in the IPython instance. We seem to be getting somewhere
3827 dicts in the IPython instance. We seem to be getting somewhere
3812 with this, finally...
3828 with this, finally...
3813
3829
3814 * Small documentation updates.
3830 * Small documentation updates.
3815
3831
3816 * Created the Extensions directory under IPython (with an
3832 * Created the Extensions directory under IPython (with an
3817 __init__.py). Put the PhysicalQ stuff there. This directory should
3833 __init__.py). Put the PhysicalQ stuff there. This directory should
3818 be used for all special-purpose extensions.
3834 be used for all special-purpose extensions.
3819
3835
3820 * File renaming:
3836 * File renaming:
3821 ipythonlib --> ipmaker
3837 ipythonlib --> ipmaker
3822 ipplib --> iplib
3838 ipplib --> iplib
3823 This makes a bit more sense in terms of what these files actually do.
3839 This makes a bit more sense in terms of what these files actually do.
3824
3840
3825 * Moved all the classes and functions in ipythonlib to ipplib, so
3841 * Moved all the classes and functions in ipythonlib to ipplib, so
3826 now ipythonlib only has make_IPython(). This will ease up its
3842 now ipythonlib only has make_IPython(). This will ease up its
3827 splitting in smaller functional chunks later.
3843 splitting in smaller functional chunks later.
3828
3844
3829 * Cleaned up (done, I think) output of @whos. Better column
3845 * Cleaned up (done, I think) output of @whos. Better column
3830 formatting, and now shows str(var) for as much as it can, which is
3846 formatting, and now shows str(var) for as much as it can, which is
3831 typically what one gets with a 'print var'.
3847 typically what one gets with a 'print var'.
3832
3848
3833 2001-12-04 Fernando Perez <fperez@colorado.edu>
3849 2001-12-04 Fernando Perez <fperez@colorado.edu>
3834
3850
3835 * Fixed namespace problems. Now builtin/IPyhton/user names get
3851 * Fixed namespace problems. Now builtin/IPyhton/user names get
3836 properly reported in their namespace. Internal namespace handling
3852 properly reported in their namespace. Internal namespace handling
3837 is finally getting decent (not perfect yet, but much better than
3853 is finally getting decent (not perfect yet, but much better than
3838 the ad-hoc mess we had).
3854 the ad-hoc mess we had).
3839
3855
3840 * Removed -exit option. If people just want to run a python
3856 * Removed -exit option. If people just want to run a python
3841 script, that's what the normal interpreter is for. Less
3857 script, that's what the normal interpreter is for. Less
3842 unnecessary options, less chances for bugs.
3858 unnecessary options, less chances for bugs.
3843
3859
3844 * Added a crash handler which generates a complete post-mortem if
3860 * Added a crash handler which generates a complete post-mortem if
3845 IPython crashes. This will help a lot in tracking bugs down the
3861 IPython crashes. This will help a lot in tracking bugs down the
3846 road.
3862 road.
3847
3863
3848 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
3864 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
3849 which were boud to functions being reassigned would bypass the
3865 which were boud to functions being reassigned would bypass the
3850 logger, breaking the sync of _il with the prompt counter. This
3866 logger, breaking the sync of _il with the prompt counter. This
3851 would then crash IPython later when a new line was logged.
3867 would then crash IPython later when a new line was logged.
3852
3868
3853 2001-12-02 Fernando Perez <fperez@colorado.edu>
3869 2001-12-02 Fernando Perez <fperez@colorado.edu>
3854
3870
3855 * Made IPython a package. This means people don't have to clutter
3871 * Made IPython a package. This means people don't have to clutter
3856 their sys.path with yet another directory. Changed the INSTALL
3872 their sys.path with yet another directory. Changed the INSTALL
3857 file accordingly.
3873 file accordingly.
3858
3874
3859 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
3875 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
3860 sorts its output (so @who shows it sorted) and @whos formats the
3876 sorts its output (so @who shows it sorted) and @whos formats the
3861 table according to the width of the first column. Nicer, easier to
3877 table according to the width of the first column. Nicer, easier to
3862 read. Todo: write a generic table_format() which takes a list of
3878 read. Todo: write a generic table_format() which takes a list of
3863 lists and prints it nicely formatted, with optional row/column
3879 lists and prints it nicely formatted, with optional row/column
3864 separators and proper padding and justification.
3880 separators and proper padding and justification.
3865
3881
3866 * Released 0.1.20
3882 * Released 0.1.20
3867
3883
3868 * Fixed bug in @log which would reverse the inputcache list (a
3884 * Fixed bug in @log which would reverse the inputcache list (a
3869 copy operation was missing).
3885 copy operation was missing).
3870
3886
3871 * Code cleanup. @config was changed to use page(). Better, since
3887 * Code cleanup. @config was changed to use page(). Better, since
3872 its output is always quite long.
3888 its output is always quite long.
3873
3889
3874 * Itpl is back as a dependency. I was having too many problems
3890 * Itpl is back as a dependency. I was having too many problems
3875 getting the parametric aliases to work reliably, and it's just
3891 getting the parametric aliases to work reliably, and it's just
3876 easier to code weird string operations with it than playing %()s
3892 easier to code weird string operations with it than playing %()s
3877 games. It's only ~6k, so I don't think it's too big a deal.
3893 games. It's only ~6k, so I don't think it's too big a deal.
3878
3894
3879 * Found (and fixed) a very nasty bug with history. !lines weren't
3895 * Found (and fixed) a very nasty bug with history. !lines weren't
3880 getting cached, and the out of sync caches would crash
3896 getting cached, and the out of sync caches would crash
3881 IPython. Fixed it by reorganizing the prefilter/handlers/logger
3897 IPython. Fixed it by reorganizing the prefilter/handlers/logger
3882 division of labor a bit better. Bug fixed, cleaner structure.
3898 division of labor a bit better. Bug fixed, cleaner structure.
3883
3899
3884 2001-12-01 Fernando Perez <fperez@colorado.edu>
3900 2001-12-01 Fernando Perez <fperez@colorado.edu>
3885
3901
3886 * Released 0.1.19
3902 * Released 0.1.19
3887
3903
3888 * Added option -n to @hist to prevent line number printing. Much
3904 * Added option -n to @hist to prevent line number printing. Much
3889 easier to copy/paste code this way.
3905 easier to copy/paste code this way.
3890
3906
3891 * Created global _il to hold the input list. Allows easy
3907 * Created global _il to hold the input list. Allows easy
3892 re-execution of blocks of code by slicing it (inspired by Janko's
3908 re-execution of blocks of code by slicing it (inspired by Janko's
3893 comment on 'macros').
3909 comment on 'macros').
3894
3910
3895 * Small fixes and doc updates.
3911 * Small fixes and doc updates.
3896
3912
3897 * Rewrote @history function (was @h). Renamed it to @hist, @h is
3913 * Rewrote @history function (was @h). Renamed it to @hist, @h is
3898 much too fragile with automagic. Handles properly multi-line
3914 much too fragile with automagic. Handles properly multi-line
3899 statements and takes parameters.
3915 statements and takes parameters.
3900
3916
3901 2001-11-30 Fernando Perez <fperez@colorado.edu>
3917 2001-11-30 Fernando Perez <fperez@colorado.edu>
3902
3918
3903 * Version 0.1.18 released.
3919 * Version 0.1.18 released.
3904
3920
3905 * Fixed nasty namespace bug in initial module imports.
3921 * Fixed nasty namespace bug in initial module imports.
3906
3922
3907 * Added copyright/license notes to all code files (except
3923 * Added copyright/license notes to all code files (except
3908 DPyGetOpt). For the time being, LGPL. That could change.
3924 DPyGetOpt). For the time being, LGPL. That could change.
3909
3925
3910 * Rewrote a much nicer README, updated INSTALL, cleaned up
3926 * Rewrote a much nicer README, updated INSTALL, cleaned up
3911 ipythonrc-* samples.
3927 ipythonrc-* samples.
3912
3928
3913 * Overall code/documentation cleanup. Basically ready for
3929 * Overall code/documentation cleanup. Basically ready for
3914 release. Only remaining thing: licence decision (LGPL?).
3930 release. Only remaining thing: licence decision (LGPL?).
3915
3931
3916 * Converted load_config to a class, ConfigLoader. Now recursion
3932 * Converted load_config to a class, ConfigLoader. Now recursion
3917 control is better organized. Doesn't include the same file twice.
3933 control is better organized. Doesn't include the same file twice.
3918
3934
3919 2001-11-29 Fernando Perez <fperez@colorado.edu>
3935 2001-11-29 Fernando Perez <fperez@colorado.edu>
3920
3936
3921 * Got input history working. Changed output history variables from
3937 * Got input history working. Changed output history variables from
3922 _p to _o so that _i is for input and _o for output. Just cleaner
3938 _p to _o so that _i is for input and _o for output. Just cleaner
3923 convention.
3939 convention.
3924
3940
3925 * Implemented parametric aliases. This pretty much allows the
3941 * Implemented parametric aliases. This pretty much allows the
3926 alias system to offer full-blown shell convenience, I think.
3942 alias system to offer full-blown shell convenience, I think.
3927
3943
3928 * Version 0.1.17 released, 0.1.18 opened.
3944 * Version 0.1.17 released, 0.1.18 opened.
3929
3945
3930 * dot_ipython/ipythonrc (alias): added documentation.
3946 * dot_ipython/ipythonrc (alias): added documentation.
3931 (xcolor): Fixed small bug (xcolors -> xcolor)
3947 (xcolor): Fixed small bug (xcolors -> xcolor)
3932
3948
3933 * Changed the alias system. Now alias is a magic command to define
3949 * Changed the alias system. Now alias is a magic command to define
3934 aliases just like the shell. Rationale: the builtin magics should
3950 aliases just like the shell. Rationale: the builtin magics should
3935 be there for things deeply connected to IPython's
3951 be there for things deeply connected to IPython's
3936 architecture. And this is a much lighter system for what I think
3952 architecture. And this is a much lighter system for what I think
3937 is the really important feature: allowing users to define quickly
3953 is the really important feature: allowing users to define quickly
3938 magics that will do shell things for them, so they can customize
3954 magics that will do shell things for them, so they can customize
3939 IPython easily to match their work habits. If someone is really
3955 IPython easily to match their work habits. If someone is really
3940 desperate to have another name for a builtin alias, they can
3956 desperate to have another name for a builtin alias, they can
3941 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
3957 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
3942 works.
3958 works.
3943
3959
3944 2001-11-28 Fernando Perez <fperez@colorado.edu>
3960 2001-11-28 Fernando Perez <fperez@colorado.edu>
3945
3961
3946 * Changed @file so that it opens the source file at the proper
3962 * Changed @file so that it opens the source file at the proper
3947 line. Since it uses less, if your EDITOR environment is
3963 line. Since it uses less, if your EDITOR environment is
3948 configured, typing v will immediately open your editor of choice
3964 configured, typing v will immediately open your editor of choice
3949 right at the line where the object is defined. Not as quick as
3965 right at the line where the object is defined. Not as quick as
3950 having a direct @edit command, but for all intents and purposes it
3966 having a direct @edit command, but for all intents and purposes it
3951 works. And I don't have to worry about writing @edit to deal with
3967 works. And I don't have to worry about writing @edit to deal with
3952 all the editors, less does that.
3968 all the editors, less does that.
3953
3969
3954 * Version 0.1.16 released, 0.1.17 opened.
3970 * Version 0.1.16 released, 0.1.17 opened.
3955
3971
3956 * Fixed some nasty bugs in the page/page_dumb combo that could
3972 * Fixed some nasty bugs in the page/page_dumb combo that could
3957 crash IPython.
3973 crash IPython.
3958
3974
3959 2001-11-27 Fernando Perez <fperez@colorado.edu>
3975 2001-11-27 Fernando Perez <fperez@colorado.edu>
3960
3976
3961 * Version 0.1.15 released, 0.1.16 opened.
3977 * Version 0.1.15 released, 0.1.16 opened.
3962
3978
3963 * Finally got ? and ?? to work for undefined things: now it's
3979 * Finally got ? and ?? to work for undefined things: now it's
3964 possible to type {}.get? and get information about the get method
3980 possible to type {}.get? and get information about the get method
3965 of dicts, or os.path? even if only os is defined (so technically
3981 of dicts, or os.path? even if only os is defined (so technically
3966 os.path isn't). Works at any level. For example, after import os,
3982 os.path isn't). Works at any level. For example, after import os,
3967 os?, os.path?, os.path.abspath? all work. This is great, took some
3983 os?, os.path?, os.path.abspath? all work. This is great, took some
3968 work in _ofind.
3984 work in _ofind.
3969
3985
3970 * Fixed more bugs with logging. The sanest way to do it was to add
3986 * Fixed more bugs with logging. The sanest way to do it was to add
3971 to @log a 'mode' parameter. Killed two in one shot (this mode
3987 to @log a 'mode' parameter. Killed two in one shot (this mode
3972 option was a request of Janko's). I think it's finally clean
3988 option was a request of Janko's). I think it's finally clean
3973 (famous last words).
3989 (famous last words).
3974
3990
3975 * Added a page_dumb() pager which does a decent job of paging on
3991 * Added a page_dumb() pager which does a decent job of paging on
3976 screen, if better things (like less) aren't available. One less
3992 screen, if better things (like less) aren't available. One less
3977 unix dependency (someday maybe somebody will port this to
3993 unix dependency (someday maybe somebody will port this to
3978 windows).
3994 windows).
3979
3995
3980 * Fixed problem in magic_log: would lock of logging out if log
3996 * Fixed problem in magic_log: would lock of logging out if log
3981 creation failed (because it would still think it had succeeded).
3997 creation failed (because it would still think it had succeeded).
3982
3998
3983 * Improved the page() function using curses to auto-detect screen
3999 * Improved the page() function using curses to auto-detect screen
3984 size. Now it can make a much better decision on whether to print
4000 size. Now it can make a much better decision on whether to print
3985 or page a string. Option screen_length was modified: a value 0
4001 or page a string. Option screen_length was modified: a value 0
3986 means auto-detect, and that's the default now.
4002 means auto-detect, and that's the default now.
3987
4003
3988 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4004 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
3989 go out. I'll test it for a few days, then talk to Janko about
4005 go out. I'll test it for a few days, then talk to Janko about
3990 licences and announce it.
4006 licences and announce it.
3991
4007
3992 * Fixed the length of the auto-generated ---> prompt which appears
4008 * Fixed the length of the auto-generated ---> prompt which appears
3993 for auto-parens and auto-quotes. Getting this right isn't trivial,
4009 for auto-parens and auto-quotes. Getting this right isn't trivial,
3994 with all the color escapes, different prompt types and optional
4010 with all the color escapes, different prompt types and optional
3995 separators. But it seems to be working in all the combinations.
4011 separators. But it seems to be working in all the combinations.
3996
4012
3997 2001-11-26 Fernando Perez <fperez@colorado.edu>
4013 2001-11-26 Fernando Perez <fperez@colorado.edu>
3998
4014
3999 * Wrote a regexp filter to get option types from the option names
4015 * Wrote a regexp filter to get option types from the option names
4000 string. This eliminates the need to manually keep two duplicate
4016 string. This eliminates the need to manually keep two duplicate
4001 lists.
4017 lists.
4002
4018
4003 * Removed the unneeded check_option_names. Now options are handled
4019 * Removed the unneeded check_option_names. Now options are handled
4004 in a much saner manner and it's easy to visually check that things
4020 in a much saner manner and it's easy to visually check that things
4005 are ok.
4021 are ok.
4006
4022
4007 * Updated version numbers on all files I modified to carry a
4023 * Updated version numbers on all files I modified to carry a
4008 notice so Janko and Nathan have clear version markers.
4024 notice so Janko and Nathan have clear version markers.
4009
4025
4010 * Updated docstring for ultraTB with my changes. I should send
4026 * Updated docstring for ultraTB with my changes. I should send
4011 this to Nathan.
4027 this to Nathan.
4012
4028
4013 * Lots of small fixes. Ran everything through pychecker again.
4029 * Lots of small fixes. Ran everything through pychecker again.
4014
4030
4015 * Made loading of deep_reload an cmd line option. If it's not too
4031 * Made loading of deep_reload an cmd line option. If it's not too
4016 kosher, now people can just disable it. With -nodeep_reload it's
4032 kosher, now people can just disable it. With -nodeep_reload it's
4017 still available as dreload(), it just won't overwrite reload().
4033 still available as dreload(), it just won't overwrite reload().
4018
4034
4019 * Moved many options to the no| form (-opt and -noopt
4035 * Moved many options to the no| form (-opt and -noopt
4020 accepted). Cleaner.
4036 accepted). Cleaner.
4021
4037
4022 * Changed magic_log so that if called with no parameters, it uses
4038 * Changed magic_log so that if called with no parameters, it uses
4023 'rotate' mode. That way auto-generated logs aren't automatically
4039 'rotate' mode. That way auto-generated logs aren't automatically
4024 over-written. For normal logs, now a backup is made if it exists
4040 over-written. For normal logs, now a backup is made if it exists
4025 (only 1 level of backups). A new 'backup' mode was added to the
4041 (only 1 level of backups). A new 'backup' mode was added to the
4026 Logger class to support this. This was a request by Janko.
4042 Logger class to support this. This was a request by Janko.
4027
4043
4028 * Added @logoff/@logon to stop/restart an active log.
4044 * Added @logoff/@logon to stop/restart an active log.
4029
4045
4030 * Fixed a lot of bugs in log saving/replay. It was pretty
4046 * Fixed a lot of bugs in log saving/replay. It was pretty
4031 broken. Now special lines (!@,/) appear properly in the command
4047 broken. Now special lines (!@,/) appear properly in the command
4032 history after a log replay.
4048 history after a log replay.
4033
4049
4034 * Tried and failed to implement full session saving via pickle. My
4050 * Tried and failed to implement full session saving via pickle. My
4035 idea was to pickle __main__.__dict__, but modules can't be
4051 idea was to pickle __main__.__dict__, but modules can't be
4036 pickled. This would be a better alternative to replaying logs, but
4052 pickled. This would be a better alternative to replaying logs, but
4037 seems quite tricky to get to work. Changed -session to be called
4053 seems quite tricky to get to work. Changed -session to be called
4038 -logplay, which more accurately reflects what it does. And if we
4054 -logplay, which more accurately reflects what it does. And if we
4039 ever get real session saving working, -session is now available.
4055 ever get real session saving working, -session is now available.
4040
4056
4041 * Implemented color schemes for prompts also. As for tracebacks,
4057 * Implemented color schemes for prompts also. As for tracebacks,
4042 currently only NoColor and Linux are supported. But now the
4058 currently only NoColor and Linux are supported. But now the
4043 infrastructure is in place, based on a generic ColorScheme
4059 infrastructure is in place, based on a generic ColorScheme
4044 class. So writing and activating new schemes both for the prompts
4060 class. So writing and activating new schemes both for the prompts
4045 and the tracebacks should be straightforward.
4061 and the tracebacks should be straightforward.
4046
4062
4047 * Version 0.1.13 released, 0.1.14 opened.
4063 * Version 0.1.13 released, 0.1.14 opened.
4048
4064
4049 * Changed handling of options for output cache. Now counter is
4065 * Changed handling of options for output cache. Now counter is
4050 hardwired starting at 1 and one specifies the maximum number of
4066 hardwired starting at 1 and one specifies the maximum number of
4051 entries *in the outcache* (not the max prompt counter). This is
4067 entries *in the outcache* (not the max prompt counter). This is
4052 much better, since many statements won't increase the cache
4068 much better, since many statements won't increase the cache
4053 count. It also eliminated some confusing options, now there's only
4069 count. It also eliminated some confusing options, now there's only
4054 one: cache_size.
4070 one: cache_size.
4055
4071
4056 * Added 'alias' magic function and magic_alias option in the
4072 * Added 'alias' magic function and magic_alias option in the
4057 ipythonrc file. Now the user can easily define whatever names he
4073 ipythonrc file. Now the user can easily define whatever names he
4058 wants for the magic functions without having to play weird
4074 wants for the magic functions without having to play weird
4059 namespace games. This gives IPython a real shell-like feel.
4075 namespace games. This gives IPython a real shell-like feel.
4060
4076
4061 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4077 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4062 @ or not).
4078 @ or not).
4063
4079
4064 This was one of the last remaining 'visible' bugs (that I know
4080 This was one of the last remaining 'visible' bugs (that I know
4065 of). I think if I can clean up the session loading so it works
4081 of). I think if I can clean up the session loading so it works
4066 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4082 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4067 about licensing).
4083 about licensing).
4068
4084
4069 2001-11-25 Fernando Perez <fperez@colorado.edu>
4085 2001-11-25 Fernando Perez <fperez@colorado.edu>
4070
4086
4071 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4087 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4072 there's a cleaner distinction between what ? and ?? show.
4088 there's a cleaner distinction between what ? and ?? show.
4073
4089
4074 * Added screen_length option. Now the user can define his own
4090 * Added screen_length option. Now the user can define his own
4075 screen size for page() operations.
4091 screen size for page() operations.
4076
4092
4077 * Implemented magic shell-like functions with automatic code
4093 * Implemented magic shell-like functions with automatic code
4078 generation. Now adding another function is just a matter of adding
4094 generation. Now adding another function is just a matter of adding
4079 an entry to a dict, and the function is dynamically generated at
4095 an entry to a dict, and the function is dynamically generated at
4080 run-time. Python has some really cool features!
4096 run-time. Python has some really cool features!
4081
4097
4082 * Renamed many options to cleanup conventions a little. Now all
4098 * Renamed many options to cleanup conventions a little. Now all
4083 are lowercase, and only underscores where needed. Also in the code
4099 are lowercase, and only underscores where needed. Also in the code
4084 option name tables are clearer.
4100 option name tables are clearer.
4085
4101
4086 * Changed prompts a little. Now input is 'In [n]:' instead of
4102 * Changed prompts a little. Now input is 'In [n]:' instead of
4087 'In[n]:='. This allows it the numbers to be aligned with the
4103 'In[n]:='. This allows it the numbers to be aligned with the
4088 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4104 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4089 Python (it was a Mathematica thing). The '...' continuation prompt
4105 Python (it was a Mathematica thing). The '...' continuation prompt
4090 was also changed a little to align better.
4106 was also changed a little to align better.
4091
4107
4092 * Fixed bug when flushing output cache. Not all _p<n> variables
4108 * Fixed bug when flushing output cache. Not all _p<n> variables
4093 exist, so their deletion needs to be wrapped in a try:
4109 exist, so their deletion needs to be wrapped in a try:
4094
4110
4095 * Figured out how to properly use inspect.formatargspec() (it
4111 * Figured out how to properly use inspect.formatargspec() (it
4096 requires the args preceded by *). So I removed all the code from
4112 requires the args preceded by *). So I removed all the code from
4097 _get_pdef in Magic, which was just replicating that.
4113 _get_pdef in Magic, which was just replicating that.
4098
4114
4099 * Added test to prefilter to allow redefining magic function names
4115 * Added test to prefilter to allow redefining magic function names
4100 as variables. This is ok, since the @ form is always available,
4116 as variables. This is ok, since the @ form is always available,
4101 but whe should allow the user to define a variable called 'ls' if
4117 but whe should allow the user to define a variable called 'ls' if
4102 he needs it.
4118 he needs it.
4103
4119
4104 * Moved the ToDo information from README into a separate ToDo.
4120 * Moved the ToDo information from README into a separate ToDo.
4105
4121
4106 * General code cleanup and small bugfixes. I think it's close to a
4122 * General code cleanup and small bugfixes. I think it's close to a
4107 state where it can be released, obviously with a big 'beta'
4123 state where it can be released, obviously with a big 'beta'
4108 warning on it.
4124 warning on it.
4109
4125
4110 * Got the magic function split to work. Now all magics are defined
4126 * Got the magic function split to work. Now all magics are defined
4111 in a separate class. It just organizes things a bit, and now
4127 in a separate class. It just organizes things a bit, and now
4112 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4128 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4113 was too long).
4129 was too long).
4114
4130
4115 * Changed @clear to @reset to avoid potential confusions with
4131 * Changed @clear to @reset to avoid potential confusions with
4116 the shell command clear. Also renamed @cl to @clear, which does
4132 the shell command clear. Also renamed @cl to @clear, which does
4117 exactly what people expect it to from their shell experience.
4133 exactly what people expect it to from their shell experience.
4118
4134
4119 Added a check to the @reset command (since it's so
4135 Added a check to the @reset command (since it's so
4120 destructive, it's probably a good idea to ask for confirmation).
4136 destructive, it's probably a good idea to ask for confirmation).
4121 But now reset only works for full namespace resetting. Since the
4137 But now reset only works for full namespace resetting. Since the
4122 del keyword is already there for deleting a few specific
4138 del keyword is already there for deleting a few specific
4123 variables, I don't see the point of having a redundant magic
4139 variables, I don't see the point of having a redundant magic
4124 function for the same task.
4140 function for the same task.
4125
4141
4126 2001-11-24 Fernando Perez <fperez@colorado.edu>
4142 2001-11-24 Fernando Perez <fperez@colorado.edu>
4127
4143
4128 * Updated the builtin docs (esp. the ? ones).
4144 * Updated the builtin docs (esp. the ? ones).
4129
4145
4130 * Ran all the code through pychecker. Not terribly impressed with
4146 * Ran all the code through pychecker. Not terribly impressed with
4131 it: lots of spurious warnings and didn't really find anything of
4147 it: lots of spurious warnings and didn't really find anything of
4132 substance (just a few modules being imported and not used).
4148 substance (just a few modules being imported and not used).
4133
4149
4134 * Implemented the new ultraTB functionality into IPython. New
4150 * Implemented the new ultraTB functionality into IPython. New
4135 option: xcolors. This chooses color scheme. xmode now only selects
4151 option: xcolors. This chooses color scheme. xmode now only selects
4136 between Plain and Verbose. Better orthogonality.
4152 between Plain and Verbose. Better orthogonality.
4137
4153
4138 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4154 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4139 mode and color scheme for the exception handlers. Now it's
4155 mode and color scheme for the exception handlers. Now it's
4140 possible to have the verbose traceback with no coloring.
4156 possible to have the verbose traceback with no coloring.
4141
4157
4142 2001-11-23 Fernando Perez <fperez@colorado.edu>
4158 2001-11-23 Fernando Perez <fperez@colorado.edu>
4143
4159
4144 * Version 0.1.12 released, 0.1.13 opened.
4160 * Version 0.1.12 released, 0.1.13 opened.
4145
4161
4146 * Removed option to set auto-quote and auto-paren escapes by
4162 * Removed option to set auto-quote and auto-paren escapes by
4147 user. The chances of breaking valid syntax are just too high. If
4163 user. The chances of breaking valid syntax are just too high. If
4148 someone *really* wants, they can always dig into the code.
4164 someone *really* wants, they can always dig into the code.
4149
4165
4150 * Made prompt separators configurable.
4166 * Made prompt separators configurable.
4151
4167
4152 2001-11-22 Fernando Perez <fperez@colorado.edu>
4168 2001-11-22 Fernando Perez <fperez@colorado.edu>
4153
4169
4154 * Small bugfixes in many places.
4170 * Small bugfixes in many places.
4155
4171
4156 * Removed the MyCompleter class from ipplib. It seemed redundant
4172 * Removed the MyCompleter class from ipplib. It seemed redundant
4157 with the C-p,C-n history search functionality. Less code to
4173 with the C-p,C-n history search functionality. Less code to
4158 maintain.
4174 maintain.
4159
4175
4160 * Moved all the original ipython.py code into ipythonlib.py. Right
4176 * Moved all the original ipython.py code into ipythonlib.py. Right
4161 now it's just one big dump into a function called make_IPython, so
4177 now it's just one big dump into a function called make_IPython, so
4162 no real modularity has been gained. But at least it makes the
4178 no real modularity has been gained. But at least it makes the
4163 wrapper script tiny, and since ipythonlib is a module, it gets
4179 wrapper script tiny, and since ipythonlib is a module, it gets
4164 compiled and startup is much faster.
4180 compiled and startup is much faster.
4165
4181
4166 This is a reasobably 'deep' change, so we should test it for a
4182 This is a reasobably 'deep' change, so we should test it for a
4167 while without messing too much more with the code.
4183 while without messing too much more with the code.
4168
4184
4169 2001-11-21 Fernando Perez <fperez@colorado.edu>
4185 2001-11-21 Fernando Perez <fperez@colorado.edu>
4170
4186
4171 * Version 0.1.11 released, 0.1.12 opened for further work.
4187 * Version 0.1.11 released, 0.1.12 opened for further work.
4172
4188
4173 * Removed dependency on Itpl. It was only needed in one place. It
4189 * Removed dependency on Itpl. It was only needed in one place. It
4174 would be nice if this became part of python, though. It makes life
4190 would be nice if this became part of python, though. It makes life
4175 *a lot* easier in some cases.
4191 *a lot* easier in some cases.
4176
4192
4177 * Simplified the prefilter code a bit. Now all handlers are
4193 * Simplified the prefilter code a bit. Now all handlers are
4178 expected to explicitly return a value (at least a blank string).
4194 expected to explicitly return a value (at least a blank string).
4179
4195
4180 * Heavy edits in ipplib. Removed the help system altogether. Now
4196 * Heavy edits in ipplib. Removed the help system altogether. Now
4181 obj?/?? is used for inspecting objects, a magic @doc prints
4197 obj?/?? is used for inspecting objects, a magic @doc prints
4182 docstrings, and full-blown Python help is accessed via the 'help'
4198 docstrings, and full-blown Python help is accessed via the 'help'
4183 keyword. This cleans up a lot of code (less to maintain) and does
4199 keyword. This cleans up a lot of code (less to maintain) and does
4184 the job. Since 'help' is now a standard Python component, might as
4200 the job. Since 'help' is now a standard Python component, might as
4185 well use it and remove duplicate functionality.
4201 well use it and remove duplicate functionality.
4186
4202
4187 Also removed the option to use ipplib as a standalone program. By
4203 Also removed the option to use ipplib as a standalone program. By
4188 now it's too dependent on other parts of IPython to function alone.
4204 now it's too dependent on other parts of IPython to function alone.
4189
4205
4190 * Fixed bug in genutils.pager. It would crash if the pager was
4206 * Fixed bug in genutils.pager. It would crash if the pager was
4191 exited immediately after opening (broken pipe).
4207 exited immediately after opening (broken pipe).
4192
4208
4193 * Trimmed down the VerboseTB reporting a little. The header is
4209 * Trimmed down the VerboseTB reporting a little. The header is
4194 much shorter now and the repeated exception arguments at the end
4210 much shorter now and the repeated exception arguments at the end
4195 have been removed. For interactive use the old header seemed a bit
4211 have been removed. For interactive use the old header seemed a bit
4196 excessive.
4212 excessive.
4197
4213
4198 * Fixed small bug in output of @whos for variables with multi-word
4214 * Fixed small bug in output of @whos for variables with multi-word
4199 types (only first word was displayed).
4215 types (only first word was displayed).
4200
4216
4201 2001-11-17 Fernando Perez <fperez@colorado.edu>
4217 2001-11-17 Fernando Perez <fperez@colorado.edu>
4202
4218
4203 * Version 0.1.10 released, 0.1.11 opened for further work.
4219 * Version 0.1.10 released, 0.1.11 opened for further work.
4204
4220
4205 * Modified dirs and friends. dirs now *returns* the stack (not
4221 * Modified dirs and friends. dirs now *returns* the stack (not
4206 prints), so one can manipulate it as a variable. Convenient to
4222 prints), so one can manipulate it as a variable. Convenient to
4207 travel along many directories.
4223 travel along many directories.
4208
4224
4209 * Fixed bug in magic_pdef: would only work with functions with
4225 * Fixed bug in magic_pdef: would only work with functions with
4210 arguments with default values.
4226 arguments with default values.
4211
4227
4212 2001-11-14 Fernando Perez <fperez@colorado.edu>
4228 2001-11-14 Fernando Perez <fperez@colorado.edu>
4213
4229
4214 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4230 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4215 example with IPython. Various other minor fixes and cleanups.
4231 example with IPython. Various other minor fixes and cleanups.
4216
4232
4217 * Version 0.1.9 released, 0.1.10 opened for further work.
4233 * Version 0.1.9 released, 0.1.10 opened for further work.
4218
4234
4219 * Added sys.path to the list of directories searched in the
4235 * Added sys.path to the list of directories searched in the
4220 execfile= option. It used to be the current directory and the
4236 execfile= option. It used to be the current directory and the
4221 user's IPYTHONDIR only.
4237 user's IPYTHONDIR only.
4222
4238
4223 2001-11-13 Fernando Perez <fperez@colorado.edu>
4239 2001-11-13 Fernando Perez <fperez@colorado.edu>
4224
4240
4225 * Reinstated the raw_input/prefilter separation that Janko had
4241 * Reinstated the raw_input/prefilter separation that Janko had
4226 initially. This gives a more convenient setup for extending the
4242 initially. This gives a more convenient setup for extending the
4227 pre-processor from the outside: raw_input always gets a string,
4243 pre-processor from the outside: raw_input always gets a string,
4228 and prefilter has to process it. We can then redefine prefilter
4244 and prefilter has to process it. We can then redefine prefilter
4229 from the outside and implement extensions for special
4245 from the outside and implement extensions for special
4230 purposes.
4246 purposes.
4231
4247
4232 Today I got one for inputting PhysicalQuantity objects
4248 Today I got one for inputting PhysicalQuantity objects
4233 (from Scientific) without needing any function calls at
4249 (from Scientific) without needing any function calls at
4234 all. Extremely convenient, and it's all done as a user-level
4250 all. Extremely convenient, and it's all done as a user-level
4235 extension (no IPython code was touched). Now instead of:
4251 extension (no IPython code was touched). Now instead of:
4236 a = PhysicalQuantity(4.2,'m/s**2')
4252 a = PhysicalQuantity(4.2,'m/s**2')
4237 one can simply say
4253 one can simply say
4238 a = 4.2 m/s**2
4254 a = 4.2 m/s**2
4239 or even
4255 or even
4240 a = 4.2 m/s^2
4256 a = 4.2 m/s^2
4241
4257
4242 I use this, but it's also a proof of concept: IPython really is
4258 I use this, but it's also a proof of concept: IPython really is
4243 fully user-extensible, even at the level of the parsing of the
4259 fully user-extensible, even at the level of the parsing of the
4244 command line. It's not trivial, but it's perfectly doable.
4260 command line. It's not trivial, but it's perfectly doable.
4245
4261
4246 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4262 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4247 the problem of modules being loaded in the inverse order in which
4263 the problem of modules being loaded in the inverse order in which
4248 they were defined in
4264 they were defined in
4249
4265
4250 * Version 0.1.8 released, 0.1.9 opened for further work.
4266 * Version 0.1.8 released, 0.1.9 opened for further work.
4251
4267
4252 * Added magics pdef, source and file. They respectively show the
4268 * Added magics pdef, source and file. They respectively show the
4253 definition line ('prototype' in C), source code and full python
4269 definition line ('prototype' in C), source code and full python
4254 file for any callable object. The object inspector oinfo uses
4270 file for any callable object. The object inspector oinfo uses
4255 these to show the same information.
4271 these to show the same information.
4256
4272
4257 * Version 0.1.7 released, 0.1.8 opened for further work.
4273 * Version 0.1.7 released, 0.1.8 opened for further work.
4258
4274
4259 * Separated all the magic functions into a class called Magic. The
4275 * Separated all the magic functions into a class called Magic. The
4260 InteractiveShell class was becoming too big for Xemacs to handle
4276 InteractiveShell class was becoming too big for Xemacs to handle
4261 (de-indenting a line would lock it up for 10 seconds while it
4277 (de-indenting a line would lock it up for 10 seconds while it
4262 backtracked on the whole class!)
4278 backtracked on the whole class!)
4263
4279
4264 FIXME: didn't work. It can be done, but right now namespaces are
4280 FIXME: didn't work. It can be done, but right now namespaces are
4265 all messed up. Do it later (reverted it for now, so at least
4281 all messed up. Do it later (reverted it for now, so at least
4266 everything works as before).
4282 everything works as before).
4267
4283
4268 * Got the object introspection system (magic_oinfo) working! I
4284 * Got the object introspection system (magic_oinfo) working! I
4269 think this is pretty much ready for release to Janko, so he can
4285 think this is pretty much ready for release to Janko, so he can
4270 test it for a while and then announce it. Pretty much 100% of what
4286 test it for a while and then announce it. Pretty much 100% of what
4271 I wanted for the 'phase 1' release is ready. Happy, tired.
4287 I wanted for the 'phase 1' release is ready. Happy, tired.
4272
4288
4273 2001-11-12 Fernando Perez <fperez@colorado.edu>
4289 2001-11-12 Fernando Perez <fperez@colorado.edu>
4274
4290
4275 * Version 0.1.6 released, 0.1.7 opened for further work.
4291 * Version 0.1.6 released, 0.1.7 opened for further work.
4276
4292
4277 * Fixed bug in printing: it used to test for truth before
4293 * Fixed bug in printing: it used to test for truth before
4278 printing, so 0 wouldn't print. Now checks for None.
4294 printing, so 0 wouldn't print. Now checks for None.
4279
4295
4280 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4296 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4281 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4297 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4282 reaches by hand into the outputcache. Think of a better way to do
4298 reaches by hand into the outputcache. Think of a better way to do
4283 this later.
4299 this later.
4284
4300
4285 * Various small fixes thanks to Nathan's comments.
4301 * Various small fixes thanks to Nathan's comments.
4286
4302
4287 * Changed magic_pprint to magic_Pprint. This way it doesn't
4303 * Changed magic_pprint to magic_Pprint. This way it doesn't
4288 collide with pprint() and the name is consistent with the command
4304 collide with pprint() and the name is consistent with the command
4289 line option.
4305 line option.
4290
4306
4291 * Changed prompt counter behavior to be fully like
4307 * Changed prompt counter behavior to be fully like
4292 Mathematica's. That is, even input that doesn't return a result
4308 Mathematica's. That is, even input that doesn't return a result
4293 raises the prompt counter. The old behavior was kind of confusing
4309 raises the prompt counter. The old behavior was kind of confusing
4294 (getting the same prompt number several times if the operation
4310 (getting the same prompt number several times if the operation
4295 didn't return a result).
4311 didn't return a result).
4296
4312
4297 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4313 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4298
4314
4299 * Fixed -Classic mode (wasn't working anymore).
4315 * Fixed -Classic mode (wasn't working anymore).
4300
4316
4301 * Added colored prompts using Nathan's new code. Colors are
4317 * Added colored prompts using Nathan's new code. Colors are
4302 currently hardwired, they can be user-configurable. For
4318 currently hardwired, they can be user-configurable. For
4303 developers, they can be chosen in file ipythonlib.py, at the
4319 developers, they can be chosen in file ipythonlib.py, at the
4304 beginning of the CachedOutput class def.
4320 beginning of the CachedOutput class def.
4305
4321
4306 2001-11-11 Fernando Perez <fperez@colorado.edu>
4322 2001-11-11 Fernando Perez <fperez@colorado.edu>
4307
4323
4308 * Version 0.1.5 released, 0.1.6 opened for further work.
4324 * Version 0.1.5 released, 0.1.6 opened for further work.
4309
4325
4310 * Changed magic_env to *return* the environment as a dict (not to
4326 * Changed magic_env to *return* the environment as a dict (not to
4311 print it). This way it prints, but it can also be processed.
4327 print it). This way it prints, but it can also be processed.
4312
4328
4313 * Added Verbose exception reporting to interactive
4329 * Added Verbose exception reporting to interactive
4314 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4330 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4315 traceback. Had to make some changes to the ultraTB file. This is
4331 traceback. Had to make some changes to the ultraTB file. This is
4316 probably the last 'big' thing in my mental todo list. This ties
4332 probably the last 'big' thing in my mental todo list. This ties
4317 in with the next entry:
4333 in with the next entry:
4318
4334
4319 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4335 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4320 has to specify is Plain, Color or Verbose for all exception
4336 has to specify is Plain, Color or Verbose for all exception
4321 handling.
4337 handling.
4322
4338
4323 * Removed ShellServices option. All this can really be done via
4339 * Removed ShellServices option. All this can really be done via
4324 the magic system. It's easier to extend, cleaner and has automatic
4340 the magic system. It's easier to extend, cleaner and has automatic
4325 namespace protection and documentation.
4341 namespace protection and documentation.
4326
4342
4327 2001-11-09 Fernando Perez <fperez@colorado.edu>
4343 2001-11-09 Fernando Perez <fperez@colorado.edu>
4328
4344
4329 * Fixed bug in output cache flushing (missing parameter to
4345 * Fixed bug in output cache flushing (missing parameter to
4330 __init__). Other small bugs fixed (found using pychecker).
4346 __init__). Other small bugs fixed (found using pychecker).
4331
4347
4332 * Version 0.1.4 opened for bugfixing.
4348 * Version 0.1.4 opened for bugfixing.
4333
4349
4334 2001-11-07 Fernando Perez <fperez@colorado.edu>
4350 2001-11-07 Fernando Perez <fperez@colorado.edu>
4335
4351
4336 * Version 0.1.3 released, mainly because of the raw_input bug.
4352 * Version 0.1.3 released, mainly because of the raw_input bug.
4337
4353
4338 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4354 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4339 and when testing for whether things were callable, a call could
4355 and when testing for whether things were callable, a call could
4340 actually be made to certain functions. They would get called again
4356 actually be made to certain functions. They would get called again
4341 once 'really' executed, with a resulting double call. A disaster
4357 once 'really' executed, with a resulting double call. A disaster
4342 in many cases (list.reverse() would never work!).
4358 in many cases (list.reverse() would never work!).
4343
4359
4344 * Removed prefilter() function, moved its code to raw_input (which
4360 * Removed prefilter() function, moved its code to raw_input (which
4345 after all was just a near-empty caller for prefilter). This saves
4361 after all was just a near-empty caller for prefilter). This saves
4346 a function call on every prompt, and simplifies the class a tiny bit.
4362 a function call on every prompt, and simplifies the class a tiny bit.
4347
4363
4348 * Fix _ip to __ip name in magic example file.
4364 * Fix _ip to __ip name in magic example file.
4349
4365
4350 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4366 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4351 work with non-gnu versions of tar.
4367 work with non-gnu versions of tar.
4352
4368
4353 2001-11-06 Fernando Perez <fperez@colorado.edu>
4369 2001-11-06 Fernando Perez <fperez@colorado.edu>
4354
4370
4355 * Version 0.1.2. Just to keep track of the recent changes.
4371 * Version 0.1.2. Just to keep track of the recent changes.
4356
4372
4357 * Fixed nasty bug in output prompt routine. It used to check 'if
4373 * Fixed nasty bug in output prompt routine. It used to check 'if
4358 arg != None...'. Problem is, this fails if arg implements a
4374 arg != None...'. Problem is, this fails if arg implements a
4359 special comparison (__cmp__) which disallows comparing to
4375 special comparison (__cmp__) which disallows comparing to
4360 None. Found it when trying to use the PhysicalQuantity module from
4376 None. Found it when trying to use the PhysicalQuantity module from
4361 ScientificPython.
4377 ScientificPython.
4362
4378
4363 2001-11-05 Fernando Perez <fperez@colorado.edu>
4379 2001-11-05 Fernando Perez <fperez@colorado.edu>
4364
4380
4365 * Also added dirs. Now the pushd/popd/dirs family functions
4381 * Also added dirs. Now the pushd/popd/dirs family functions
4366 basically like the shell, with the added convenience of going home
4382 basically like the shell, with the added convenience of going home
4367 when called with no args.
4383 when called with no args.
4368
4384
4369 * pushd/popd slightly modified to mimic shell behavior more
4385 * pushd/popd slightly modified to mimic shell behavior more
4370 closely.
4386 closely.
4371
4387
4372 * Added env,pushd,popd from ShellServices as magic functions. I
4388 * Added env,pushd,popd from ShellServices as magic functions. I
4373 think the cleanest will be to port all desired functions from
4389 think the cleanest will be to port all desired functions from
4374 ShellServices as magics and remove ShellServices altogether. This
4390 ShellServices as magics and remove ShellServices altogether. This
4375 will provide a single, clean way of adding functionality
4391 will provide a single, clean way of adding functionality
4376 (shell-type or otherwise) to IP.
4392 (shell-type or otherwise) to IP.
4377
4393
4378 2001-11-04 Fernando Perez <fperez@colorado.edu>
4394 2001-11-04 Fernando Perez <fperez@colorado.edu>
4379
4395
4380 * Added .ipython/ directory to sys.path. This way users can keep
4396 * Added .ipython/ directory to sys.path. This way users can keep
4381 customizations there and access them via import.
4397 customizations there and access them via import.
4382
4398
4383 2001-11-03 Fernando Perez <fperez@colorado.edu>
4399 2001-11-03 Fernando Perez <fperez@colorado.edu>
4384
4400
4385 * Opened version 0.1.1 for new changes.
4401 * Opened version 0.1.1 for new changes.
4386
4402
4387 * Changed version number to 0.1.0: first 'public' release, sent to
4403 * Changed version number to 0.1.0: first 'public' release, sent to
4388 Nathan and Janko.
4404 Nathan and Janko.
4389
4405
4390 * Lots of small fixes and tweaks.
4406 * Lots of small fixes and tweaks.
4391
4407
4392 * Minor changes to whos format. Now strings are shown, snipped if
4408 * Minor changes to whos format. Now strings are shown, snipped if
4393 too long.
4409 too long.
4394
4410
4395 * Changed ShellServices to work on __main__ so they show up in @who
4411 * Changed ShellServices to work on __main__ so they show up in @who
4396
4412
4397 * Help also works with ? at the end of a line:
4413 * Help also works with ? at the end of a line:
4398 ?sin and sin?
4414 ?sin and sin?
4399 both produce the same effect. This is nice, as often I use the
4415 both produce the same effect. This is nice, as often I use the
4400 tab-complete to find the name of a method, but I used to then have
4416 tab-complete to find the name of a method, but I used to then have
4401 to go to the beginning of the line to put a ? if I wanted more
4417 to go to the beginning of the line to put a ? if I wanted more
4402 info. Now I can just add the ? and hit return. Convenient.
4418 info. Now I can just add the ? and hit return. Convenient.
4403
4419
4404 2001-11-02 Fernando Perez <fperez@colorado.edu>
4420 2001-11-02 Fernando Perez <fperez@colorado.edu>
4405
4421
4406 * Python version check (>=2.1) added.
4422 * Python version check (>=2.1) added.
4407
4423
4408 * Added LazyPython documentation. At this point the docs are quite
4424 * Added LazyPython documentation. At this point the docs are quite
4409 a mess. A cleanup is in order.
4425 a mess. A cleanup is in order.
4410
4426
4411 * Auto-installer created. For some bizarre reason, the zipfiles
4427 * Auto-installer created. For some bizarre reason, the zipfiles
4412 module isn't working on my system. So I made a tar version
4428 module isn't working on my system. So I made a tar version
4413 (hopefully the command line options in various systems won't kill
4429 (hopefully the command line options in various systems won't kill
4414 me).
4430 me).
4415
4431
4416 * Fixes to Struct in genutils. Now all dictionary-like methods are
4432 * Fixes to Struct in genutils. Now all dictionary-like methods are
4417 protected (reasonably).
4433 protected (reasonably).
4418
4434
4419 * Added pager function to genutils and changed ? to print usage
4435 * Added pager function to genutils and changed ? to print usage
4420 note through it (it was too long).
4436 note through it (it was too long).
4421
4437
4422 * Added the LazyPython functionality. Works great! I changed the
4438 * Added the LazyPython functionality. Works great! I changed the
4423 auto-quote escape to ';', it's on home row and next to '. But
4439 auto-quote escape to ';', it's on home row and next to '. But
4424 both auto-quote and auto-paren (still /) escapes are command-line
4440 both auto-quote and auto-paren (still /) escapes are command-line
4425 parameters.
4441 parameters.
4426
4442
4427
4443
4428 2001-11-01 Fernando Perez <fperez@colorado.edu>
4444 2001-11-01 Fernando Perez <fperez@colorado.edu>
4429
4445
4430 * Version changed to 0.0.7. Fairly large change: configuration now
4446 * Version changed to 0.0.7. Fairly large change: configuration now
4431 is all stored in a directory, by default .ipython. There, all
4447 is all stored in a directory, by default .ipython. There, all
4432 config files have normal looking names (not .names)
4448 config files have normal looking names (not .names)
4433
4449
4434 * Version 0.0.6 Released first to Lucas and Archie as a test
4450 * Version 0.0.6 Released first to Lucas and Archie as a test
4435 run. Since it's the first 'semi-public' release, change version to
4451 run. Since it's the first 'semi-public' release, change version to
4436 > 0.0.6 for any changes now.
4452 > 0.0.6 for any changes now.
4437
4453
4438 * Stuff I had put in the ipplib.py changelog:
4454 * Stuff I had put in the ipplib.py changelog:
4439
4455
4440 Changes to InteractiveShell:
4456 Changes to InteractiveShell:
4441
4457
4442 - Made the usage message a parameter.
4458 - Made the usage message a parameter.
4443
4459
4444 - Require the name of the shell variable to be given. It's a bit
4460 - Require the name of the shell variable to be given. It's a bit
4445 of a hack, but allows the name 'shell' not to be hardwire in the
4461 of a hack, but allows the name 'shell' not to be hardwire in the
4446 magic (@) handler, which is problematic b/c it requires
4462 magic (@) handler, which is problematic b/c it requires
4447 polluting the global namespace with 'shell'. This in turn is
4463 polluting the global namespace with 'shell'. This in turn is
4448 fragile: if a user redefines a variable called shell, things
4464 fragile: if a user redefines a variable called shell, things
4449 break.
4465 break.
4450
4466
4451 - magic @: all functions available through @ need to be defined
4467 - magic @: all functions available through @ need to be defined
4452 as magic_<name>, even though they can be called simply as
4468 as magic_<name>, even though they can be called simply as
4453 @<name>. This allows the special command @magic to gather
4469 @<name>. This allows the special command @magic to gather
4454 information automatically about all existing magic functions,
4470 information automatically about all existing magic functions,
4455 even if they are run-time user extensions, by parsing the shell
4471 even if they are run-time user extensions, by parsing the shell
4456 instance __dict__ looking for special magic_ names.
4472 instance __dict__ looking for special magic_ names.
4457
4473
4458 - mainloop: added *two* local namespace parameters. This allows
4474 - mainloop: added *two* local namespace parameters. This allows
4459 the class to differentiate between parameters which were there
4475 the class to differentiate between parameters which were there
4460 before and after command line initialization was processed. This
4476 before and after command line initialization was processed. This
4461 way, later @who can show things loaded at startup by the
4477 way, later @who can show things loaded at startup by the
4462 user. This trick was necessary to make session saving/reloading
4478 user. This trick was necessary to make session saving/reloading
4463 really work: ideally after saving/exiting/reloading a session,
4479 really work: ideally after saving/exiting/reloading a session,
4464 *everythin* should look the same, including the output of @who. I
4480 *everythin* should look the same, including the output of @who. I
4465 was only able to make this work with this double namespace
4481 was only able to make this work with this double namespace
4466 trick.
4482 trick.
4467
4483
4468 - added a header to the logfile which allows (almost) full
4484 - added a header to the logfile which allows (almost) full
4469 session restoring.
4485 session restoring.
4470
4486
4471 - prepend lines beginning with @ or !, with a and log
4487 - prepend lines beginning with @ or !, with a and log
4472 them. Why? !lines: may be useful to know what you did @lines:
4488 them. Why? !lines: may be useful to know what you did @lines:
4473 they may affect session state. So when restoring a session, at
4489 they may affect session state. So when restoring a session, at
4474 least inform the user of their presence. I couldn't quite get
4490 least inform the user of their presence. I couldn't quite get
4475 them to properly re-execute, but at least the user is warned.
4491 them to properly re-execute, but at least the user is warned.
4476
4492
4477 * Started ChangeLog.
4493 * Started ChangeLog.
@@ -1,149 +1,150 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
2 # -*- coding: utf-8 -*-
3 """Setup script for IPython.
3 """Setup script for IPython.
4
4
5 Under Posix environments it works like a typical setup.py script.
5 Under Posix environments it works like a typical setup.py script.
6 Under Windows, the command sdist is not supported, since IPython
6 Under Windows, the command sdist is not supported, since IPython
7 requires utilities, which are not available under Windows."""
7 requires utilities, which are not available under Windows."""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2005 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 import sys, os
16 import sys, os
17 from glob import glob
17 from glob import glob
18 from setupext import install_data_ext
18 from setupext import install_data_ext
19 isfile = os.path.isfile
19 isfile = os.path.isfile
20
20
21 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
21 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
22 # update it when the contents of directories change.
22 # update it when the contents of directories change.
23 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
23 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
24
24
25 if os.name == 'posix':
25 if os.name == 'posix':
26 os_name = 'posix'
26 os_name = 'posix'
27 elif os.name in ['nt','dos']:
27 elif os.name in ['nt','dos']:
28 os_name = 'windows'
28 os_name = 'windows'
29 else:
29 else:
30 print 'Unsupported operating system:',os.name
30 print 'Unsupported operating system:',os.name
31 sys.exit(1)
31 sys.exit(1)
32
32
33 # Under Windows, 'sdist' is not supported, since it requires lyxport (and
33 # Under Windows, 'sdist' is not supported, since it requires lyxport (and
34 # hence lyx,perl,latex,pdflatex,latex2html,sh,...)
34 # hence lyx,perl,latex,pdflatex,latex2html,sh,...)
35 if os_name == 'windows' and sys.argv[1] == 'sdist':
35 if os_name == 'windows' and sys.argv[1] == 'sdist':
36 print 'The sdist command is not available under Windows. Exiting.'
36 print 'The sdist command is not available under Windows. Exiting.'
37 sys.exit(1)
37 sys.exit(1)
38
38
39 from distutils.core import setup
39 from distutils.core import setup
40
40
41 # update the manuals when building a source dist
41 # update the manuals when building a source dist
42 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
42 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
43 from IPython.genutils import target_update
43 from IPython.genutils import target_update
44 # list of things to be updated. Each entry is a triplet of args for
44 # list of things to be updated. Each entry is a triplet of args for
45 # target_update()
45 # target_update()
46 to_update = [('doc/magic.tex',
46 to_update = [('doc/magic.tex',
47 ['IPython/Magic.py'],
47 ['IPython/Magic.py'],
48 "cd doc && ./update_magic.sh" ),
48 "cd doc && ./update_magic.sh" ),
49
49
50 ('doc/manual.lyx',
50 ('doc/manual.lyx',
51 ['IPython/Release.py','doc/manual_base.lyx'],
51 ['IPython/Release.py','doc/manual_base.lyx'],
52 "cd doc && ./update_version.sh" ),
52 "cd doc && ./update_version.sh" ),
53
53
54 ('doc/manual/manual.html',
54 ('doc/manual/manual.html',
55 ['doc/manual.lyx',
55 ['doc/manual.lyx',
56 'doc/magic.tex',
56 'doc/magic.tex',
57 'doc/examples/example-gnuplot.py',
57 'doc/examples/example-gnuplot.py',
58 'doc/examples/example-magic.py',
58 'doc/examples/example-magic.py',
59 'doc/examples/example-embed.py',
59 'doc/examples/example-embed.py',
60 'doc/examples/example-embed-short.py',
60 'doc/examples/example-embed-short.py',
61 'IPython/UserConfig/ipythonrc',
61 'IPython/UserConfig/ipythonrc',
62 ],
62 ],
63 "cd doc && "
63 "cd doc && "
64 "lyxport -tt --leave --pdf "
64 "lyxport -tt --leave --pdf "
65 "--html -o '-noinfo -split +1 -local_icons' manual.lyx"),
65 "--html -o '-noinfo -split +1 -local_icons' manual.lyx"),
66
66
67 ('doc/new_design.pdf',
67 ('doc/new_design.pdf',
68 ['doc/new_design.lyx'],
68 ['doc/new_design.lyx'],
69 "cd doc && lyxport -tt --pdf new_design.lyx"),
69 "cd doc && lyxport -tt --pdf new_design.lyx"),
70
70
71 ('doc/ipython.1.gz',
71 ('doc/ipython.1.gz',
72 ['doc/ipython.1'],
72 ['doc/ipython.1'],
73 "cd doc && gzip -9c ipython.1 > ipython.1.gz"),
73 "cd doc && gzip -9c ipython.1 > ipython.1.gz"),
74
74
75 ('doc/pycolor.1.gz',
75 ('doc/pycolor.1.gz',
76 ['doc/pycolor.1'],
76 ['doc/pycolor.1'],
77 "cd doc && gzip -9c pycolor.1 > pycolor.1.gz"),
77 "cd doc && gzip -9c pycolor.1 > pycolor.1.gz"),
78 ]
78 ]
79 for target in to_update:
79 for target in to_update:
80 target_update(*target)
80 target_update(*target)
81
81
82 # Release.py contains version, authors, license, url, keywords, etc.
82 # Release.py contains version, authors, license, url, keywords, etc.
83 execfile(os.path.join('IPython','Release.py'))
83 execfile(os.path.join('IPython','Release.py'))
84
84
85 # A little utility we'll need below, since glob() does NOT allow you to do
85 # A little utility we'll need below, since glob() does NOT allow you to do
86 # exclusion on multiple endings!
86 # exclusion on multiple endings!
87 def file_doesnt_endwith(test,endings):
87 def file_doesnt_endwith(test,endings):
88 """Return true if test is a file and its name does NOT end with any
88 """Return true if test is a file and its name does NOT end with any
89 of the strings listed in endings."""
89 of the strings listed in endings."""
90 if not isfile(test):
90 if not isfile(test):
91 return False
91 return False
92 for e in endings:
92 for e in endings:
93 if test.endswith(e):
93 if test.endswith(e):
94 return False
94 return False
95 return True
95 return True
96
96
97 # I can't find how to make distutils create a nested dir. structure, so
97 # I can't find how to make distutils create a nested dir. structure, so
98 # in the meantime do it manually. Butt ugly.
98 # in the meantime do it manually. Butt ugly.
99 # Note that http://www.redbrick.dcu.ie/~noel/distutils.html, ex. 2/3, contain
99 # Note that http://www.redbrick.dcu.ie/~noel/distutils.html, ex. 2/3, contain
100 # information on how to do this more cleanly once python 2.4 can be assumed.
100 # information on how to do this more cleanly once python 2.4 can be assumed.
101 # Thanks to Noel for the tip.
101 # Thanks to Noel for the tip.
102 docdirbase = 'share/doc/ipython-%s' % version
102 docdirbase = 'share/doc/ipython-%s' % version
103 manpagebase = 'share/man/man1'
103 manpagebase = 'share/man/man1'
104
104
105 # We only need to exclude from this things NOT already excluded in the
105 # We only need to exclude from this things NOT already excluded in the
106 # MANIFEST.in file.
106 # MANIFEST.in file.
107 exclude = ('.sh','.1.gz')
107 exclude = ('.sh','.1.gz')
108 docfiles = filter(lambda f:file_doesnt_endwith(f,exclude),glob('doc/*'))
108 docfiles = filter(lambda f:file_doesnt_endwith(f,exclude),glob('doc/*'))
109
109
110 examfiles = filter(isfile, glob('doc/examples/*.py'))
110 examfiles = filter(isfile, glob('doc/examples/*.py'))
111 manfiles = filter(isfile, glob('doc/manual/*.html')) + \
111 manfiles = filter(isfile, glob('doc/manual/*.html')) + \
112 filter(isfile, glob('doc/manual/*.css')) + \
112 filter(isfile, glob('doc/manual/*.css')) + \
113 filter(isfile, glob('doc/manual/*.png'))
113 filter(isfile, glob('doc/manual/*.png'))
114 manpages = filter(isfile, glob('doc/*.1.gz'))
114 manpages = filter(isfile, glob('doc/*.1.gz'))
115 cfgfiles = filter(isfile, glob('IPython/UserConfig/*'))
115 cfgfiles = filter(isfile, glob('IPython/UserConfig/*'))
116 scriptfiles = filter(isfile, ['scripts/ipython','scripts/pycolor'])
116 scriptfiles = filter(isfile, ['scripts/ipython','scripts/pycolor'])
117
117
118 # Script to be run by the windows binary installer after the default setup
118 # Script to be run by the windows binary installer after the default setup
119 # routine, to add shortcuts and similar windows-only things. Windows
119 # routine, to add shortcuts and similar windows-only things. Windows
120 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
120 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
121 # doesn't find them.
121 # doesn't find them.
122 if 'bdist_wininst' in sys.argv:
122 if 'bdist_wininst' in sys.argv:
123 if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
123 if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
124 print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting."
124 print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting."
125 sys.exit(1)
125 sys.exit(1)
126 scriptfiles.append('scripts/ipython_win_post_install.py')
126 scriptfiles.append('scripts/ipython_win_post_install.py')
127
127
128 # Call the setup() routine which does most of the work
128 # Call the setup() routine which does most of the work
129 setup(name = name,
129 setup(name = name,
130 version = version,
130 version = version,
131 description = description,
131 description = description,
132 long_description = long_description,
132 long_description = long_description,
133 author = authors['Fernando'][0],
133 author = authors['Fernando'][0],
134 author_email = authors['Fernando'][1],
134 author_email = authors['Fernando'][1],
135 url = url,
135 url = url,
136 download_url = download_url,
136 license = license,
137 license = license,
137 platforms = platforms,
138 platforms = platforms,
138 keywords = keywords,
139 keywords = keywords,
139 packages = ['IPython', 'IPython.Extensions'],
140 packages = ['IPython', 'IPython.Extensions'],
140 scripts = scriptfiles,
141 scripts = scriptfiles,
141 cmdclass = {'install_data': install_data_ext},
142 cmdclass = {'install_data': install_data_ext},
142 data_files = [('data', docdirbase, docfiles),
143 data_files = [('data', docdirbase, docfiles),
143 ('data', os.path.join(docdirbase, 'examples'),
144 ('data', os.path.join(docdirbase, 'examples'),
144 examfiles),
145 examfiles),
145 ('data', os.path.join(docdirbase, 'manual'),
146 ('data', os.path.join(docdirbase, 'manual'),
146 manfiles),
147 manfiles),
147 ('data', manpagebase, manpages),
148 ('data', manpagebase, manpages),
148 ('lib', 'IPython/UserConfig', cfgfiles)]
149 ('lib', 'IPython/UserConfig', cfgfiles)]
149 )
150 )
General Comments 0
You need to be logged in to leave comments. Login now