##// END OF EJS Templates
- applied Nicolas Pernetty's patch to improve support for (X)Emacs under Win32....
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,164 +1,170 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 1005 2006-01-12 08:39:26Z fperez $"""
4 $Id: ColorANSI.py 2152 2007-03-18 20:13:35Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 from IPython import Release
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
15 __license__ = Release.license
16
16
17 __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
17 __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
18
18
19 import os
19 import os
20
20
21 from IPython.ipstruct import Struct
21 from IPython.ipstruct import Struct
22
22
23 def make_color_table(in_class):
23 def make_color_table(in_class):
24 """Build a set of color attributes in a class.
24 """Build a set of color attributes in a class.
25
25
26 Helper function for building the *TermColors classes."""
26 Helper function for building the *TermColors classes."""
27
27
28 color_templates = (
28 color_templates = (
29 ("Black" , "0;30"),
29 ("Black" , "0;30"),
30 ("Red" , "0;31"),
30 ("Red" , "0;31"),
31 ("Green" , "0;32"),
31 ("Green" , "0;32"),
32 ("Brown" , "0;33"),
32 ("Brown" , "0;33"),
33 ("Blue" , "0;34"),
33 ("Blue" , "0;34"),
34 ("Purple" , "0;35"),
34 ("Purple" , "0;35"),
35 ("Cyan" , "0;36"),
35 ("Cyan" , "0;36"),
36 ("LightGray" , "0;37"),
36 ("LightGray" , "0;37"),
37 ("DarkGray" , "1;30"),
37 ("DarkGray" , "1;30"),
38 ("LightRed" , "1;31"),
38 ("LightRed" , "1;31"),
39 ("LightGreen" , "1;32"),
39 ("LightGreen" , "1;32"),
40 ("Yellow" , "1;33"),
40 ("Yellow" , "1;33"),
41 ("LightBlue" , "1;34"),
41 ("LightBlue" , "1;34"),
42 ("LightPurple" , "1;35"),
42 ("LightPurple" , "1;35"),
43 ("LightCyan" , "1;36"),
43 ("LightCyan" , "1;36"),
44 ("White" , "1;37"), )
44 ("White" , "1;37"), )
45
45
46 for name,value in color_templates:
46 for name,value in color_templates:
47 setattr(in_class,name,in_class._base % value)
47 setattr(in_class,name,in_class._base % value)
48
48
49 class TermColors:
49 class TermColors:
50 """Color escape sequences.
50 """Color escape sequences.
51
51
52 This class defines the escape sequences for all the standard (ANSI?)
52 This class defines the escape sequences for all the standard (ANSI?)
53 colors in terminals. Also defines a NoColor escape which is just the null
53 colors in terminals. Also defines a NoColor escape which is just the null
54 string, suitable for defining 'dummy' color schemes in terminals which get
54 string, suitable for defining 'dummy' color schemes in terminals which get
55 confused by color escapes.
55 confused by color escapes.
56
56
57 This class should be used as a mixin for building color schemes."""
57 This class should be used as a mixin for building color schemes."""
58
58
59 NoColor = '' # for color schemes in color-less terminals.
59 NoColor = '' # for color schemes in color-less terminals.
60 Normal = '\033[0m' # Reset normal coloring
60 Normal = '\033[0m' # Reset normal coloring
61 _base = '\033[%sm' # Template for all other colors
61 _base = '\033[%sm' # Template for all other colors
62
62
63 # Build the actual color table as a set of class attributes:
63 # Build the actual color table as a set of class attributes:
64 make_color_table(TermColors)
64 make_color_table(TermColors)
65
65
66 class InputTermColors:
66 class InputTermColors:
67 """Color escape sequences for input prompts.
67 """Color escape sequences for input prompts.
68
68
69 This class is similar to TermColors, but the escapes are wrapped in \001
69 This class is similar to TermColors, but the escapes are wrapped in \001
70 and \002 so that readline can properly know the length of each line and
70 and \002 so that readline can properly know the length of each line and
71 can wrap lines accordingly. Use this class for any colored text which
71 can wrap lines accordingly. Use this class for any colored text which
72 needs to be used in input prompts, such as in calls to raw_input().
72 needs to be used in input prompts, such as in calls to raw_input().
73
73
74 This class defines the escape sequences for all the standard (ANSI?)
74 This class defines the escape sequences for all the standard (ANSI?)
75 colors in terminals. Also defines a NoColor escape which is just the null
75 colors in terminals. Also defines a NoColor escape which is just the null
76 string, suitable for defining 'dummy' color schemes in terminals which get
76 string, suitable for defining 'dummy' color schemes in terminals which get
77 confused by color escapes.
77 confused by color escapes.
78
78
79 This class should be used as a mixin for building color schemes."""
79 This class should be used as a mixin for building color schemes."""
80
80
81 NoColor = '' # for color schemes in color-less terminals.
81 NoColor = '' # for color schemes in color-less terminals.
82 Normal = '\001\033[0m\002' # Reset normal coloring
82
83 _base = '\001\033[%sm\002' # Template for all other colors
83 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
84 # (X)emacs on W32 gets confused with \001 and \002 so we remove them
85 Normal = '\033[0m' # Reset normal coloring
86 _base = '\033[%sm' # Template for all other colors
87 else:
88 Normal = '\001\033[0m\002' # Reset normal coloring
89 _base = '\001\033[%sm\002' # Template for all other colors
84
90
85 # Build the actual color table as a set of class attributes:
91 # Build the actual color table as a set of class attributes:
86 make_color_table(InputTermColors)
92 make_color_table(InputTermColors)
87
93
88 class ColorScheme:
94 class ColorScheme:
89 """Generic color scheme class. Just a name and a Struct."""
95 """Generic color scheme class. Just a name and a Struct."""
90 def __init__(self,__scheme_name_,colordict=None,**colormap):
96 def __init__(self,__scheme_name_,colordict=None,**colormap):
91 self.name = __scheme_name_
97 self.name = __scheme_name_
92 if colordict is None:
98 if colordict is None:
93 self.colors = Struct(**colormap)
99 self.colors = Struct(**colormap)
94 else:
100 else:
95 self.colors = Struct(colordict)
101 self.colors = Struct(colordict)
96
102
97 def copy(self,name=None):
103 def copy(self,name=None):
98 """Return a full copy of the object, optionally renaming it."""
104 """Return a full copy of the object, optionally renaming it."""
99 if name is None:
105 if name is None:
100 name = self.name
106 name = self.name
101 return ColorScheme(name,self.colors.__dict__)
107 return ColorScheme(name,self.colors.__dict__)
102
108
103 class ColorSchemeTable(dict):
109 class ColorSchemeTable(dict):
104 """General class to handle tables of color schemes.
110 """General class to handle tables of color schemes.
105
111
106 It's basically a dict of color schemes with a couple of shorthand
112 It's basically a dict of color schemes with a couple of shorthand
107 attributes and some convenient methods.
113 attributes and some convenient methods.
108
114
109 active_scheme_name -> obvious
115 active_scheme_name -> obvious
110 active_colors -> actual color table of the active scheme"""
116 active_colors -> actual color table of the active scheme"""
111
117
112 def __init__(self,scheme_list=None,default_scheme=''):
118 def __init__(self,scheme_list=None,default_scheme=''):
113 """Create a table of color schemes.
119 """Create a table of color schemes.
114
120
115 The table can be created empty and manually filled or it can be
121 The table can be created empty and manually filled or it can be
116 created with a list of valid color schemes AND the specification for
122 created with a list of valid color schemes AND the specification for
117 the default active scheme.
123 the default active scheme.
118 """
124 """
119
125
120 # create object attributes to be set later
126 # create object attributes to be set later
121 self.active_scheme_name = ''
127 self.active_scheme_name = ''
122 self.active_colors = None
128 self.active_colors = None
123
129
124 if scheme_list:
130 if scheme_list:
125 if default_scheme == '':
131 if default_scheme == '':
126 raise ValueError,'you must specify the default color scheme'
132 raise ValueError,'you must specify the default color scheme'
127 for scheme in scheme_list:
133 for scheme in scheme_list:
128 self.add_scheme(scheme)
134 self.add_scheme(scheme)
129 self.set_active_scheme(default_scheme)
135 self.set_active_scheme(default_scheme)
130
136
131 def copy(self):
137 def copy(self):
132 """Return full copy of object"""
138 """Return full copy of object"""
133 return ColorSchemeTable(self.values(),self.active_scheme_name)
139 return ColorSchemeTable(self.values(),self.active_scheme_name)
134
140
135 def add_scheme(self,new_scheme):
141 def add_scheme(self,new_scheme):
136 """Add a new color scheme to the table."""
142 """Add a new color scheme to the table."""
137 if not isinstance(new_scheme,ColorScheme):
143 if not isinstance(new_scheme,ColorScheme):
138 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
144 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
139 self[new_scheme.name] = new_scheme
145 self[new_scheme.name] = new_scheme
140
146
141 def set_active_scheme(self,scheme,case_sensitive=0):
147 def set_active_scheme(self,scheme,case_sensitive=0):
142 """Set the currently active scheme.
148 """Set the currently active scheme.
143
149
144 Names are by default compared in a case-insensitive way, but this can
150 Names are by default compared in a case-insensitive way, but this can
145 be changed by setting the parameter case_sensitive to true."""
151 be changed by setting the parameter case_sensitive to true."""
146
152
147 scheme_names = self.keys()
153 scheme_names = self.keys()
148 if case_sensitive:
154 if case_sensitive:
149 valid_schemes = scheme_names
155 valid_schemes = scheme_names
150 scheme_test = scheme
156 scheme_test = scheme
151 else:
157 else:
152 valid_schemes = [s.lower() for s in scheme_names]
158 valid_schemes = [s.lower() for s in scheme_names]
153 scheme_test = scheme.lower()
159 scheme_test = scheme.lower()
154 try:
160 try:
155 scheme_idx = valid_schemes.index(scheme_test)
161 scheme_idx = valid_schemes.index(scheme_test)
156 except ValueError:
162 except ValueError:
157 raise ValueError,'Unrecognized color scheme: ' + scheme + \
163 raise ValueError,'Unrecognized color scheme: ' + scheme + \
158 '\nValid schemes: '+str(scheme_names).replace("'', ",'')
164 '\nValid schemes: '+str(scheme_names).replace("'', ",'')
159 else:
165 else:
160 active = scheme_names[scheme_idx]
166 active = scheme_names[scheme_idx]
161 self.active_scheme_name = active
167 self.active_scheme_name = active
162 self.active_colors = self[active].colors
168 self.active_colors = self[active].colors
163 # Now allow using '' as an index for the current active scheme
169 # Now allow using '' as an index for the current active scheme
164 self[''] = self[active]
170 self[''] = self[active]
@@ -1,1751 +1,1752 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 General purpose utilities.
3 General purpose utilities.
4
4
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 2108 2007-02-23 00:31:17Z fperez $"""
8 $Id: genutils.py 2152 2007-03-18 20:13:35Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __license__ = Release.license
19 __license__ = Release.license
20
20
21 #****************************************************************************
21 #****************************************************************************
22 # required modules from the Python standard library
22 # required modules from the Python standard library
23 import __main__
23 import __main__
24 import commands
24 import commands
25 import os
25 import os
26 import re
26 import re
27 import shlex
27 import shlex
28 import shutil
28 import shutil
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import time
31 import time
32 import types
32 import types
33 import warnings
33 import warnings
34
34
35 # Other IPython utilities
35 # Other IPython utilities
36 from IPython.Itpl import Itpl,itpl,printpl
36 from IPython.Itpl import Itpl,itpl,printpl
37 from IPython import DPyGetOpt
37 from IPython import DPyGetOpt
38 from path import path
38 from path import path
39 if os.name == "nt":
39 if os.name == "nt":
40 from IPython.winconsole import get_console_size
40 from IPython.winconsole import get_console_size
41
41
42 #****************************************************************************
42 #****************************************************************************
43 # Exceptions
43 # Exceptions
44 class Error(Exception):
44 class Error(Exception):
45 """Base class for exceptions in this module."""
45 """Base class for exceptions in this module."""
46 pass
46 pass
47
47
48 #----------------------------------------------------------------------------
48 #----------------------------------------------------------------------------
49 class IOStream:
49 class IOStream:
50 def __init__(self,stream,fallback):
50 def __init__(self,stream,fallback):
51 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
51 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
52 stream = fallback
52 stream = fallback
53 self.stream = stream
53 self.stream = stream
54 self._swrite = stream.write
54 self._swrite = stream.write
55 self.flush = stream.flush
55 self.flush = stream.flush
56
56
57 def write(self,data):
57 def write(self,data):
58 try:
58 try:
59 self._swrite(data)
59 self._swrite(data)
60 except:
60 except:
61 try:
61 try:
62 # print handles some unicode issues which may trip a plain
62 # print handles some unicode issues which may trip a plain
63 # write() call. Attempt to emulate write() by using a
63 # write() call. Attempt to emulate write() by using a
64 # trailing comma
64 # trailing comma
65 print >> self.stream, data,
65 print >> self.stream, data,
66 except:
66 except:
67 # if we get here, something is seriously broken.
67 # if we get here, something is seriously broken.
68 print >> sys.stderr, \
68 print >> sys.stderr, \
69 'ERROR - failed to write data to stream:', self.stream
69 'ERROR - failed to write data to stream:', self.stream
70
70
71 class IOTerm:
71 class IOTerm:
72 """ Term holds the file or file-like objects for handling I/O operations.
72 """ Term holds the file or file-like objects for handling I/O operations.
73
73
74 These are normally just sys.stdin, sys.stdout and sys.stderr but for
74 These are normally just sys.stdin, sys.stdout and sys.stderr but for
75 Windows they can can replaced to allow editing the strings before they are
75 Windows they can can replaced to allow editing the strings before they are
76 displayed."""
76 displayed."""
77
77
78 # In the future, having IPython channel all its I/O operations through
78 # In the future, having IPython channel all its I/O operations through
79 # this class will make it easier to embed it into other environments which
79 # this class will make it easier to embed it into other environments which
80 # are not a normal terminal (such as a GUI-based shell)
80 # are not a normal terminal (such as a GUI-based shell)
81 def __init__(self,cin=None,cout=None,cerr=None):
81 def __init__(self,cin=None,cout=None,cerr=None):
82 self.cin = IOStream(cin,sys.stdin)
82 self.cin = IOStream(cin,sys.stdin)
83 self.cout = IOStream(cout,sys.stdout)
83 self.cout = IOStream(cout,sys.stdout)
84 self.cerr = IOStream(cerr,sys.stderr)
84 self.cerr = IOStream(cerr,sys.stderr)
85
85
86 # Global variable to be used for all I/O
86 # Global variable to be used for all I/O
87 Term = IOTerm()
87 Term = IOTerm()
88
88
89 import IPython.rlineimpl as readline
89 import IPython.rlineimpl as readline
90 # Remake Term to use the readline i/o facilities
90 # Remake Term to use the readline i/o facilities
91 if sys.platform == 'win32' and readline.have_readline:
91 if sys.platform == 'win32' and readline.have_readline:
92
92
93 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
93 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
94
94
95
95
96 #****************************************************************************
96 #****************************************************************************
97 # Generic warning/error printer, used by everything else
97 # Generic warning/error printer, used by everything else
98 def warn(msg,level=2,exit_val=1):
98 def warn(msg,level=2,exit_val=1):
99 """Standard warning printer. Gives formatting consistency.
99 """Standard warning printer. Gives formatting consistency.
100
100
101 Output is sent to Term.cerr (sys.stderr by default).
101 Output is sent to Term.cerr (sys.stderr by default).
102
102
103 Options:
103 Options:
104
104
105 -level(2): allows finer control:
105 -level(2): allows finer control:
106 0 -> Do nothing, dummy function.
106 0 -> Do nothing, dummy function.
107 1 -> Print message.
107 1 -> Print message.
108 2 -> Print 'WARNING:' + message. (Default level).
108 2 -> Print 'WARNING:' + message. (Default level).
109 3 -> Print 'ERROR:' + message.
109 3 -> Print 'ERROR:' + message.
110 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
110 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
111
111
112 -exit_val (1): exit value returned by sys.exit() for a level 4
112 -exit_val (1): exit value returned by sys.exit() for a level 4
113 warning. Ignored for all other levels."""
113 warning. Ignored for all other levels."""
114
114
115 if level>0:
115 if level>0:
116 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
116 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
117 print >> Term.cerr, '%s%s' % (header[level],msg)
117 print >> Term.cerr, '%s%s' % (header[level],msg)
118 if level == 4:
118 if level == 4:
119 print >> Term.cerr,'Exiting.\n'
119 print >> Term.cerr,'Exiting.\n'
120 sys.exit(exit_val)
120 sys.exit(exit_val)
121
121
122 def info(msg):
122 def info(msg):
123 """Equivalent to warn(msg,level=1)."""
123 """Equivalent to warn(msg,level=1)."""
124
124
125 warn(msg,level=1)
125 warn(msg,level=1)
126
126
127 def error(msg):
127 def error(msg):
128 """Equivalent to warn(msg,level=3)."""
128 """Equivalent to warn(msg,level=3)."""
129
129
130 warn(msg,level=3)
130 warn(msg,level=3)
131
131
132 def fatal(msg,exit_val=1):
132 def fatal(msg,exit_val=1):
133 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
133 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
134
134
135 warn(msg,exit_val=exit_val,level=4)
135 warn(msg,exit_val=exit_val,level=4)
136
136
137 #---------------------------------------------------------------------------
137 #---------------------------------------------------------------------------
138 # Debugging routines
138 # Debugging routines
139 #
139 #
140 def debugx(expr,pre_msg=''):
140 def debugx(expr,pre_msg=''):
141 """Print the value of an expression from the caller's frame.
141 """Print the value of an expression from the caller's frame.
142
142
143 Takes an expression, evaluates it in the caller's frame and prints both
143 Takes an expression, evaluates it in the caller's frame and prints both
144 the given expression and the resulting value (as well as a debug mark
144 the given expression and the resulting value (as well as a debug mark
145 indicating the name of the calling function. The input must be of a form
145 indicating the name of the calling function. The input must be of a form
146 suitable for eval().
146 suitable for eval().
147
147
148 An optional message can be passed, which will be prepended to the printed
148 An optional message can be passed, which will be prepended to the printed
149 expr->value pair."""
149 expr->value pair."""
150
150
151 cf = sys._getframe(1)
151 cf = sys._getframe(1)
152 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
152 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
153 eval(expr,cf.f_globals,cf.f_locals))
153 eval(expr,cf.f_globals,cf.f_locals))
154
154
155 # deactivate it by uncommenting the following line, which makes it a no-op
155 # deactivate it by uncommenting the following line, which makes it a no-op
156 #def debugx(expr,pre_msg=''): pass
156 #def debugx(expr,pre_msg=''): pass
157
157
158 #----------------------------------------------------------------------------
158 #----------------------------------------------------------------------------
159 StringTypes = types.StringTypes
159 StringTypes = types.StringTypes
160
160
161 # Basic timing functionality
161 # Basic timing functionality
162
162
163 # If possible (Unix), use the resource module instead of time.clock()
163 # If possible (Unix), use the resource module instead of time.clock()
164 try:
164 try:
165 import resource
165 import resource
166 def clocku():
166 def clocku():
167 """clocku() -> floating point number
167 """clocku() -> floating point number
168
168
169 Return the *USER* CPU time in seconds since the start of the process.
169 Return the *USER* CPU time in seconds since the start of the process.
170 This is done via a call to resource.getrusage, so it avoids the
170 This is done via a call to resource.getrusage, so it avoids the
171 wraparound problems in time.clock()."""
171 wraparound problems in time.clock()."""
172
172
173 return resource.getrusage(resource.RUSAGE_SELF)[0]
173 return resource.getrusage(resource.RUSAGE_SELF)[0]
174
174
175 def clocks():
175 def clocks():
176 """clocks() -> floating point number
176 """clocks() -> floating point number
177
177
178 Return the *SYSTEM* CPU time in seconds since the start of the process.
178 Return the *SYSTEM* CPU time in seconds since the start of the process.
179 This is done via a call to resource.getrusage, so it avoids the
179 This is done via a call to resource.getrusage, so it avoids the
180 wraparound problems in time.clock()."""
180 wraparound problems in time.clock()."""
181
181
182 return resource.getrusage(resource.RUSAGE_SELF)[1]
182 return resource.getrusage(resource.RUSAGE_SELF)[1]
183
183
184 def clock():
184 def clock():
185 """clock() -> floating point number
185 """clock() -> floating point number
186
186
187 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
187 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
188 the process. This is done via a call to resource.getrusage, so it
188 the process. This is done via a call to resource.getrusage, so it
189 avoids the wraparound problems in time.clock()."""
189 avoids the wraparound problems in time.clock()."""
190
190
191 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
191 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
192 return u+s
192 return u+s
193
193
194 def clock2():
194 def clock2():
195 """clock2() -> (t_user,t_system)
195 """clock2() -> (t_user,t_system)
196
196
197 Similar to clock(), but return a tuple of user/system times."""
197 Similar to clock(), but return a tuple of user/system times."""
198 return resource.getrusage(resource.RUSAGE_SELF)[:2]
198 return resource.getrusage(resource.RUSAGE_SELF)[:2]
199
199
200 except ImportError:
200 except ImportError:
201 # There is no distinction of user/system time under windows, so we just use
201 # There is no distinction of user/system time under windows, so we just use
202 # time.clock() for everything...
202 # time.clock() for everything...
203 clocku = clocks = clock = time.clock
203 clocku = clocks = clock = time.clock
204 def clock2():
204 def clock2():
205 """Under windows, system CPU time can't be measured.
205 """Under windows, system CPU time can't be measured.
206
206
207 This just returns clock() and zero."""
207 This just returns clock() and zero."""
208 return time.clock(),0.0
208 return time.clock(),0.0
209
209
210 def timings_out(reps,func,*args,**kw):
210 def timings_out(reps,func,*args,**kw):
211 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
211 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
212
212
213 Execute a function reps times, return a tuple with the elapsed total
213 Execute a function reps times, return a tuple with the elapsed total
214 CPU time in seconds, the time per call and the function's output.
214 CPU time in seconds, the time per call and the function's output.
215
215
216 Under Unix, the return value is the sum of user+system time consumed by
216 Under Unix, the return value is the sum of user+system time consumed by
217 the process, computed via the resource module. This prevents problems
217 the process, computed via the resource module. This prevents problems
218 related to the wraparound effect which the time.clock() function has.
218 related to the wraparound effect which the time.clock() function has.
219
219
220 Under Windows the return value is in wall clock seconds. See the
220 Under Windows the return value is in wall clock seconds. See the
221 documentation for the time module for more details."""
221 documentation for the time module for more details."""
222
222
223 reps = int(reps)
223 reps = int(reps)
224 assert reps >=1, 'reps must be >= 1'
224 assert reps >=1, 'reps must be >= 1'
225 if reps==1:
225 if reps==1:
226 start = clock()
226 start = clock()
227 out = func(*args,**kw)
227 out = func(*args,**kw)
228 tot_time = clock()-start
228 tot_time = clock()-start
229 else:
229 else:
230 rng = xrange(reps-1) # the last time is executed separately to store output
230 rng = xrange(reps-1) # the last time is executed separately to store output
231 start = clock()
231 start = clock()
232 for dummy in rng: func(*args,**kw)
232 for dummy in rng: func(*args,**kw)
233 out = func(*args,**kw) # one last time
233 out = func(*args,**kw) # one last time
234 tot_time = clock()-start
234 tot_time = clock()-start
235 av_time = tot_time / reps
235 av_time = tot_time / reps
236 return tot_time,av_time,out
236 return tot_time,av_time,out
237
237
238 def timings(reps,func,*args,**kw):
238 def timings(reps,func,*args,**kw):
239 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
239 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
240
240
241 Execute a function reps times, return a tuple with the elapsed total CPU
241 Execute a function reps times, return a tuple with the elapsed total CPU
242 time in seconds and the time per call. These are just the first two values
242 time in seconds and the time per call. These are just the first two values
243 in timings_out()."""
243 in timings_out()."""
244
244
245 return timings_out(reps,func,*args,**kw)[0:2]
245 return timings_out(reps,func,*args,**kw)[0:2]
246
246
247 def timing(func,*args,**kw):
247 def timing(func,*args,**kw):
248 """timing(func,*args,**kw) -> t_total
248 """timing(func,*args,**kw) -> t_total
249
249
250 Execute a function once, return the elapsed total CPU time in
250 Execute a function once, return the elapsed total CPU time in
251 seconds. This is just the first value in timings_out()."""
251 seconds. This is just the first value in timings_out()."""
252
252
253 return timings_out(1,func,*args,**kw)[0]
253 return timings_out(1,func,*args,**kw)[0]
254
254
255 #****************************************************************************
255 #****************************************************************************
256 # file and system
256 # file and system
257
257
258 def arg_split(s,posix=False):
258 def arg_split(s,posix=False):
259 """Split a command line's arguments in a shell-like manner.
259 """Split a command line's arguments in a shell-like manner.
260
260
261 This is a modified version of the standard library's shlex.split()
261 This is a modified version of the standard library's shlex.split()
262 function, but with a default of posix=False for splitting, so that quotes
262 function, but with a default of posix=False for splitting, so that quotes
263 in inputs are respected."""
263 in inputs are respected."""
264
264
265 lex = shlex.shlex(s, posix=posix)
265 lex = shlex.shlex(s, posix=posix)
266 lex.whitespace_split = True
266 lex.whitespace_split = True
267 return list(lex)
267 return list(lex)
268
268
269 def system(cmd,verbose=0,debug=0,header=''):
269 def system(cmd,verbose=0,debug=0,header=''):
270 """Execute a system command, return its exit status.
270 """Execute a system command, return its exit status.
271
271
272 Options:
272 Options:
273
273
274 - verbose (0): print the command to be executed.
274 - verbose (0): print the command to be executed.
275
275
276 - debug (0): only print, do not actually execute.
276 - debug (0): only print, do not actually execute.
277
277
278 - header (''): Header to print on screen prior to the executed command (it
278 - header (''): Header to print on screen prior to the executed command (it
279 is only prepended to the command, no newlines are added).
279 is only prepended to the command, no newlines are added).
280
280
281 Note: a stateful version of this function is available through the
281 Note: a stateful version of this function is available through the
282 SystemExec class."""
282 SystemExec class."""
283
283
284 stat = 0
284 stat = 0
285 if verbose or debug: print header+cmd
285 if verbose or debug: print header+cmd
286 sys.stdout.flush()
286 sys.stdout.flush()
287 if not debug: stat = os.system(cmd)
287 if not debug: stat = os.system(cmd)
288 return stat
288 return stat
289
289
290 # This function is used by ipython in a lot of places to make system calls.
290 # This function is used by ipython in a lot of places to make system calls.
291 # We need it to be slightly different under win32, due to the vagaries of
291 # We need it to be slightly different under win32, due to the vagaries of
292 # 'network shares'. A win32 override is below.
292 # 'network shares'. A win32 override is below.
293
293
294 def shell(cmd,verbose=0,debug=0,header=''):
294 def shell(cmd,verbose=0,debug=0,header=''):
295 """Execute a command in the system shell, always return None.
295 """Execute a command in the system shell, always return None.
296
296
297 Options:
297 Options:
298
298
299 - verbose (0): print the command to be executed.
299 - verbose (0): print the command to be executed.
300
300
301 - debug (0): only print, do not actually execute.
301 - debug (0): only print, do not actually execute.
302
302
303 - header (''): Header to print on screen prior to the executed command (it
303 - header (''): Header to print on screen prior to the executed command (it
304 is only prepended to the command, no newlines are added).
304 is only prepended to the command, no newlines are added).
305
305
306 Note: this is similar to genutils.system(), but it returns None so it can
306 Note: this is similar to genutils.system(), but it returns None so it can
307 be conveniently used in interactive loops without getting the return value
307 be conveniently used in interactive loops without getting the return value
308 (typically 0) printed many times."""
308 (typically 0) printed many times."""
309
309
310 stat = 0
310 stat = 0
311 if verbose or debug: print header+cmd
311 if verbose or debug: print header+cmd
312 # flush stdout so we don't mangle python's buffering
312 # flush stdout so we don't mangle python's buffering
313 sys.stdout.flush()
313 sys.stdout.flush()
314 if not debug:
314 if not debug:
315 os.system(cmd)
315 os.system(cmd)
316
316
317 # override shell() for win32 to deal with network shares
317 # override shell() for win32 to deal with network shares
318 if os.name in ('nt','dos'):
318 if os.name in ('nt','dos'):
319
319
320 shell_ori = shell
320 shell_ori = shell
321
321
322 def shell(cmd,verbose=0,debug=0,header=''):
322 def shell(cmd,verbose=0,debug=0,header=''):
323 if os.getcwd().startswith(r"\\"):
323 if os.getcwd().startswith(r"\\"):
324 path = os.getcwd()
324 path = os.getcwd()
325 # change to c drive (cannot be on UNC-share when issuing os.system,
325 # change to c drive (cannot be on UNC-share when issuing os.system,
326 # as cmd.exe cannot handle UNC addresses)
326 # as cmd.exe cannot handle UNC addresses)
327 os.chdir("c:")
327 os.chdir("c:")
328 # issue pushd to the UNC-share and then run the command
328 # issue pushd to the UNC-share and then run the command
329 try:
329 try:
330 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
330 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
331 finally:
331 finally:
332 os.chdir(path)
332 os.chdir(path)
333 else:
333 else:
334 shell_ori(cmd,verbose,debug,header)
334 shell_ori(cmd,verbose,debug,header)
335
335
336 shell.__doc__ = shell_ori.__doc__
336 shell.__doc__ = shell_ori.__doc__
337
337
338 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
338 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
339 """Dummy substitute for perl's backquotes.
339 """Dummy substitute for perl's backquotes.
340
340
341 Executes a command and returns the output.
341 Executes a command and returns the output.
342
342
343 Accepts the same arguments as system(), plus:
343 Accepts the same arguments as system(), plus:
344
344
345 - split(0): if true, the output is returned as a list split on newlines.
345 - split(0): if true, the output is returned as a list split on newlines.
346
346
347 Note: a stateful version of this function is available through the
347 Note: a stateful version of this function is available through the
348 SystemExec class.
348 SystemExec class.
349
349
350 This is pretty much deprecated and rarely used,
350 This is pretty much deprecated and rarely used,
351 genutils.getoutputerror may be what you need.
351 genutils.getoutputerror may be what you need.
352
352
353 """
353 """
354
354
355 if verbose or debug: print header+cmd
355 if verbose or debug: print header+cmd
356 if not debug:
356 if not debug:
357 output = os.popen(cmd).read()
357 output = os.popen(cmd).read()
358 # stipping last \n is here for backwards compat.
358 # stipping last \n is here for backwards compat.
359 if output.endswith('\n'):
359 if output.endswith('\n'):
360 output = output[:-1]
360 output = output[:-1]
361 if split:
361 if split:
362 return output.split('\n')
362 return output.split('\n')
363 else:
363 else:
364 return output
364 return output
365
365
366 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
366 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
367 """Return (standard output,standard error) of executing cmd in a shell.
367 """Return (standard output,standard error) of executing cmd in a shell.
368
368
369 Accepts the same arguments as system(), plus:
369 Accepts the same arguments as system(), plus:
370
370
371 - split(0): if true, each of stdout/err is returned as a list split on
371 - split(0): if true, each of stdout/err is returned as a list split on
372 newlines.
372 newlines.
373
373
374 Note: a stateful version of this function is available through the
374 Note: a stateful version of this function is available through the
375 SystemExec class."""
375 SystemExec class."""
376
376
377 if verbose or debug: print header+cmd
377 if verbose or debug: print header+cmd
378 if not cmd:
378 if not cmd:
379 if split:
379 if split:
380 return [],[]
380 return [],[]
381 else:
381 else:
382 return '',''
382 return '',''
383 if not debug:
383 if not debug:
384 pin,pout,perr = os.popen3(cmd)
384 pin,pout,perr = os.popen3(cmd)
385 tout = pout.read().rstrip()
385 tout = pout.read().rstrip()
386 terr = perr.read().rstrip()
386 terr = perr.read().rstrip()
387 pin.close()
387 pin.close()
388 pout.close()
388 pout.close()
389 perr.close()
389 perr.close()
390 if split:
390 if split:
391 return tout.split('\n'),terr.split('\n')
391 return tout.split('\n'),terr.split('\n')
392 else:
392 else:
393 return tout,terr
393 return tout,terr
394
394
395 # for compatibility with older naming conventions
395 # for compatibility with older naming conventions
396 xsys = system
396 xsys = system
397 bq = getoutput
397 bq = getoutput
398
398
399 class SystemExec:
399 class SystemExec:
400 """Access the system and getoutput functions through a stateful interface.
400 """Access the system and getoutput functions through a stateful interface.
401
401
402 Note: here we refer to the system and getoutput functions from this
402 Note: here we refer to the system and getoutput functions from this
403 library, not the ones from the standard python library.
403 library, not the ones from the standard python library.
404
404
405 This class offers the system and getoutput functions as methods, but the
405 This class offers the system and getoutput functions as methods, but the
406 verbose, debug and header parameters can be set for the instance (at
406 verbose, debug and header parameters can be set for the instance (at
407 creation time or later) so that they don't need to be specified on each
407 creation time or later) so that they don't need to be specified on each
408 call.
408 call.
409
409
410 For efficiency reasons, there's no way to override the parameters on a
410 For efficiency reasons, there's no way to override the parameters on a
411 per-call basis other than by setting instance attributes. If you need
411 per-call basis other than by setting instance attributes. If you need
412 local overrides, it's best to directly call system() or getoutput().
412 local overrides, it's best to directly call system() or getoutput().
413
413
414 The following names are provided as alternate options:
414 The following names are provided as alternate options:
415 - xsys: alias to system
415 - xsys: alias to system
416 - bq: alias to getoutput
416 - bq: alias to getoutput
417
417
418 An instance can then be created as:
418 An instance can then be created as:
419 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
419 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
420
420
421 And used as:
421 And used as:
422 >>> sysexec.xsys('pwd')
422 >>> sysexec.xsys('pwd')
423 >>> dirlist = sysexec.bq('ls -l')
423 >>> dirlist = sysexec.bq('ls -l')
424 """
424 """
425
425
426 def __init__(self,verbose=0,debug=0,header='',split=0):
426 def __init__(self,verbose=0,debug=0,header='',split=0):
427 """Specify the instance's values for verbose, debug and header."""
427 """Specify the instance's values for verbose, debug and header."""
428 setattr_list(self,'verbose debug header split')
428 setattr_list(self,'verbose debug header split')
429
429
430 def system(self,cmd):
430 def system(self,cmd):
431 """Stateful interface to system(), with the same keyword parameters."""
431 """Stateful interface to system(), with the same keyword parameters."""
432
432
433 system(cmd,self.verbose,self.debug,self.header)
433 system(cmd,self.verbose,self.debug,self.header)
434
434
435 def shell(self,cmd):
435 def shell(self,cmd):
436 """Stateful interface to shell(), with the same keyword parameters."""
436 """Stateful interface to shell(), with the same keyword parameters."""
437
437
438 shell(cmd,self.verbose,self.debug,self.header)
438 shell(cmd,self.verbose,self.debug,self.header)
439
439
440 xsys = system # alias
440 xsys = system # alias
441
441
442 def getoutput(self,cmd):
442 def getoutput(self,cmd):
443 """Stateful interface to getoutput()."""
443 """Stateful interface to getoutput()."""
444
444
445 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
445 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
446
446
447 def getoutputerror(self,cmd):
447 def getoutputerror(self,cmd):
448 """Stateful interface to getoutputerror()."""
448 """Stateful interface to getoutputerror()."""
449
449
450 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
450 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
451
451
452 bq = getoutput # alias
452 bq = getoutput # alias
453
453
454 #-----------------------------------------------------------------------------
454 #-----------------------------------------------------------------------------
455 def mutex_opts(dict,ex_op):
455 def mutex_opts(dict,ex_op):
456 """Check for presence of mutually exclusive keys in a dict.
456 """Check for presence of mutually exclusive keys in a dict.
457
457
458 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
458 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
459 for op1,op2 in ex_op:
459 for op1,op2 in ex_op:
460 if op1 in dict and op2 in dict:
460 if op1 in dict and op2 in dict:
461 raise ValueError,'\n*** ERROR in Arguments *** '\
461 raise ValueError,'\n*** ERROR in Arguments *** '\
462 'Options '+op1+' and '+op2+' are mutually exclusive.'
462 'Options '+op1+' and '+op2+' are mutually exclusive.'
463
463
464 #-----------------------------------------------------------------------------
464 #-----------------------------------------------------------------------------
465 def get_py_filename(name):
465 def get_py_filename(name):
466 """Return a valid python filename in the current directory.
466 """Return a valid python filename in the current directory.
467
467
468 If the given name is not a file, it adds '.py' and searches again.
468 If the given name is not a file, it adds '.py' and searches again.
469 Raises IOError with an informative message if the file isn't found."""
469 Raises IOError with an informative message if the file isn't found."""
470
470
471 name = os.path.expanduser(name)
471 name = os.path.expanduser(name)
472 if not os.path.isfile(name) and not name.endswith('.py'):
472 if not os.path.isfile(name) and not name.endswith('.py'):
473 name += '.py'
473 name += '.py'
474 if os.path.isfile(name):
474 if os.path.isfile(name):
475 return name
475 return name
476 else:
476 else:
477 raise IOError,'File `%s` not found.' % name
477 raise IOError,'File `%s` not found.' % name
478
478
479 #-----------------------------------------------------------------------------
479 #-----------------------------------------------------------------------------
480 def filefind(fname,alt_dirs = None):
480 def filefind(fname,alt_dirs = None):
481 """Return the given filename either in the current directory, if it
481 """Return the given filename either in the current directory, if it
482 exists, or in a specified list of directories.
482 exists, or in a specified list of directories.
483
483
484 ~ expansion is done on all file and directory names.
484 ~ expansion is done on all file and directory names.
485
485
486 Upon an unsuccessful search, raise an IOError exception."""
486 Upon an unsuccessful search, raise an IOError exception."""
487
487
488 if alt_dirs is None:
488 if alt_dirs is None:
489 try:
489 try:
490 alt_dirs = get_home_dir()
490 alt_dirs = get_home_dir()
491 except HomeDirError:
491 except HomeDirError:
492 alt_dirs = os.getcwd()
492 alt_dirs = os.getcwd()
493 search = [fname] + list_strings(alt_dirs)
493 search = [fname] + list_strings(alt_dirs)
494 search = map(os.path.expanduser,search)
494 search = map(os.path.expanduser,search)
495 #print 'search list for',fname,'list:',search # dbg
495 #print 'search list for',fname,'list:',search # dbg
496 fname = search[0]
496 fname = search[0]
497 if os.path.isfile(fname):
497 if os.path.isfile(fname):
498 return fname
498 return fname
499 for direc in search[1:]:
499 for direc in search[1:]:
500 testname = os.path.join(direc,fname)
500 testname = os.path.join(direc,fname)
501 #print 'testname',testname # dbg
501 #print 'testname',testname # dbg
502 if os.path.isfile(testname):
502 if os.path.isfile(testname):
503 return testname
503 return testname
504 raise IOError,'File' + `fname` + \
504 raise IOError,'File' + `fname` + \
505 ' not found in current or supplied directories:' + `alt_dirs`
505 ' not found in current or supplied directories:' + `alt_dirs`
506
506
507 #----------------------------------------------------------------------------
507 #----------------------------------------------------------------------------
508 def file_read(filename):
508 def file_read(filename):
509 """Read a file and close it. Returns the file source."""
509 """Read a file and close it. Returns the file source."""
510 fobj = open(filename,'r');
510 fobj = open(filename,'r');
511 source = fobj.read();
511 source = fobj.read();
512 fobj.close()
512 fobj.close()
513 return source
513 return source
514
514
515 def file_readlines(filename):
515 def file_readlines(filename):
516 """Read a file and close it. Returns the file source using readlines()."""
516 """Read a file and close it. Returns the file source using readlines()."""
517 fobj = open(filename,'r');
517 fobj = open(filename,'r');
518 lines = fobj.readlines();
518 lines = fobj.readlines();
519 fobj.close()
519 fobj.close()
520 return lines
520 return lines
521
521
522 #----------------------------------------------------------------------------
522 #----------------------------------------------------------------------------
523 def target_outdated(target,deps):
523 def target_outdated(target,deps):
524 """Determine whether a target is out of date.
524 """Determine whether a target is out of date.
525
525
526 target_outdated(target,deps) -> 1/0
526 target_outdated(target,deps) -> 1/0
527
527
528 deps: list of filenames which MUST exist.
528 deps: list of filenames which MUST exist.
529 target: single filename which may or may not exist.
529 target: single filename which may or may not exist.
530
530
531 If target doesn't exist or is older than any file listed in deps, return
531 If target doesn't exist or is older than any file listed in deps, return
532 true, otherwise return false.
532 true, otherwise return false.
533 """
533 """
534 try:
534 try:
535 target_time = os.path.getmtime(target)
535 target_time = os.path.getmtime(target)
536 except os.error:
536 except os.error:
537 return 1
537 return 1
538 for dep in deps:
538 for dep in deps:
539 dep_time = os.path.getmtime(dep)
539 dep_time = os.path.getmtime(dep)
540 if dep_time > target_time:
540 if dep_time > target_time:
541 #print "For target",target,"Dep failed:",dep # dbg
541 #print "For target",target,"Dep failed:",dep # dbg
542 #print "times (dep,tar):",dep_time,target_time # dbg
542 #print "times (dep,tar):",dep_time,target_time # dbg
543 return 1
543 return 1
544 return 0
544 return 0
545
545
546 #-----------------------------------------------------------------------------
546 #-----------------------------------------------------------------------------
547 def target_update(target,deps,cmd):
547 def target_update(target,deps,cmd):
548 """Update a target with a given command given a list of dependencies.
548 """Update a target with a given command given a list of dependencies.
549
549
550 target_update(target,deps,cmd) -> runs cmd if target is outdated.
550 target_update(target,deps,cmd) -> runs cmd if target is outdated.
551
551
552 This is just a wrapper around target_outdated() which calls the given
552 This is just a wrapper around target_outdated() which calls the given
553 command if target is outdated."""
553 command if target is outdated."""
554
554
555 if target_outdated(target,deps):
555 if target_outdated(target,deps):
556 xsys(cmd)
556 xsys(cmd)
557
557
558 #----------------------------------------------------------------------------
558 #----------------------------------------------------------------------------
559 def unquote_ends(istr):
559 def unquote_ends(istr):
560 """Remove a single pair of quotes from the endpoints of a string."""
560 """Remove a single pair of quotes from the endpoints of a string."""
561
561
562 if not istr:
562 if not istr:
563 return istr
563 return istr
564 if (istr[0]=="'" and istr[-1]=="'") or \
564 if (istr[0]=="'" and istr[-1]=="'") or \
565 (istr[0]=='"' and istr[-1]=='"'):
565 (istr[0]=='"' and istr[-1]=='"'):
566 return istr[1:-1]
566 return istr[1:-1]
567 else:
567 else:
568 return istr
568 return istr
569
569
570 #----------------------------------------------------------------------------
570 #----------------------------------------------------------------------------
571 def process_cmdline(argv,names=[],defaults={},usage=''):
571 def process_cmdline(argv,names=[],defaults={},usage=''):
572 """ Process command-line options and arguments.
572 """ Process command-line options and arguments.
573
573
574 Arguments:
574 Arguments:
575
575
576 - argv: list of arguments, typically sys.argv.
576 - argv: list of arguments, typically sys.argv.
577
577
578 - names: list of option names. See DPyGetOpt docs for details on options
578 - names: list of option names. See DPyGetOpt docs for details on options
579 syntax.
579 syntax.
580
580
581 - defaults: dict of default values.
581 - defaults: dict of default values.
582
582
583 - usage: optional usage notice to print if a wrong argument is passed.
583 - usage: optional usage notice to print if a wrong argument is passed.
584
584
585 Return a dict of options and a list of free arguments."""
585 Return a dict of options and a list of free arguments."""
586
586
587 getopt = DPyGetOpt.DPyGetOpt()
587 getopt = DPyGetOpt.DPyGetOpt()
588 getopt.setIgnoreCase(0)
588 getopt.setIgnoreCase(0)
589 getopt.parseConfiguration(names)
589 getopt.parseConfiguration(names)
590
590
591 try:
591 try:
592 getopt.processArguments(argv)
592 getopt.processArguments(argv)
593 except:
593 except:
594 print usage
594 print usage
595 warn(`sys.exc_value`,level=4)
595 warn(`sys.exc_value`,level=4)
596
596
597 defaults.update(getopt.optionValues)
597 defaults.update(getopt.optionValues)
598 args = getopt.freeValues
598 args = getopt.freeValues
599
599
600 return defaults,args
600 return defaults,args
601
601
602 #----------------------------------------------------------------------------
602 #----------------------------------------------------------------------------
603 def optstr2types(ostr):
603 def optstr2types(ostr):
604 """Convert a string of option names to a dict of type mappings.
604 """Convert a string of option names to a dict of type mappings.
605
605
606 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
606 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
607
607
608 This is used to get the types of all the options in a string formatted
608 This is used to get the types of all the options in a string formatted
609 with the conventions of DPyGetOpt. The 'type' None is used for options
609 with the conventions of DPyGetOpt. The 'type' None is used for options
610 which are strings (they need no further conversion). This function's main
610 which are strings (they need no further conversion). This function's main
611 use is to get a typemap for use with read_dict().
611 use is to get a typemap for use with read_dict().
612 """
612 """
613
613
614 typeconv = {None:'',int:'',float:''}
614 typeconv = {None:'',int:'',float:''}
615 typemap = {'s':None,'i':int,'f':float}
615 typemap = {'s':None,'i':int,'f':float}
616 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
616 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
617
617
618 for w in ostr.split():
618 for w in ostr.split():
619 oname,alias,otype = opt_re.match(w).groups()
619 oname,alias,otype = opt_re.match(w).groups()
620 if otype == '' or alias == '!': # simple switches are integers too
620 if otype == '' or alias == '!': # simple switches are integers too
621 otype = 'i'
621 otype = 'i'
622 typeconv[typemap[otype]] += oname + ' '
622 typeconv[typemap[otype]] += oname + ' '
623 return typeconv
623 return typeconv
624
624
625 #----------------------------------------------------------------------------
625 #----------------------------------------------------------------------------
626 def read_dict(filename,type_conv=None,**opt):
626 def read_dict(filename,type_conv=None,**opt):
627
627
628 """Read a dictionary of key=value pairs from an input file, optionally
628 """Read a dictionary of key=value pairs from an input file, optionally
629 performing conversions on the resulting values.
629 performing conversions on the resulting values.
630
630
631 read_dict(filename,type_conv,**opt) -> dict
631 read_dict(filename,type_conv,**opt) -> dict
632
632
633 Only one value per line is accepted, the format should be
633 Only one value per line is accepted, the format should be
634 # optional comments are ignored
634 # optional comments are ignored
635 key value\n
635 key value\n
636
636
637 Args:
637 Args:
638
638
639 - type_conv: A dictionary specifying which keys need to be converted to
639 - type_conv: A dictionary specifying which keys need to be converted to
640 which types. By default all keys are read as strings. This dictionary
640 which types. By default all keys are read as strings. This dictionary
641 should have as its keys valid conversion functions for strings
641 should have as its keys valid conversion functions for strings
642 (int,long,float,complex, or your own). The value for each key
642 (int,long,float,complex, or your own). The value for each key
643 (converter) should be a whitespace separated string containing the names
643 (converter) should be a whitespace separated string containing the names
644 of all the entries in the file to be converted using that function. For
644 of all the entries in the file to be converted using that function. For
645 keys to be left alone, use None as the conversion function (only needed
645 keys to be left alone, use None as the conversion function (only needed
646 with purge=1, see below).
646 with purge=1, see below).
647
647
648 - opt: dictionary with extra options as below (default in parens)
648 - opt: dictionary with extra options as below (default in parens)
649
649
650 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
650 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
651 of the dictionary to be returned. If purge is going to be used, the
651 of the dictionary to be returned. If purge is going to be used, the
652 set of keys to be left as strings also has to be explicitly specified
652 set of keys to be left as strings also has to be explicitly specified
653 using the (non-existent) conversion function None.
653 using the (non-existent) conversion function None.
654
654
655 fs(None): field separator. This is the key/value separator to be used
655 fs(None): field separator. This is the key/value separator to be used
656 when parsing the file. The None default means any whitespace [behavior
656 when parsing the file. The None default means any whitespace [behavior
657 of string.split()].
657 of string.split()].
658
658
659 strip(0): if 1, strip string values of leading/trailinig whitespace.
659 strip(0): if 1, strip string values of leading/trailinig whitespace.
660
660
661 warn(1): warning level if requested keys are not found in file.
661 warn(1): warning level if requested keys are not found in file.
662 - 0: silently ignore.
662 - 0: silently ignore.
663 - 1: inform but proceed.
663 - 1: inform but proceed.
664 - 2: raise KeyError exception.
664 - 2: raise KeyError exception.
665
665
666 no_empty(0): if 1, remove keys with whitespace strings as a value.
666 no_empty(0): if 1, remove keys with whitespace strings as a value.
667
667
668 unique([]): list of keys (or space separated string) which can't be
668 unique([]): list of keys (or space separated string) which can't be
669 repeated. If one such key is found in the file, each new instance
669 repeated. If one such key is found in the file, each new instance
670 overwrites the previous one. For keys not listed here, the behavior is
670 overwrites the previous one. For keys not listed here, the behavior is
671 to make a list of all appearances.
671 to make a list of all appearances.
672
672
673 Example:
673 Example:
674 If the input file test.ini has:
674 If the input file test.ini has:
675 i 3
675 i 3
676 x 4.5
676 x 4.5
677 y 5.5
677 y 5.5
678 s hi ho
678 s hi ho
679 Then:
679 Then:
680
680
681 >>> type_conv={int:'i',float:'x',None:'s'}
681 >>> type_conv={int:'i',float:'x',None:'s'}
682 >>> read_dict('test.ini')
682 >>> read_dict('test.ini')
683 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
683 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
684 >>> read_dict('test.ini',type_conv)
684 >>> read_dict('test.ini',type_conv)
685 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
685 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
686 >>> read_dict('test.ini',type_conv,purge=1)
686 >>> read_dict('test.ini',type_conv,purge=1)
687 {'i': 3, 's': 'hi ho', 'x': 4.5}
687 {'i': 3, 's': 'hi ho', 'x': 4.5}
688 """
688 """
689
689
690 # starting config
690 # starting config
691 opt.setdefault('purge',0)
691 opt.setdefault('purge',0)
692 opt.setdefault('fs',None) # field sep defaults to any whitespace
692 opt.setdefault('fs',None) # field sep defaults to any whitespace
693 opt.setdefault('strip',0)
693 opt.setdefault('strip',0)
694 opt.setdefault('warn',1)
694 opt.setdefault('warn',1)
695 opt.setdefault('no_empty',0)
695 opt.setdefault('no_empty',0)
696 opt.setdefault('unique','')
696 opt.setdefault('unique','')
697 if type(opt['unique']) in StringTypes:
697 if type(opt['unique']) in StringTypes:
698 unique_keys = qw(opt['unique'])
698 unique_keys = qw(opt['unique'])
699 elif type(opt['unique']) in (types.TupleType,types.ListType):
699 elif type(opt['unique']) in (types.TupleType,types.ListType):
700 unique_keys = opt['unique']
700 unique_keys = opt['unique']
701 else:
701 else:
702 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
702 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
703
703
704 dict = {}
704 dict = {}
705 # first read in table of values as strings
705 # first read in table of values as strings
706 file = open(filename,'r')
706 file = open(filename,'r')
707 for line in file.readlines():
707 for line in file.readlines():
708 line = line.strip()
708 line = line.strip()
709 if len(line) and line[0]=='#': continue
709 if len(line) and line[0]=='#': continue
710 if len(line)>0:
710 if len(line)>0:
711 lsplit = line.split(opt['fs'],1)
711 lsplit = line.split(opt['fs'],1)
712 try:
712 try:
713 key,val = lsplit
713 key,val = lsplit
714 except ValueError:
714 except ValueError:
715 key,val = lsplit[0],''
715 key,val = lsplit[0],''
716 key = key.strip()
716 key = key.strip()
717 if opt['strip']: val = val.strip()
717 if opt['strip']: val = val.strip()
718 if val == "''" or val == '""': val = ''
718 if val == "''" or val == '""': val = ''
719 if opt['no_empty'] and (val=='' or val.isspace()):
719 if opt['no_empty'] and (val=='' or val.isspace()):
720 continue
720 continue
721 # if a key is found more than once in the file, build a list
721 # if a key is found more than once in the file, build a list
722 # unless it's in the 'unique' list. In that case, last found in file
722 # unless it's in the 'unique' list. In that case, last found in file
723 # takes precedence. User beware.
723 # takes precedence. User beware.
724 try:
724 try:
725 if dict[key] and key in unique_keys:
725 if dict[key] and key in unique_keys:
726 dict[key] = val
726 dict[key] = val
727 elif type(dict[key]) is types.ListType:
727 elif type(dict[key]) is types.ListType:
728 dict[key].append(val)
728 dict[key].append(val)
729 else:
729 else:
730 dict[key] = [dict[key],val]
730 dict[key] = [dict[key],val]
731 except KeyError:
731 except KeyError:
732 dict[key] = val
732 dict[key] = val
733 # purge if requested
733 # purge if requested
734 if opt['purge']:
734 if opt['purge']:
735 accepted_keys = qwflat(type_conv.values())
735 accepted_keys = qwflat(type_conv.values())
736 for key in dict.keys():
736 for key in dict.keys():
737 if key in accepted_keys: continue
737 if key in accepted_keys: continue
738 del(dict[key])
738 del(dict[key])
739 # now convert if requested
739 # now convert if requested
740 if type_conv==None: return dict
740 if type_conv==None: return dict
741 conversions = type_conv.keys()
741 conversions = type_conv.keys()
742 try: conversions.remove(None)
742 try: conversions.remove(None)
743 except: pass
743 except: pass
744 for convert in conversions:
744 for convert in conversions:
745 for val in qw(type_conv[convert]):
745 for val in qw(type_conv[convert]):
746 try:
746 try:
747 dict[val] = convert(dict[val])
747 dict[val] = convert(dict[val])
748 except KeyError,e:
748 except KeyError,e:
749 if opt['warn'] == 0:
749 if opt['warn'] == 0:
750 pass
750 pass
751 elif opt['warn'] == 1:
751 elif opt['warn'] == 1:
752 print >>sys.stderr, 'Warning: key',val,\
752 print >>sys.stderr, 'Warning: key',val,\
753 'not found in file',filename
753 'not found in file',filename
754 elif opt['warn'] == 2:
754 elif opt['warn'] == 2:
755 raise KeyError,e
755 raise KeyError,e
756 else:
756 else:
757 raise ValueError,'Warning level must be 0,1 or 2'
757 raise ValueError,'Warning level must be 0,1 or 2'
758
758
759 return dict
759 return dict
760
760
761 #----------------------------------------------------------------------------
761 #----------------------------------------------------------------------------
762 def flag_calls(func):
762 def flag_calls(func):
763 """Wrap a function to detect and flag when it gets called.
763 """Wrap a function to detect and flag when it gets called.
764
764
765 This is a decorator which takes a function and wraps it in a function with
765 This is a decorator which takes a function and wraps it in a function with
766 a 'called' attribute. wrapper.called is initialized to False.
766 a 'called' attribute. wrapper.called is initialized to False.
767
767
768 The wrapper.called attribute is set to False right before each call to the
768 The wrapper.called attribute is set to False right before each call to the
769 wrapped function, so if the call fails it remains False. After the call
769 wrapped function, so if the call fails it remains False. After the call
770 completes, wrapper.called is set to True and the output is returned.
770 completes, wrapper.called is set to True and the output is returned.
771
771
772 Testing for truth in wrapper.called allows you to determine if a call to
772 Testing for truth in wrapper.called allows you to determine if a call to
773 func() was attempted and succeeded."""
773 func() was attempted and succeeded."""
774
774
775 def wrapper(*args,**kw):
775 def wrapper(*args,**kw):
776 wrapper.called = False
776 wrapper.called = False
777 out = func(*args,**kw)
777 out = func(*args,**kw)
778 wrapper.called = True
778 wrapper.called = True
779 return out
779 return out
780
780
781 wrapper.called = False
781 wrapper.called = False
782 wrapper.__doc__ = func.__doc__
782 wrapper.__doc__ = func.__doc__
783 return wrapper
783 return wrapper
784
784
785 #----------------------------------------------------------------------------
785 #----------------------------------------------------------------------------
786 class HomeDirError(Error):
786 class HomeDirError(Error):
787 pass
787 pass
788
788
789 def get_home_dir():
789 def get_home_dir():
790 """Return the closest possible equivalent to a 'home' directory.
790 """Return the closest possible equivalent to a 'home' directory.
791
791
792 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
792 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
793
793
794 Currently only Posix and NT are implemented, a HomeDirError exception is
794 Currently only Posix and NT are implemented, a HomeDirError exception is
795 raised for all other OSes. """
795 raised for all other OSes. """
796
796
797 isdir = os.path.isdir
797 isdir = os.path.isdir
798 env = os.environ
798 env = os.environ
799 try:
799 try:
800 homedir = env['HOME']
800 homedir = env['HOME']
801 if not isdir(homedir):
801 if not isdir(homedir):
802 # in case a user stuck some string which does NOT resolve to a
802 # in case a user stuck some string which does NOT resolve to a
803 # valid path, it's as good as if we hadn't foud it
803 # valid path, it's as good as if we hadn't foud it
804 raise KeyError
804 raise KeyError
805 return homedir
805 return homedir
806 except KeyError:
806 except KeyError:
807 if os.name == 'posix':
807 if os.name == 'posix':
808 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
808 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
809 elif os.name == 'nt':
809 elif os.name == 'nt':
810 # For some strange reason, win9x returns 'nt' for os.name.
810 # For some strange reason, win9x returns 'nt' for os.name.
811 try:
811 try:
812 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
812 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
813 if not isdir(homedir):
813 if not isdir(homedir):
814 homedir = os.path.join(env['USERPROFILE'])
814 homedir = os.path.join(env['USERPROFILE'])
815 if not isdir(homedir):
815 if not isdir(homedir):
816 raise HomeDirError
816 raise HomeDirError
817 return homedir
817 return homedir
818 except:
818 except:
819 try:
819 try:
820 # Use the registry to get the 'My Documents' folder.
820 # Use the registry to get the 'My Documents' folder.
821 import _winreg as wreg
821 import _winreg as wreg
822 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
822 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
823 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
823 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
824 homedir = wreg.QueryValueEx(key,'Personal')[0]
824 homedir = wreg.QueryValueEx(key,'Personal')[0]
825 key.Close()
825 key.Close()
826 if not isdir(homedir):
826 if not isdir(homedir):
827 e = ('Invalid "Personal" folder registry key '
827 e = ('Invalid "Personal" folder registry key '
828 'typically "My Documents".\n'
828 'typically "My Documents".\n'
829 'Value: %s\n'
829 'Value: %s\n'
830 'This is not a valid directory on your system.' %
830 'This is not a valid directory on your system.' %
831 homedir)
831 homedir)
832 raise HomeDirError(e)
832 raise HomeDirError(e)
833 return homedir
833 return homedir
834 except HomeDirError:
834 except HomeDirError:
835 raise
835 raise
836 except:
836 except:
837 return 'C:\\'
837 return 'C:\\'
838 elif os.name == 'dos':
838 elif os.name == 'dos':
839 # Desperate, may do absurd things in classic MacOS. May work under DOS.
839 # Desperate, may do absurd things in classic MacOS. May work under DOS.
840 return 'C:\\'
840 return 'C:\\'
841 else:
841 else:
842 raise HomeDirError,'support for your operating system not implemented.'
842 raise HomeDirError,'support for your operating system not implemented.'
843
843
844 #****************************************************************************
844 #****************************************************************************
845 # strings and text
845 # strings and text
846
846
847 class LSString(str):
847 class LSString(str):
848 """String derivative with a special access attributes.
848 """String derivative with a special access attributes.
849
849
850 These are normal strings, but with the special attributes:
850 These are normal strings, but with the special attributes:
851
851
852 .l (or .list) : value as list (split on newlines).
852 .l (or .list) : value as list (split on newlines).
853 .n (or .nlstr): original value (the string itself).
853 .n (or .nlstr): original value (the string itself).
854 .s (or .spstr): value as whitespace-separated string.
854 .s (or .spstr): value as whitespace-separated string.
855
855
856 Any values which require transformations are computed only once and
856 Any values which require transformations are computed only once and
857 cached.
857 cached.
858
858
859 Such strings are very useful to efficiently interact with the shell, which
859 Such strings are very useful to efficiently interact with the shell, which
860 typically only understands whitespace-separated options for commands."""
860 typically only understands whitespace-separated options for commands."""
861
861
862 def get_list(self):
862 def get_list(self):
863 try:
863 try:
864 return self.__list
864 return self.__list
865 except AttributeError:
865 except AttributeError:
866 self.__list = self.split('\n')
866 self.__list = self.split('\n')
867 return self.__list
867 return self.__list
868
868
869 l = list = property(get_list)
869 l = list = property(get_list)
870
870
871 def get_spstr(self):
871 def get_spstr(self):
872 try:
872 try:
873 return self.__spstr
873 return self.__spstr
874 except AttributeError:
874 except AttributeError:
875 self.__spstr = self.replace('\n',' ')
875 self.__spstr = self.replace('\n',' ')
876 return self.__spstr
876 return self.__spstr
877
877
878 s = spstr = property(get_spstr)
878 s = spstr = property(get_spstr)
879
879
880 def get_nlstr(self):
880 def get_nlstr(self):
881 return self
881 return self
882
882
883 n = nlstr = property(get_nlstr)
883 n = nlstr = property(get_nlstr)
884
884
885 def get_paths(self):
885 def get_paths(self):
886 try:
886 try:
887 return self.__paths
887 return self.__paths
888 except AttributeError:
888 except AttributeError:
889 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
889 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
890 return self.__paths
890 return self.__paths
891
891
892 p = paths = property(get_paths)
892 p = paths = property(get_paths)
893
893
894
894
895 #----------------------------------------------------------------------------
895 #----------------------------------------------------------------------------
896 class SList(list):
896 class SList(list):
897 """List derivative with a special access attributes.
897 """List derivative with a special access attributes.
898
898
899 These are normal lists, but with the special attributes:
899 These are normal lists, but with the special attributes:
900
900
901 .l (or .list) : value as list (the list itself).
901 .l (or .list) : value as list (the list itself).
902 .n (or .nlstr): value as a string, joined on newlines.
902 .n (or .nlstr): value as a string, joined on newlines.
903 .s (or .spstr): value as a string, joined on spaces.
903 .s (or .spstr): value as a string, joined on spaces.
904
904
905 Any values which require transformations are computed only once and
905 Any values which require transformations are computed only once and
906 cached."""
906 cached."""
907
907
908 def get_list(self):
908 def get_list(self):
909 return self
909 return self
910
910
911 l = list = property(get_list)
911 l = list = property(get_list)
912
912
913 def get_spstr(self):
913 def get_spstr(self):
914 try:
914 try:
915 return self.__spstr
915 return self.__spstr
916 except AttributeError:
916 except AttributeError:
917 self.__spstr = ' '.join(self)
917 self.__spstr = ' '.join(self)
918 return self.__spstr
918 return self.__spstr
919
919
920 s = spstr = property(get_spstr)
920 s = spstr = property(get_spstr)
921
921
922 def get_nlstr(self):
922 def get_nlstr(self):
923 try:
923 try:
924 return self.__nlstr
924 return self.__nlstr
925 except AttributeError:
925 except AttributeError:
926 self.__nlstr = '\n'.join(self)
926 self.__nlstr = '\n'.join(self)
927 return self.__nlstr
927 return self.__nlstr
928
928
929 n = nlstr = property(get_nlstr)
929 n = nlstr = property(get_nlstr)
930
930
931 def get_paths(self):
931 def get_paths(self):
932 try:
932 try:
933 return self.__paths
933 return self.__paths
934 except AttributeError:
934 except AttributeError:
935 self.__paths = [path(p) for p in self if os.path.exists(p)]
935 self.__paths = [path(p) for p in self if os.path.exists(p)]
936 return self.__paths
936 return self.__paths
937
937
938 p = paths = property(get_paths)
938 p = paths = property(get_paths)
939
939
940 #----------------------------------------------------------------------------
940 #----------------------------------------------------------------------------
941 def esc_quotes(strng):
941 def esc_quotes(strng):
942 """Return the input string with single and double quotes escaped out"""
942 """Return the input string with single and double quotes escaped out"""
943
943
944 return strng.replace('"','\\"').replace("'","\\'")
944 return strng.replace('"','\\"').replace("'","\\'")
945
945
946 #----------------------------------------------------------------------------
946 #----------------------------------------------------------------------------
947 def make_quoted_expr(s):
947 def make_quoted_expr(s):
948 """Return string s in appropriate quotes, using raw string if possible.
948 """Return string s in appropriate quotes, using raw string if possible.
949
949
950 Effectively this turns string: cd \ao\ao\
950 Effectively this turns string: cd \ao\ao\
951 to: r"cd \ao\ao\_"[:-1]
951 to: r"cd \ao\ao\_"[:-1]
952
952
953 Note the use of raw string and padding at the end to allow trailing backslash.
953 Note the use of raw string and padding at the end to allow trailing backslash.
954
954
955 """
955 """
956
956
957 tail = ''
957 tail = ''
958 tailpadding = ''
958 tailpadding = ''
959 raw = ''
959 raw = ''
960 if "\\" in s:
960 if "\\" in s:
961 raw = 'r'
961 raw = 'r'
962 if s.endswith('\\'):
962 if s.endswith('\\'):
963 tail = '[:-1]'
963 tail = '[:-1]'
964 tailpadding = '_'
964 tailpadding = '_'
965 if '"' not in s:
965 if '"' not in s:
966 quote = '"'
966 quote = '"'
967 elif "'" not in s:
967 elif "'" not in s:
968 quote = "'"
968 quote = "'"
969 elif '"""' not in s and not s.endswith('"'):
969 elif '"""' not in s and not s.endswith('"'):
970 quote = '"""'
970 quote = '"""'
971 elif "'''" not in s and not s.endswith("'"):
971 elif "'''" not in s and not s.endswith("'"):
972 quote = "'''"
972 quote = "'''"
973 else:
973 else:
974 # give up, backslash-escaped string will do
974 # give up, backslash-escaped string will do
975 return '"%s"' % esc_quotes(s)
975 return '"%s"' % esc_quotes(s)
976 res = itpl("$raw$quote$s$tailpadding$quote$tail")
976 res = itpl("$raw$quote$s$tailpadding$quote$tail")
977 return res
977 return res
978
978
979
979
980 #----------------------------------------------------------------------------
980 #----------------------------------------------------------------------------
981 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
981 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
982 """Take multiple lines of input.
982 """Take multiple lines of input.
983
983
984 A list with each line of input as a separate element is returned when a
984 A list with each line of input as a separate element is returned when a
985 termination string is entered (defaults to a single '.'). Input can also
985 termination string is entered (defaults to a single '.'). Input can also
986 terminate via EOF (^D in Unix, ^Z-RET in Windows).
986 terminate via EOF (^D in Unix, ^Z-RET in Windows).
987
987
988 Lines of input which end in \\ are joined into single entries (and a
988 Lines of input which end in \\ are joined into single entries (and a
989 secondary continuation prompt is issued as long as the user terminates
989 secondary continuation prompt is issued as long as the user terminates
990 lines with \\). This allows entering very long strings which are still
990 lines with \\). This allows entering very long strings which are still
991 meant to be treated as single entities.
991 meant to be treated as single entities.
992 """
992 """
993
993
994 try:
994 try:
995 if header:
995 if header:
996 header += '\n'
996 header += '\n'
997 lines = [raw_input(header + ps1)]
997 lines = [raw_input(header + ps1)]
998 except EOFError:
998 except EOFError:
999 return []
999 return []
1000 terminate = [terminate_str]
1000 terminate = [terminate_str]
1001 try:
1001 try:
1002 while lines[-1:] != terminate:
1002 while lines[-1:] != terminate:
1003 new_line = raw_input(ps1)
1003 new_line = raw_input(ps1)
1004 while new_line.endswith('\\'):
1004 while new_line.endswith('\\'):
1005 new_line = new_line[:-1] + raw_input(ps2)
1005 new_line = new_line[:-1] + raw_input(ps2)
1006 lines.append(new_line)
1006 lines.append(new_line)
1007
1007
1008 return lines[:-1] # don't return the termination command
1008 return lines[:-1] # don't return the termination command
1009 except EOFError:
1009 except EOFError:
1010 print
1010 print
1011 return lines
1011 return lines
1012
1012
1013 #----------------------------------------------------------------------------
1013 #----------------------------------------------------------------------------
1014 def raw_input_ext(prompt='', ps2='... '):
1014 def raw_input_ext(prompt='', ps2='... '):
1015 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1015 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1016
1016
1017 line = raw_input(prompt)
1017 line = raw_input(prompt)
1018 while line.endswith('\\'):
1018 while line.endswith('\\'):
1019 line = line[:-1] + raw_input(ps2)
1019 line = line[:-1] + raw_input(ps2)
1020 return line
1020 return line
1021
1021
1022 #----------------------------------------------------------------------------
1022 #----------------------------------------------------------------------------
1023 def ask_yes_no(prompt,default=None):
1023 def ask_yes_no(prompt,default=None):
1024 """Asks a question and returns an integer 1/0 (y/n) answer.
1024 """Asks a question and returns an integer 1/0 (y/n) answer.
1025
1025
1026 If default is given (one of 'y','n'), it is used if the user input is
1026 If default is given (one of 'y','n'), it is used if the user input is
1027 empty. Otherwise the question is repeated until an answer is given.
1027 empty. Otherwise the question is repeated until an answer is given.
1028
1028
1029 An EOF is treated as the default answer. If there is no default, an
1029 An EOF is treated as the default answer. If there is no default, an
1030 exception is raised to prevent infinite loops.
1030 exception is raised to prevent infinite loops.
1031
1031
1032 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1032 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1033
1033
1034 answers = {'y':True,'n':False,'yes':True,'no':False}
1034 answers = {'y':True,'n':False,'yes':True,'no':False}
1035 ans = None
1035 ans = None
1036 while ans not in answers.keys():
1036 while ans not in answers.keys():
1037 try:
1037 try:
1038 ans = raw_input(prompt+' ').lower()
1038 ans = raw_input(prompt+' ').lower()
1039 if not ans: # response was an empty string
1039 if not ans: # response was an empty string
1040 ans = default
1040 ans = default
1041 except KeyboardInterrupt:
1041 except KeyboardInterrupt:
1042 pass
1042 pass
1043 except EOFError:
1043 except EOFError:
1044 if default in answers.keys():
1044 if default in answers.keys():
1045 ans = default
1045 ans = default
1046 print
1046 print
1047 else:
1047 else:
1048 raise
1048 raise
1049
1049
1050 return answers[ans]
1050 return answers[ans]
1051
1051
1052 #----------------------------------------------------------------------------
1052 #----------------------------------------------------------------------------
1053 def marquee(txt='',width=78,mark='*'):
1053 def marquee(txt='',width=78,mark='*'):
1054 """Return the input string centered in a 'marquee'."""
1054 """Return the input string centered in a 'marquee'."""
1055 if not txt:
1055 if not txt:
1056 return (mark*width)[:width]
1056 return (mark*width)[:width]
1057 nmark = (width-len(txt)-2)/len(mark)/2
1057 nmark = (width-len(txt)-2)/len(mark)/2
1058 if nmark < 0: nmark =0
1058 if nmark < 0: nmark =0
1059 marks = mark*nmark
1059 marks = mark*nmark
1060 return '%s %s %s' % (marks,txt,marks)
1060 return '%s %s %s' % (marks,txt,marks)
1061
1061
1062 #----------------------------------------------------------------------------
1062 #----------------------------------------------------------------------------
1063 class EvalDict:
1063 class EvalDict:
1064 """
1064 """
1065 Emulate a dict which evaluates its contents in the caller's frame.
1065 Emulate a dict which evaluates its contents in the caller's frame.
1066
1066
1067 Usage:
1067 Usage:
1068 >>>number = 19
1068 >>>number = 19
1069 >>>text = "python"
1069 >>>text = "python"
1070 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1070 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1071 """
1071 """
1072
1072
1073 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1073 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1074 # modified (shorter) version of:
1074 # modified (shorter) version of:
1075 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1075 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1076 # Skip Montanaro (skip@pobox.com).
1076 # Skip Montanaro (skip@pobox.com).
1077
1077
1078 def __getitem__(self, name):
1078 def __getitem__(self, name):
1079 frame = sys._getframe(1)
1079 frame = sys._getframe(1)
1080 return eval(name, frame.f_globals, frame.f_locals)
1080 return eval(name, frame.f_globals, frame.f_locals)
1081
1081
1082 EvalString = EvalDict # for backwards compatibility
1082 EvalString = EvalDict # for backwards compatibility
1083 #----------------------------------------------------------------------------
1083 #----------------------------------------------------------------------------
1084 def qw(words,flat=0,sep=None,maxsplit=-1):
1084 def qw(words,flat=0,sep=None,maxsplit=-1):
1085 """Similar to Perl's qw() operator, but with some more options.
1085 """Similar to Perl's qw() operator, but with some more options.
1086
1086
1087 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1087 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1088
1088
1089 words can also be a list itself, and with flat=1, the output will be
1089 words can also be a list itself, and with flat=1, the output will be
1090 recursively flattened. Examples:
1090 recursively flattened. Examples:
1091
1091
1092 >>> qw('1 2')
1092 >>> qw('1 2')
1093 ['1', '2']
1093 ['1', '2']
1094 >>> qw(['a b','1 2',['m n','p q']])
1094 >>> qw(['a b','1 2',['m n','p q']])
1095 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1095 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1096 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1096 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1097 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1097 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1098
1098
1099 if type(words) in StringTypes:
1099 if type(words) in StringTypes:
1100 return [word.strip() for word in words.split(sep,maxsplit)
1100 return [word.strip() for word in words.split(sep,maxsplit)
1101 if word and not word.isspace() ]
1101 if word and not word.isspace() ]
1102 if flat:
1102 if flat:
1103 return flatten(map(qw,words,[1]*len(words)))
1103 return flatten(map(qw,words,[1]*len(words)))
1104 return map(qw,words)
1104 return map(qw,words)
1105
1105
1106 #----------------------------------------------------------------------------
1106 #----------------------------------------------------------------------------
1107 def qwflat(words,sep=None,maxsplit=-1):
1107 def qwflat(words,sep=None,maxsplit=-1):
1108 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1108 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1109 return qw(words,1,sep,maxsplit)
1109 return qw(words,1,sep,maxsplit)
1110
1110
1111 #----------------------------------------------------------------------------
1111 #----------------------------------------------------------------------------
1112 def qw_lol(indata):
1112 def qw_lol(indata):
1113 """qw_lol('a b') -> [['a','b']],
1113 """qw_lol('a b') -> [['a','b']],
1114 otherwise it's just a call to qw().
1114 otherwise it's just a call to qw().
1115
1115
1116 We need this to make sure the modules_some keys *always* end up as a
1116 We need this to make sure the modules_some keys *always* end up as a
1117 list of lists."""
1117 list of lists."""
1118
1118
1119 if type(indata) in StringTypes:
1119 if type(indata) in StringTypes:
1120 return [qw(indata)]
1120 return [qw(indata)]
1121 else:
1121 else:
1122 return qw(indata)
1122 return qw(indata)
1123
1123
1124 #-----------------------------------------------------------------------------
1124 #-----------------------------------------------------------------------------
1125 def list_strings(arg):
1125 def list_strings(arg):
1126 """Always return a list of strings, given a string or list of strings
1126 """Always return a list of strings, given a string or list of strings
1127 as input."""
1127 as input."""
1128
1128
1129 if type(arg) in StringTypes: return [arg]
1129 if type(arg) in StringTypes: return [arg]
1130 else: return arg
1130 else: return arg
1131
1131
1132 #----------------------------------------------------------------------------
1132 #----------------------------------------------------------------------------
1133 def grep(pat,list,case=1):
1133 def grep(pat,list,case=1):
1134 """Simple minded grep-like function.
1134 """Simple minded grep-like function.
1135 grep(pat,list) returns occurrences of pat in list, None on failure.
1135 grep(pat,list) returns occurrences of pat in list, None on failure.
1136
1136
1137 It only does simple string matching, with no support for regexps. Use the
1137 It only does simple string matching, with no support for regexps. Use the
1138 option case=0 for case-insensitive matching."""
1138 option case=0 for case-insensitive matching."""
1139
1139
1140 # This is pretty crude. At least it should implement copying only references
1140 # This is pretty crude. At least it should implement copying only references
1141 # to the original data in case it's big. Now it copies the data for output.
1141 # to the original data in case it's big. Now it copies the data for output.
1142 out=[]
1142 out=[]
1143 if case:
1143 if case:
1144 for term in list:
1144 for term in list:
1145 if term.find(pat)>-1: out.append(term)
1145 if term.find(pat)>-1: out.append(term)
1146 else:
1146 else:
1147 lpat=pat.lower()
1147 lpat=pat.lower()
1148 for term in list:
1148 for term in list:
1149 if term.lower().find(lpat)>-1: out.append(term)
1149 if term.lower().find(lpat)>-1: out.append(term)
1150
1150
1151 if len(out): return out
1151 if len(out): return out
1152 else: return None
1152 else: return None
1153
1153
1154 #----------------------------------------------------------------------------
1154 #----------------------------------------------------------------------------
1155 def dgrep(pat,*opts):
1155 def dgrep(pat,*opts):
1156 """Return grep() on dir()+dir(__builtins__).
1156 """Return grep() on dir()+dir(__builtins__).
1157
1157
1158 A very common use of grep() when working interactively."""
1158 A very common use of grep() when working interactively."""
1159
1159
1160 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1160 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1161
1161
1162 #----------------------------------------------------------------------------
1162 #----------------------------------------------------------------------------
1163 def idgrep(pat):
1163 def idgrep(pat):
1164 """Case-insensitive dgrep()"""
1164 """Case-insensitive dgrep()"""
1165
1165
1166 return dgrep(pat,0)
1166 return dgrep(pat,0)
1167
1167
1168 #----------------------------------------------------------------------------
1168 #----------------------------------------------------------------------------
1169 def igrep(pat,list):
1169 def igrep(pat,list):
1170 """Synonym for case-insensitive grep."""
1170 """Synonym for case-insensitive grep."""
1171
1171
1172 return grep(pat,list,case=0)
1172 return grep(pat,list,case=0)
1173
1173
1174 #----------------------------------------------------------------------------
1174 #----------------------------------------------------------------------------
1175 def indent(str,nspaces=4,ntabs=0):
1175 def indent(str,nspaces=4,ntabs=0):
1176 """Indent a string a given number of spaces or tabstops.
1176 """Indent a string a given number of spaces or tabstops.
1177
1177
1178 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1178 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1179 """
1179 """
1180 if str is None:
1180 if str is None:
1181 return
1181 return
1182 ind = '\t'*ntabs+' '*nspaces
1182 ind = '\t'*ntabs+' '*nspaces
1183 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1183 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1184 if outstr.endswith(os.linesep+ind):
1184 if outstr.endswith(os.linesep+ind):
1185 return outstr[:-len(ind)]
1185 return outstr[:-len(ind)]
1186 else:
1186 else:
1187 return outstr
1187 return outstr
1188
1188
1189 #-----------------------------------------------------------------------------
1189 #-----------------------------------------------------------------------------
1190 def native_line_ends(filename,backup=1):
1190 def native_line_ends(filename,backup=1):
1191 """Convert (in-place) a file to line-ends native to the current OS.
1191 """Convert (in-place) a file to line-ends native to the current OS.
1192
1192
1193 If the optional backup argument is given as false, no backup of the
1193 If the optional backup argument is given as false, no backup of the
1194 original file is left. """
1194 original file is left. """
1195
1195
1196 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1196 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1197
1197
1198 bak_filename = filename + backup_suffixes[os.name]
1198 bak_filename = filename + backup_suffixes[os.name]
1199
1199
1200 original = open(filename).read()
1200 original = open(filename).read()
1201 shutil.copy2(filename,bak_filename)
1201 shutil.copy2(filename,bak_filename)
1202 try:
1202 try:
1203 new = open(filename,'wb')
1203 new = open(filename,'wb')
1204 new.write(os.linesep.join(original.splitlines()))
1204 new.write(os.linesep.join(original.splitlines()))
1205 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1205 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1206 new.close()
1206 new.close()
1207 except:
1207 except:
1208 os.rename(bak_filename,filename)
1208 os.rename(bak_filename,filename)
1209 if not backup:
1209 if not backup:
1210 try:
1210 try:
1211 os.remove(bak_filename)
1211 os.remove(bak_filename)
1212 except:
1212 except:
1213 pass
1213 pass
1214
1214
1215 #----------------------------------------------------------------------------
1215 #----------------------------------------------------------------------------
1216 def get_pager_cmd(pager_cmd = None):
1216 def get_pager_cmd(pager_cmd = None):
1217 """Return a pager command.
1217 """Return a pager command.
1218
1218
1219 Makes some attempts at finding an OS-correct one."""
1219 Makes some attempts at finding an OS-correct one."""
1220
1220
1221 if os.name == 'posix':
1221 if os.name == 'posix':
1222 default_pager_cmd = 'less -r' # -r for color control sequences
1222 default_pager_cmd = 'less -r' # -r for color control sequences
1223 elif os.name in ['nt','dos']:
1223 elif os.name in ['nt','dos']:
1224 default_pager_cmd = 'type'
1224 default_pager_cmd = 'type'
1225
1225
1226 if pager_cmd is None:
1226 if pager_cmd is None:
1227 try:
1227 try:
1228 pager_cmd = os.environ['PAGER']
1228 pager_cmd = os.environ['PAGER']
1229 except:
1229 except:
1230 pager_cmd = default_pager_cmd
1230 pager_cmd = default_pager_cmd
1231 return pager_cmd
1231 return pager_cmd
1232
1232
1233 #-----------------------------------------------------------------------------
1233 #-----------------------------------------------------------------------------
1234 def get_pager_start(pager,start):
1234 def get_pager_start(pager,start):
1235 """Return the string for paging files with an offset.
1235 """Return the string for paging files with an offset.
1236
1236
1237 This is the '+N' argument which less and more (under Unix) accept.
1237 This is the '+N' argument which less and more (under Unix) accept.
1238 """
1238 """
1239
1239
1240 if pager in ['less','more']:
1240 if pager in ['less','more']:
1241 if start:
1241 if start:
1242 start_string = '+' + str(start)
1242 start_string = '+' + str(start)
1243 else:
1243 else:
1244 start_string = ''
1244 start_string = ''
1245 else:
1245 else:
1246 start_string = ''
1246 start_string = ''
1247 return start_string
1247 return start_string
1248
1248
1249 #----------------------------------------------------------------------------
1249 #----------------------------------------------------------------------------
1250 if os.name == "nt":
1250 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1251 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1251 import msvcrt
1252 import msvcrt
1252 def page_more():
1253 def page_more():
1253 """ Smart pausing between pages
1254 """ Smart pausing between pages
1254
1255
1255 @return: True if need print more lines, False if quit
1256 @return: True if need print more lines, False if quit
1256 """
1257 """
1257 Term.cout.write('---Return to continue, q to quit--- ')
1258 Term.cout.write('---Return to continue, q to quit--- ')
1258 ans = msvcrt.getch()
1259 ans = msvcrt.getch()
1259 if ans in ("q", "Q"):
1260 if ans in ("q", "Q"):
1260 result = False
1261 result = False
1261 else:
1262 else:
1262 result = True
1263 result = True
1263 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1264 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1264 return result
1265 return result
1265 else:
1266 else:
1266 def page_more():
1267 def page_more():
1267 ans = raw_input('---Return to continue, q to quit--- ')
1268 ans = raw_input('---Return to continue, q to quit--- ')
1268 if ans.lower().startswith('q'):
1269 if ans.lower().startswith('q'):
1269 return False
1270 return False
1270 else:
1271 else:
1271 return True
1272 return True
1272
1273
1273 esc_re = re.compile(r"(\x1b[^m]+m)")
1274 esc_re = re.compile(r"(\x1b[^m]+m)")
1274
1275
1275 def page_dumb(strng,start=0,screen_lines=25):
1276 def page_dumb(strng,start=0,screen_lines=25):
1276 """Very dumb 'pager' in Python, for when nothing else works.
1277 """Very dumb 'pager' in Python, for when nothing else works.
1277
1278
1278 Only moves forward, same interface as page(), except for pager_cmd and
1279 Only moves forward, same interface as page(), except for pager_cmd and
1279 mode."""
1280 mode."""
1280
1281
1281 out_ln = strng.splitlines()[start:]
1282 out_ln = strng.splitlines()[start:]
1282 screens = chop(out_ln,screen_lines-1)
1283 screens = chop(out_ln,screen_lines-1)
1283 if len(screens) == 1:
1284 if len(screens) == 1:
1284 print >>Term.cout, os.linesep.join(screens[0])
1285 print >>Term.cout, os.linesep.join(screens[0])
1285 else:
1286 else:
1286 last_escape = ""
1287 last_escape = ""
1287 for scr in screens[0:-1]:
1288 for scr in screens[0:-1]:
1288 hunk = os.linesep.join(scr)
1289 hunk = os.linesep.join(scr)
1289 print >>Term.cout, last_escape + hunk
1290 print >>Term.cout, last_escape + hunk
1290 if not page_more():
1291 if not page_more():
1291 return
1292 return
1292 esc_list = esc_re.findall(hunk)
1293 esc_list = esc_re.findall(hunk)
1293 if len(esc_list) > 0:
1294 if len(esc_list) > 0:
1294 last_escape = esc_list[-1]
1295 last_escape = esc_list[-1]
1295 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1296 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1296
1297
1297 #----------------------------------------------------------------------------
1298 #----------------------------------------------------------------------------
1298 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1299 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1299 """Print a string, piping through a pager after a certain length.
1300 """Print a string, piping through a pager after a certain length.
1300
1301
1301 The screen_lines parameter specifies the number of *usable* lines of your
1302 The screen_lines parameter specifies the number of *usable* lines of your
1302 terminal screen (total lines minus lines you need to reserve to show other
1303 terminal screen (total lines minus lines you need to reserve to show other
1303 information).
1304 information).
1304
1305
1305 If you set screen_lines to a number <=0, page() will try to auto-determine
1306 If you set screen_lines to a number <=0, page() will try to auto-determine
1306 your screen size and will only use up to (screen_size+screen_lines) for
1307 your screen size and will only use up to (screen_size+screen_lines) for
1307 printing, paging after that. That is, if you want auto-detection but need
1308 printing, paging after that. That is, if you want auto-detection but need
1308 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1309 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1309 auto-detection without any lines reserved simply use screen_lines = 0.
1310 auto-detection without any lines reserved simply use screen_lines = 0.
1310
1311
1311 If a string won't fit in the allowed lines, it is sent through the
1312 If a string won't fit in the allowed lines, it is sent through the
1312 specified pager command. If none given, look for PAGER in the environment,
1313 specified pager command. If none given, look for PAGER in the environment,
1313 and ultimately default to less.
1314 and ultimately default to less.
1314
1315
1315 If no system pager works, the string is sent through a 'dumb pager'
1316 If no system pager works, the string is sent through a 'dumb pager'
1316 written in python, very simplistic.
1317 written in python, very simplistic.
1317 """
1318 """
1318
1319
1319 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1320 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1320 TERM = os.environ.get('TERM','dumb')
1321 TERM = os.environ.get('TERM','dumb')
1321 if TERM in ['dumb','emacs'] and os.name != 'nt':
1322 if TERM in ['dumb','emacs'] and os.name != 'nt':
1322 print strng
1323 print strng
1323 return
1324 return
1324 # chop off the topmost part of the string we don't want to see
1325 # chop off the topmost part of the string we don't want to see
1325 str_lines = strng.split(os.linesep)[start:]
1326 str_lines = strng.split(os.linesep)[start:]
1326 str_toprint = os.linesep.join(str_lines)
1327 str_toprint = os.linesep.join(str_lines)
1327 num_newlines = len(str_lines)
1328 num_newlines = len(str_lines)
1328 len_str = len(str_toprint)
1329 len_str = len(str_toprint)
1329
1330
1330 # Dumb heuristics to guesstimate number of on-screen lines the string
1331 # Dumb heuristics to guesstimate number of on-screen lines the string
1331 # takes. Very basic, but good enough for docstrings in reasonable
1332 # takes. Very basic, but good enough for docstrings in reasonable
1332 # terminals. If someone later feels like refining it, it's not hard.
1333 # terminals. If someone later feels like refining it, it's not hard.
1333 numlines = max(num_newlines,int(len_str/80)+1)
1334 numlines = max(num_newlines,int(len_str/80)+1)
1334
1335
1335 if os.name == "nt":
1336 if os.name == "nt":
1336 screen_lines_def = get_console_size(defaulty=25)[1]
1337 screen_lines_def = get_console_size(defaulty=25)[1]
1337 else:
1338 else:
1338 screen_lines_def = 25 # default value if we can't auto-determine
1339 screen_lines_def = 25 # default value if we can't auto-determine
1339
1340
1340 # auto-determine screen size
1341 # auto-determine screen size
1341 if screen_lines <= 0:
1342 if screen_lines <= 0:
1342 if TERM=='xterm':
1343 if TERM=='xterm':
1343 try:
1344 try:
1344 import curses
1345 import curses
1345 if hasattr(curses,'initscr'):
1346 if hasattr(curses,'initscr'):
1346 use_curses = 1
1347 use_curses = 1
1347 else:
1348 else:
1348 use_curses = 0
1349 use_curses = 0
1349 except ImportError:
1350 except ImportError:
1350 use_curses = 0
1351 use_curses = 0
1351 else:
1352 else:
1352 # curses causes problems on many terminals other than xterm.
1353 # curses causes problems on many terminals other than xterm.
1353 use_curses = 0
1354 use_curses = 0
1354 if use_curses:
1355 if use_curses:
1355 scr = curses.initscr()
1356 scr = curses.initscr()
1356 screen_lines_real,screen_cols = scr.getmaxyx()
1357 screen_lines_real,screen_cols = scr.getmaxyx()
1357 curses.endwin()
1358 curses.endwin()
1358 screen_lines += screen_lines_real
1359 screen_lines += screen_lines_real
1359 #print '***Screen size:',screen_lines_real,'lines x',\
1360 #print '***Screen size:',screen_lines_real,'lines x',\
1360 #screen_cols,'columns.' # dbg
1361 #screen_cols,'columns.' # dbg
1361 else:
1362 else:
1362 screen_lines += screen_lines_def
1363 screen_lines += screen_lines_def
1363
1364
1364 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1365 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1365 if numlines <= screen_lines :
1366 if numlines <= screen_lines :
1366 #print '*** normal print' # dbg
1367 #print '*** normal print' # dbg
1367 print >>Term.cout, str_toprint
1368 print >>Term.cout, str_toprint
1368 else:
1369 else:
1369 # Try to open pager and default to internal one if that fails.
1370 # Try to open pager and default to internal one if that fails.
1370 # All failure modes are tagged as 'retval=1', to match the return
1371 # All failure modes are tagged as 'retval=1', to match the return
1371 # value of a failed system command. If any intermediate attempt
1372 # value of a failed system command. If any intermediate attempt
1372 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1373 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1373 pager_cmd = get_pager_cmd(pager_cmd)
1374 pager_cmd = get_pager_cmd(pager_cmd)
1374 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1375 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1375 if os.name == 'nt':
1376 if os.name == 'nt':
1376 if pager_cmd.startswith('type'):
1377 if pager_cmd.startswith('type'):
1377 # The default WinXP 'type' command is failing on complex strings.
1378 # The default WinXP 'type' command is failing on complex strings.
1378 retval = 1
1379 retval = 1
1379 else:
1380 else:
1380 tmpname = tempfile.mktemp('.txt')
1381 tmpname = tempfile.mktemp('.txt')
1381 tmpfile = file(tmpname,'wt')
1382 tmpfile = file(tmpname,'wt')
1382 tmpfile.write(strng)
1383 tmpfile.write(strng)
1383 tmpfile.close()
1384 tmpfile.close()
1384 cmd = "%s < %s" % (pager_cmd,tmpname)
1385 cmd = "%s < %s" % (pager_cmd,tmpname)
1385 if os.system(cmd):
1386 if os.system(cmd):
1386 retval = 1
1387 retval = 1
1387 else:
1388 else:
1388 retval = None
1389 retval = None
1389 os.remove(tmpname)
1390 os.remove(tmpname)
1390 else:
1391 else:
1391 try:
1392 try:
1392 retval = None
1393 retval = None
1393 # if I use popen4, things hang. No idea why.
1394 # if I use popen4, things hang. No idea why.
1394 #pager,shell_out = os.popen4(pager_cmd)
1395 #pager,shell_out = os.popen4(pager_cmd)
1395 pager = os.popen(pager_cmd,'w')
1396 pager = os.popen(pager_cmd,'w')
1396 pager.write(strng)
1397 pager.write(strng)
1397 pager.close()
1398 pager.close()
1398 retval = pager.close() # success returns None
1399 retval = pager.close() # success returns None
1399 except IOError,msg: # broken pipe when user quits
1400 except IOError,msg: # broken pipe when user quits
1400 if msg.args == (32,'Broken pipe'):
1401 if msg.args == (32,'Broken pipe'):
1401 retval = None
1402 retval = None
1402 else:
1403 else:
1403 retval = 1
1404 retval = 1
1404 except OSError:
1405 except OSError:
1405 # Other strange problems, sometimes seen in Win2k/cygwin
1406 # Other strange problems, sometimes seen in Win2k/cygwin
1406 retval = 1
1407 retval = 1
1407 if retval is not None:
1408 if retval is not None:
1408 page_dumb(strng,screen_lines=screen_lines)
1409 page_dumb(strng,screen_lines=screen_lines)
1409
1410
1410 #----------------------------------------------------------------------------
1411 #----------------------------------------------------------------------------
1411 def page_file(fname,start = 0, pager_cmd = None):
1412 def page_file(fname,start = 0, pager_cmd = None):
1412 """Page a file, using an optional pager command and starting line.
1413 """Page a file, using an optional pager command and starting line.
1413 """
1414 """
1414
1415
1415 pager_cmd = get_pager_cmd(pager_cmd)
1416 pager_cmd = get_pager_cmd(pager_cmd)
1416 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1417 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1417
1418
1418 try:
1419 try:
1419 if os.environ['TERM'] in ['emacs','dumb']:
1420 if os.environ['TERM'] in ['emacs','dumb']:
1420 raise EnvironmentError
1421 raise EnvironmentError
1421 xsys(pager_cmd + ' ' + fname)
1422 xsys(pager_cmd + ' ' + fname)
1422 except:
1423 except:
1423 try:
1424 try:
1424 if start > 0:
1425 if start > 0:
1425 start -= 1
1426 start -= 1
1426 page(open(fname).read(),start)
1427 page(open(fname).read(),start)
1427 except:
1428 except:
1428 print 'Unable to show file',`fname`
1429 print 'Unable to show file',`fname`
1429
1430
1430 #----------------------------------------------------------------------------
1431 #----------------------------------------------------------------------------
1431 def snip_print(str,width = 75,print_full = 0,header = ''):
1432 def snip_print(str,width = 75,print_full = 0,header = ''):
1432 """Print a string snipping the midsection to fit in width.
1433 """Print a string snipping the midsection to fit in width.
1433
1434
1434 print_full: mode control:
1435 print_full: mode control:
1435 - 0: only snip long strings
1436 - 0: only snip long strings
1436 - 1: send to page() directly.
1437 - 1: send to page() directly.
1437 - 2: snip long strings and ask for full length viewing with page()
1438 - 2: snip long strings and ask for full length viewing with page()
1438 Return 1 if snipping was necessary, 0 otherwise."""
1439 Return 1 if snipping was necessary, 0 otherwise."""
1439
1440
1440 if print_full == 1:
1441 if print_full == 1:
1441 page(header+str)
1442 page(header+str)
1442 return 0
1443 return 0
1443
1444
1444 print header,
1445 print header,
1445 if len(str) < width:
1446 if len(str) < width:
1446 print str
1447 print str
1447 snip = 0
1448 snip = 0
1448 else:
1449 else:
1449 whalf = int((width -5)/2)
1450 whalf = int((width -5)/2)
1450 print str[:whalf] + ' <...> ' + str[-whalf:]
1451 print str[:whalf] + ' <...> ' + str[-whalf:]
1451 snip = 1
1452 snip = 1
1452 if snip and print_full == 2:
1453 if snip and print_full == 2:
1453 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1454 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1454 page(str)
1455 page(str)
1455 return snip
1456 return snip
1456
1457
1457 #****************************************************************************
1458 #****************************************************************************
1458 # lists, dicts and structures
1459 # lists, dicts and structures
1459
1460
1460 def belong(candidates,checklist):
1461 def belong(candidates,checklist):
1461 """Check whether a list of items appear in a given list of options.
1462 """Check whether a list of items appear in a given list of options.
1462
1463
1463 Returns a list of 1 and 0, one for each candidate given."""
1464 Returns a list of 1 and 0, one for each candidate given."""
1464
1465
1465 return [x in checklist for x in candidates]
1466 return [x in checklist for x in candidates]
1466
1467
1467 #----------------------------------------------------------------------------
1468 #----------------------------------------------------------------------------
1468 def uniq_stable(elems):
1469 def uniq_stable(elems):
1469 """uniq_stable(elems) -> list
1470 """uniq_stable(elems) -> list
1470
1471
1471 Return from an iterable, a list of all the unique elements in the input,
1472 Return from an iterable, a list of all the unique elements in the input,
1472 but maintaining the order in which they first appear.
1473 but maintaining the order in which they first appear.
1473
1474
1474 A naive solution to this problem which just makes a dictionary with the
1475 A naive solution to this problem which just makes a dictionary with the
1475 elements as keys fails to respect the stability condition, since
1476 elements as keys fails to respect the stability condition, since
1476 dictionaries are unsorted by nature.
1477 dictionaries are unsorted by nature.
1477
1478
1478 Note: All elements in the input must be valid dictionary keys for this
1479 Note: All elements in the input must be valid dictionary keys for this
1479 routine to work, as it internally uses a dictionary for efficiency
1480 routine to work, as it internally uses a dictionary for efficiency
1480 reasons."""
1481 reasons."""
1481
1482
1482 unique = []
1483 unique = []
1483 unique_dict = {}
1484 unique_dict = {}
1484 for nn in elems:
1485 for nn in elems:
1485 if nn not in unique_dict:
1486 if nn not in unique_dict:
1486 unique.append(nn)
1487 unique.append(nn)
1487 unique_dict[nn] = None
1488 unique_dict[nn] = None
1488 return unique
1489 return unique
1489
1490
1490 #----------------------------------------------------------------------------
1491 #----------------------------------------------------------------------------
1491 class NLprinter:
1492 class NLprinter:
1492 """Print an arbitrarily nested list, indicating index numbers.
1493 """Print an arbitrarily nested list, indicating index numbers.
1493
1494
1494 An instance of this class called nlprint is available and callable as a
1495 An instance of this class called nlprint is available and callable as a
1495 function.
1496 function.
1496
1497
1497 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1498 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1498 and using 'sep' to separate the index from the value. """
1499 and using 'sep' to separate the index from the value. """
1499
1500
1500 def __init__(self):
1501 def __init__(self):
1501 self.depth = 0
1502 self.depth = 0
1502
1503
1503 def __call__(self,lst,pos='',**kw):
1504 def __call__(self,lst,pos='',**kw):
1504 """Prints the nested list numbering levels."""
1505 """Prints the nested list numbering levels."""
1505 kw.setdefault('indent',' ')
1506 kw.setdefault('indent',' ')
1506 kw.setdefault('sep',': ')
1507 kw.setdefault('sep',': ')
1507 kw.setdefault('start',0)
1508 kw.setdefault('start',0)
1508 kw.setdefault('stop',len(lst))
1509 kw.setdefault('stop',len(lst))
1509 # we need to remove start and stop from kw so they don't propagate
1510 # we need to remove start and stop from kw so they don't propagate
1510 # into a recursive call for a nested list.
1511 # into a recursive call for a nested list.
1511 start = kw['start']; del kw['start']
1512 start = kw['start']; del kw['start']
1512 stop = kw['stop']; del kw['stop']
1513 stop = kw['stop']; del kw['stop']
1513 if self.depth == 0 and 'header' in kw.keys():
1514 if self.depth == 0 and 'header' in kw.keys():
1514 print kw['header']
1515 print kw['header']
1515
1516
1516 for idx in range(start,stop):
1517 for idx in range(start,stop):
1517 elem = lst[idx]
1518 elem = lst[idx]
1518 if type(elem)==type([]):
1519 if type(elem)==type([]):
1519 self.depth += 1
1520 self.depth += 1
1520 self.__call__(elem,itpl('$pos$idx,'),**kw)
1521 self.__call__(elem,itpl('$pos$idx,'),**kw)
1521 self.depth -= 1
1522 self.depth -= 1
1522 else:
1523 else:
1523 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1524 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1524
1525
1525 nlprint = NLprinter()
1526 nlprint = NLprinter()
1526 #----------------------------------------------------------------------------
1527 #----------------------------------------------------------------------------
1527 def all_belong(candidates,checklist):
1528 def all_belong(candidates,checklist):
1528 """Check whether a list of items ALL appear in a given list of options.
1529 """Check whether a list of items ALL appear in a given list of options.
1529
1530
1530 Returns a single 1 or 0 value."""
1531 Returns a single 1 or 0 value."""
1531
1532
1532 return 1-(0 in [x in checklist for x in candidates])
1533 return 1-(0 in [x in checklist for x in candidates])
1533
1534
1534 #----------------------------------------------------------------------------
1535 #----------------------------------------------------------------------------
1535 def sort_compare(lst1,lst2,inplace = 1):
1536 def sort_compare(lst1,lst2,inplace = 1):
1536 """Sort and compare two lists.
1537 """Sort and compare two lists.
1537
1538
1538 By default it does it in place, thus modifying the lists. Use inplace = 0
1539 By default it does it in place, thus modifying the lists. Use inplace = 0
1539 to avoid that (at the cost of temporary copy creation)."""
1540 to avoid that (at the cost of temporary copy creation)."""
1540 if not inplace:
1541 if not inplace:
1541 lst1 = lst1[:]
1542 lst1 = lst1[:]
1542 lst2 = lst2[:]
1543 lst2 = lst2[:]
1543 lst1.sort(); lst2.sort()
1544 lst1.sort(); lst2.sort()
1544 return lst1 == lst2
1545 return lst1 == lst2
1545
1546
1546 #----------------------------------------------------------------------------
1547 #----------------------------------------------------------------------------
1547 def mkdict(**kwargs):
1548 def mkdict(**kwargs):
1548 """Return a dict from a keyword list.
1549 """Return a dict from a keyword list.
1549
1550
1550 It's just syntactic sugar for making ditcionary creation more convenient:
1551 It's just syntactic sugar for making ditcionary creation more convenient:
1551 # the standard way
1552 # the standard way
1552 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1553 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1553 # a cleaner way
1554 # a cleaner way
1554 >>>data = dict(red=1, green=2, blue=3)
1555 >>>data = dict(red=1, green=2, blue=3)
1555
1556
1556 If you need more than this, look at the Struct() class."""
1557 If you need more than this, look at the Struct() class."""
1557
1558
1558 return kwargs
1559 return kwargs
1559
1560
1560 #----------------------------------------------------------------------------
1561 #----------------------------------------------------------------------------
1561 def list2dict(lst):
1562 def list2dict(lst):
1562 """Takes a list of (key,value) pairs and turns it into a dict."""
1563 """Takes a list of (key,value) pairs and turns it into a dict."""
1563
1564
1564 dic = {}
1565 dic = {}
1565 for k,v in lst: dic[k] = v
1566 for k,v in lst: dic[k] = v
1566 return dic
1567 return dic
1567
1568
1568 #----------------------------------------------------------------------------
1569 #----------------------------------------------------------------------------
1569 def list2dict2(lst,default=''):
1570 def list2dict2(lst,default=''):
1570 """Takes a list and turns it into a dict.
1571 """Takes a list and turns it into a dict.
1571 Much slower than list2dict, but more versatile. This version can take
1572 Much slower than list2dict, but more versatile. This version can take
1572 lists with sublists of arbitrary length (including sclars)."""
1573 lists with sublists of arbitrary length (including sclars)."""
1573
1574
1574 dic = {}
1575 dic = {}
1575 for elem in lst:
1576 for elem in lst:
1576 if type(elem) in (types.ListType,types.TupleType):
1577 if type(elem) in (types.ListType,types.TupleType):
1577 size = len(elem)
1578 size = len(elem)
1578 if size == 0:
1579 if size == 0:
1579 pass
1580 pass
1580 elif size == 1:
1581 elif size == 1:
1581 dic[elem] = default
1582 dic[elem] = default
1582 else:
1583 else:
1583 k,v = elem[0], elem[1:]
1584 k,v = elem[0], elem[1:]
1584 if len(v) == 1: v = v[0]
1585 if len(v) == 1: v = v[0]
1585 dic[k] = v
1586 dic[k] = v
1586 else:
1587 else:
1587 dic[elem] = default
1588 dic[elem] = default
1588 return dic
1589 return dic
1589
1590
1590 #----------------------------------------------------------------------------
1591 #----------------------------------------------------------------------------
1591 def flatten(seq):
1592 def flatten(seq):
1592 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1593 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1593
1594
1594 return [x for subseq in seq for x in subseq]
1595 return [x for subseq in seq for x in subseq]
1595
1596
1596 #----------------------------------------------------------------------------
1597 #----------------------------------------------------------------------------
1597 def get_slice(seq,start=0,stop=None,step=1):
1598 def get_slice(seq,start=0,stop=None,step=1):
1598 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1599 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1599 if stop == None:
1600 if stop == None:
1600 stop = len(seq)
1601 stop = len(seq)
1601 item = lambda i: seq[i]
1602 item = lambda i: seq[i]
1602 return map(item,xrange(start,stop,step))
1603 return map(item,xrange(start,stop,step))
1603
1604
1604 #----------------------------------------------------------------------------
1605 #----------------------------------------------------------------------------
1605 def chop(seq,size):
1606 def chop(seq,size):
1606 """Chop a sequence into chunks of the given size."""
1607 """Chop a sequence into chunks of the given size."""
1607 chunk = lambda i: seq[i:i+size]
1608 chunk = lambda i: seq[i:i+size]
1608 return map(chunk,xrange(0,len(seq),size))
1609 return map(chunk,xrange(0,len(seq),size))
1609
1610
1610 #----------------------------------------------------------------------------
1611 #----------------------------------------------------------------------------
1611 # with is a keyword as of python 2.5, so this function is renamed to withobj
1612 # with is a keyword as of python 2.5, so this function is renamed to withobj
1612 # from its old 'with' name.
1613 # from its old 'with' name.
1613 def with_obj(object, **args):
1614 def with_obj(object, **args):
1614 """Set multiple attributes for an object, similar to Pascal's with.
1615 """Set multiple attributes for an object, similar to Pascal's with.
1615
1616
1616 Example:
1617 Example:
1617 with_obj(jim,
1618 with_obj(jim,
1618 born = 1960,
1619 born = 1960,
1619 haircolour = 'Brown',
1620 haircolour = 'Brown',
1620 eyecolour = 'Green')
1621 eyecolour = 'Green')
1621
1622
1622 Credit: Greg Ewing, in
1623 Credit: Greg Ewing, in
1623 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1624 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1624
1625
1625 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1626 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1626 has become a keyword for Python 2.5, so we had to rename it."""
1627 has become a keyword for Python 2.5, so we had to rename it."""
1627
1628
1628 object.__dict__.update(args)
1629 object.__dict__.update(args)
1629
1630
1630 #----------------------------------------------------------------------------
1631 #----------------------------------------------------------------------------
1631 def setattr_list(obj,alist,nspace = None):
1632 def setattr_list(obj,alist,nspace = None):
1632 """Set a list of attributes for an object taken from a namespace.
1633 """Set a list of attributes for an object taken from a namespace.
1633
1634
1634 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1635 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1635 alist with their values taken from nspace, which must be a dict (something
1636 alist with their values taken from nspace, which must be a dict (something
1636 like locals() will often do) If nspace isn't given, locals() of the
1637 like locals() will often do) If nspace isn't given, locals() of the
1637 *caller* is used, so in most cases you can omit it.
1638 *caller* is used, so in most cases you can omit it.
1638
1639
1639 Note that alist can be given as a string, which will be automatically
1640 Note that alist can be given as a string, which will be automatically
1640 split into a list on whitespace. If given as a list, it must be a list of
1641 split into a list on whitespace. If given as a list, it must be a list of
1641 *strings* (the variable names themselves), not of variables."""
1642 *strings* (the variable names themselves), not of variables."""
1642
1643
1643 # this grabs the local variables from the *previous* call frame -- that is
1644 # this grabs the local variables from the *previous* call frame -- that is
1644 # the locals from the function that called setattr_list().
1645 # the locals from the function that called setattr_list().
1645 # - snipped from weave.inline()
1646 # - snipped from weave.inline()
1646 if nspace is None:
1647 if nspace is None:
1647 call_frame = sys._getframe().f_back
1648 call_frame = sys._getframe().f_back
1648 nspace = call_frame.f_locals
1649 nspace = call_frame.f_locals
1649
1650
1650 if type(alist) in StringTypes:
1651 if type(alist) in StringTypes:
1651 alist = alist.split()
1652 alist = alist.split()
1652 for attr in alist:
1653 for attr in alist:
1653 val = eval(attr,nspace)
1654 val = eval(attr,nspace)
1654 setattr(obj,attr,val)
1655 setattr(obj,attr,val)
1655
1656
1656 #----------------------------------------------------------------------------
1657 #----------------------------------------------------------------------------
1657 def getattr_list(obj,alist,*args):
1658 def getattr_list(obj,alist,*args):
1658 """getattr_list(obj,alist[, default]) -> attribute list.
1659 """getattr_list(obj,alist[, default]) -> attribute list.
1659
1660
1660 Get a list of named attributes for an object. When a default argument is
1661 Get a list of named attributes for an object. When a default argument is
1661 given, it is returned when the attribute doesn't exist; without it, an
1662 given, it is returned when the attribute doesn't exist; without it, an
1662 exception is raised in that case.
1663 exception is raised in that case.
1663
1664
1664 Note that alist can be given as a string, which will be automatically
1665 Note that alist can be given as a string, which will be automatically
1665 split into a list on whitespace. If given as a list, it must be a list of
1666 split into a list on whitespace. If given as a list, it must be a list of
1666 *strings* (the variable names themselves), not of variables."""
1667 *strings* (the variable names themselves), not of variables."""
1667
1668
1668 if type(alist) in StringTypes:
1669 if type(alist) in StringTypes:
1669 alist = alist.split()
1670 alist = alist.split()
1670 if args:
1671 if args:
1671 if len(args)==1:
1672 if len(args)==1:
1672 default = args[0]
1673 default = args[0]
1673 return map(lambda attr: getattr(obj,attr,default),alist)
1674 return map(lambda attr: getattr(obj,attr,default),alist)
1674 else:
1675 else:
1675 raise ValueError,'getattr_list() takes only one optional argument'
1676 raise ValueError,'getattr_list() takes only one optional argument'
1676 else:
1677 else:
1677 return map(lambda attr: getattr(obj,attr),alist)
1678 return map(lambda attr: getattr(obj,attr),alist)
1678
1679
1679 #----------------------------------------------------------------------------
1680 #----------------------------------------------------------------------------
1680 def map_method(method,object_list,*argseq,**kw):
1681 def map_method(method,object_list,*argseq,**kw):
1681 """map_method(method,object_list,*args,**kw) -> list
1682 """map_method(method,object_list,*args,**kw) -> list
1682
1683
1683 Return a list of the results of applying the methods to the items of the
1684 Return a list of the results of applying the methods to the items of the
1684 argument sequence(s). If more than one sequence is given, the method is
1685 argument sequence(s). If more than one sequence is given, the method is
1685 called with an argument list consisting of the corresponding item of each
1686 called with an argument list consisting of the corresponding item of each
1686 sequence. All sequences must be of the same length.
1687 sequence. All sequences must be of the same length.
1687
1688
1688 Keyword arguments are passed verbatim to all objects called.
1689 Keyword arguments are passed verbatim to all objects called.
1689
1690
1690 This is Python code, so it's not nearly as fast as the builtin map()."""
1691 This is Python code, so it's not nearly as fast as the builtin map()."""
1691
1692
1692 out_list = []
1693 out_list = []
1693 idx = 0
1694 idx = 0
1694 for object in object_list:
1695 for object in object_list:
1695 try:
1696 try:
1696 handler = getattr(object, method)
1697 handler = getattr(object, method)
1697 except AttributeError:
1698 except AttributeError:
1698 out_list.append(None)
1699 out_list.append(None)
1699 else:
1700 else:
1700 if argseq:
1701 if argseq:
1701 args = map(lambda lst:lst[idx],argseq)
1702 args = map(lambda lst:lst[idx],argseq)
1702 #print 'ob',object,'hand',handler,'ar',args # dbg
1703 #print 'ob',object,'hand',handler,'ar',args # dbg
1703 out_list.append(handler(args,**kw))
1704 out_list.append(handler(args,**kw))
1704 else:
1705 else:
1705 out_list.append(handler(**kw))
1706 out_list.append(handler(**kw))
1706 idx += 1
1707 idx += 1
1707 return out_list
1708 return out_list
1708
1709
1709 #----------------------------------------------------------------------------
1710 #----------------------------------------------------------------------------
1710 def import_fail_info(mod_name,fns=None):
1711 def import_fail_info(mod_name,fns=None):
1711 """Inform load failure for a module."""
1712 """Inform load failure for a module."""
1712
1713
1713 if fns == None:
1714 if fns == None:
1714 warn("Loading of %s failed.\n" % (mod_name,))
1715 warn("Loading of %s failed.\n" % (mod_name,))
1715 else:
1716 else:
1716 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1717 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1717
1718
1718 #----------------------------------------------------------------------------
1719 #----------------------------------------------------------------------------
1719 # Proposed popitem() extension, written as a method
1720 # Proposed popitem() extension, written as a method
1720
1721
1721
1722
1722 class NotGiven: pass
1723 class NotGiven: pass
1723
1724
1724 def popkey(dct,key,default=NotGiven):
1725 def popkey(dct,key,default=NotGiven):
1725 """Return dct[key] and delete dct[key].
1726 """Return dct[key] and delete dct[key].
1726
1727
1727 If default is given, return it if dct[key] doesn't exist, otherwise raise
1728 If default is given, return it if dct[key] doesn't exist, otherwise raise
1728 KeyError. """
1729 KeyError. """
1729
1730
1730 try:
1731 try:
1731 val = dct[key]
1732 val = dct[key]
1732 except KeyError:
1733 except KeyError:
1733 if default is NotGiven:
1734 if default is NotGiven:
1734 raise
1735 raise
1735 else:
1736 else:
1736 return default
1737 return default
1737 else:
1738 else:
1738 del dct[key]
1739 del dct[key]
1739 return val
1740 return val
1740
1741
1741 def wrap_deprecated(func, suggest = '<nothing>'):
1742 def wrap_deprecated(func, suggest = '<nothing>'):
1742 def newFunc(*args, **kwargs):
1743 def newFunc(*args, **kwargs):
1743 warnings.warn("Call to deprecated function %s, use %s instead" %
1744 warnings.warn("Call to deprecated function %s, use %s instead" %
1744 ( func.__name__, suggest),
1745 ( func.__name__, suggest),
1745 category=DeprecationWarning,
1746 category=DeprecationWarning,
1746 stacklevel = 2)
1747 stacklevel = 2)
1747 return func(*args, **kwargs)
1748 return func(*args, **kwargs)
1748 return newFunc
1749 return newFunc
1749
1750
1750 #*************************** end of file <genutils.py> **********************
1751 #*************************** end of file <genutils.py> **********************
1751
1752
@@ -1,642 +1,642 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 #*****************************************************************************
2 #*****************************************************************************
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 #
4 #
5 # Distributed under the terms of the BSD License. The full license is in
5 # Distributed under the terms of the BSD License. The full license is in
6 # the file COPYING, distributed as part of this software.
6 # the file COPYING, distributed as part of this software.
7 #*****************************************************************************
7 #*****************************************************************************
8
8
9 # $Id: usage.py 2010 2006-12-20 15:29:17Z vivainio $
9 # $Id: usage.py 2152 2007-03-18 20:13:35Z fperez $
10
10
11 from IPython import Release
11 from IPython import Release
12 __author__ = '%s <%s>' % Release.authors['Fernando']
12 __author__ = '%s <%s>' % Release.authors['Fernando']
13 __license__ = Release.license
13 __license__ = Release.license
14 __version__ = Release.version
14 __version__ = Release.version
15
15
16 __doc__ = """
16 __doc__ = """
17 IPython -- An enhanced Interactive Python
17 IPython -- An enhanced Interactive Python
18 =========================================
18 =========================================
19
19
20 A Python shell with automatic history (input and output), dynamic object
20 A Python shell with automatic history (input and output), dynamic object
21 introspection, easier configuration, command completion, access to the system
21 introspection, easier configuration, command completion, access to the system
22 shell and more.
22 shell and more.
23
23
24 IPython can also be embedded in running programs. See EMBEDDING below.
24 IPython can also be embedded in running programs. See EMBEDDING below.
25
25
26
26
27 USAGE
27 USAGE
28 ipython [options] files
28 ipython [options] files
29
29
30 If invoked with no options, it executes all the files listed in
30 If invoked with no options, it executes all the files listed in
31 sequence and drops you into the interpreter while still acknowledging
31 sequence and drops you into the interpreter while still acknowledging
32 any options you may have set in your ipythonrc file. This behavior is
32 any options you may have set in your ipythonrc file. This behavior is
33 different from standard Python, which when called as python -i will
33 different from standard Python, which when called as python -i will
34 only execute one file and will ignore your configuration setup.
34 only execute one file and will ignore your configuration setup.
35
35
36 Please note that some of the configuration options are not available at
36 Please note that some of the configuration options are not available at
37 the command line, simply because they are not practical here. Look into
37 the command line, simply because they are not practical here. Look into
38 your ipythonrc configuration file for details on those. This file
38 your ipythonrc configuration file for details on those. This file
39 typically installed in the $HOME/.ipython directory.
39 typically installed in the $HOME/.ipython directory.
40
40
41 For Windows users, $HOME resolves to C:\\Documents and
41 For Windows users, $HOME resolves to C:\\Documents and
42 Settings\\YourUserName in most instances, and _ipython is used instead
42 Settings\\YourUserName in most instances, and _ipython is used instead
43 of .ipython, since some Win32 programs have problems with dotted names
43 of .ipython, since some Win32 programs have problems with dotted names
44 in directories.
44 in directories.
45
45
46 In the rest of this text, we will refer to this directory as
46 In the rest of this text, we will refer to this directory as
47 IPYTHONDIR.
47 IPYTHONDIR.
48
48
49
49
50 SPECIAL THREADING OPTIONS
50 SPECIAL THREADING OPTIONS
51 The following special options are ONLY valid at the beginning of the
51 The following special options are ONLY valid at the beginning of the
52 command line, and not later. This is because they control the initial-
52 command line, and not later. This is because they control the initial-
53 ization of ipython itself, before the normal option-handling mechanism
53 ization of ipython itself, before the normal option-handling mechanism
54 is active.
54 is active.
55
55
56 -gthread, -qthread, -wthread, -pylab
56 -gthread, -qthread, -q4thread, -wthread, -pylab
57
57
58 Only ONE of these can be given, and it can only be given as the
58 Only ONE of these can be given, and it can only be given as the
59 first option passed to IPython (it will have no effect in any
59 first option passed to IPython (it will have no effect in any
60 other position). They provide threading support for the GTK, QT
60 other position). They provide threading support for the GTK, QT
61 and WXWidgets toolkits, and for the matplotlib library.
61 and WXWidgets toolkits, and for the matplotlib library.
62
62
63 With any of the first three options, IPython starts running a
63 With any of the first four options, IPython starts running a
64 separate thread for the graphical toolkit's operation, so that
64 separate thread for the graphical toolkit's operation, so that
65 you can open and control graphical elements from within an
65 you can open and control graphical elements from within an
66 IPython command line, without blocking. All three provide
66 IPython command line, without blocking. All four provide
67 essentially the same functionality, respectively for GTK, QT and
67 essentially the same functionality, respectively for GTK, QT3,
68 WXWidgets (via their Python interfaces).
68 QT4 and WXWidgets (via their Python interfaces).
69
69
70 Note that with -wthread, you can additionally use the -wxversion
70 Note that with -wthread, you can additionally use the -wxversion
71 option to request a specific version of wx to be used. This
71 option to request a specific version of wx to be used. This
72 requires that you have the 'wxversion' Python module installed,
72 requires that you have the 'wxversion' Python module installed,
73 which is part of recent wxPython distributions.
73 which is part of recent wxPython distributions.
74
74
75 If -pylab is given, IPython loads special support for the mat-
75 If -pylab is given, IPython loads special support for the mat-
76 plotlib library (http://matplotlib.sourceforge.net), allowing
76 plotlib library (http://matplotlib.sourceforge.net), allowing
77 interactive usage of any of its backends as defined in the
77 interactive usage of any of its backends as defined in the
78 user's .matplotlibrc file. It automatically activates GTK, QT
78 user's .matplotlibrc file. It automatically activates GTK, QT
79 or WX threading for IPyhton if the choice of matplotlib backend
79 or WX threading for IPyhton if the choice of matplotlib backend
80 requires it. It also modifies the %run command to correctly
80 requires it. It also modifies the %run command to correctly
81 execute (without blocking) any matplotlib-based script which
81 execute (without blocking) any matplotlib-based script which
82 calls show() at the end.
82 calls show() at the end.
83
83
84 -tk The -g/q/wthread options, and -pylab (if matplotlib is
84 -tk The -g/q/q4/wthread options, and -pylab (if matplotlib is
85 configured to use GTK, QT or WX), will normally block Tk
85 configured to use GTK, QT or WX), will normally block Tk
86 graphical interfaces. This means that when GTK, QT or WX
86 graphical interfaces. This means that when GTK, QT or WX
87 threading is active, any attempt to open a Tk GUI will result in
87 threading is active, any attempt to open a Tk GUI will result in
88 a dead window, and possibly cause the Python interpreter to
88 a dead window, and possibly cause the Python interpreter to
89 crash. An extra option, -tk, is available to address this
89 crash. An extra option, -tk, is available to address this
90 issue. It can ONLY be given as a SECOND option after any of the
90 issue. It can ONLY be given as a SECOND option after any of the
91 above (-gthread, -qthread, -wthread or -pylab).
91 above (-gthread, -qthread, q4thread, -wthread or -pylab).
92
92
93 If -tk is given, IPython will try to coordinate Tk threading
93 If -tk is given, IPython will try to coordinate Tk threading
94 with GTK, QT or WX. This is however potentially unreliable, and
94 with GTK, QT or WX. This is however potentially unreliable, and
95 you will have to test on your platform and Python configuration
95 you will have to test on your platform and Python configuration
96 to determine whether it works for you. Debian users have
96 to determine whether it works for you. Debian users have
97 reported success, apparently due to the fact that Debian builds
97 reported success, apparently due to the fact that Debian builds
98 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
98 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
99 other Linux environments (such as Fedora Core 2/3), this option
99 other Linux environments (such as Fedora Core 2/3), this option
100 has caused random crashes and lockups of the Python interpreter.
100 has caused random crashes and lockups of the Python interpreter.
101 Under other operating systems (Mac OSX and Windows), you'll need
101 Under other operating systems (Mac OSX and Windows), you'll need
102 to try it to find out, since currently no user reports are
102 to try it to find out, since currently no user reports are
103 available.
103 available.
104
104
105 There is unfortunately no way for IPython to determine at run-
105 There is unfortunately no way for IPython to determine at run-
106 time whether -tk will work reliably or not, so you will need to
106 time whether -tk will work reliably or not, so you will need to
107 do some experiments before relying on it for regular work.
107 do some experiments before relying on it for regular work.
108
108
109 A WARNING ABOUT SIGNALS AND THREADS
109 A WARNING ABOUT SIGNALS AND THREADS
110
110
111 When any of the thread systems (GTK, QT or WX) are active, either
111 When any of the thread systems (GTK, QT or WX) are active, either
112 directly or via -pylab with a threaded backend, it is impossible to
112 directly or via -pylab with a threaded backend, it is impossible to
113 interrupt long-running Python code via Ctrl-C. IPython can not pass
113 interrupt long-running Python code via Ctrl-C. IPython can not pass
114 the KeyboardInterrupt exception (or the underlying SIGINT) across
114 the KeyboardInterrupt exception (or the underlying SIGINT) across
115 threads, so any long-running process started from IPython will run to
115 threads, so any long-running process started from IPython will run to
116 completion, or will have to be killed via an external (OS-based)
116 completion, or will have to be killed via an external (OS-based)
117 mechanism.
117 mechanism.
118
118
119 To the best of my knowledge, this limitation is imposed by the Python
119 To the best of my knowledge, this limitation is imposed by the Python
120 interpreter itself, and it comes from the difficulty of writing
120 interpreter itself, and it comes from the difficulty of writing
121 portable signal/threaded code. If any user is an expert on this topic
121 portable signal/threaded code. If any user is an expert on this topic
122 and can suggest a better solution, I would love to hear about it. In
122 and can suggest a better solution, I would love to hear about it. In
123 the IPython sources, look at the Shell.py module, and in particular at
123 the IPython sources, look at the Shell.py module, and in particular at
124 the runcode() method.
124 the runcode() method.
125
125
126 REGULAR OPTIONS
126 REGULAR OPTIONS
127 After the above threading options have been given, regular options can
127 After the above threading options have been given, regular options can
128 follow in any order. All options can be abbreviated to their shortest
128 follow in any order. All options can be abbreviated to their shortest
129 non-ambiguous form and are case-sensitive. One or two dashes can be
129 non-ambiguous form and are case-sensitive. One or two dashes can be
130 used. Some options have an alternate short form, indicated after a |.
130 used. Some options have an alternate short form, indicated after a |.
131
131
132 Most options can also be set from your ipythonrc configuration file.
132 Most options can also be set from your ipythonrc configuration file.
133 See the provided examples for assistance. Options given on the comman-
133 See the provided examples for assistance. Options given on the comman-
134 dline override the values set in the ipythonrc file.
134 dline override the values set in the ipythonrc file.
135
135
136 All options with a [no] prepended can be specified in negated form
136 All options with a [no] prepended can be specified in negated form
137 (using -nooption instead of -option) to turn the feature off.
137 (using -nooption instead of -option) to turn the feature off.
138
138
139 -h, --help
139 -h, --help
140 Show summary of options.
140 Show summary of options.
141
141
142 -pylab This can only be given as the first option passed to IPython (it
142 -pylab This can only be given as the first option passed to IPython (it
143 will have no effect in any other position). It adds special sup-
143 will have no effect in any other position). It adds special sup-
144 port for the matplotlib library (http://matplotlib.source-
144 port for the matplotlib library (http://matplotlib.source-
145 forge.net), allowing interactive usage of any of its backends as
145 forge.net), allowing interactive usage of any of its backends as
146 defined in the user's .matplotlibrc file. It automatically
146 defined in the user's .matplotlibrc file. It automatically
147 activates GTK or WX threading for IPyhton if the choice of mat-
147 activates GTK or WX threading for IPyhton if the choice of mat-
148 plotlib backend requires it. It also modifies the @run command
148 plotlib backend requires it. It also modifies the @run command
149 to correctly execute (without blocking) any matplotlib-based
149 to correctly execute (without blocking) any matplotlib-based
150 script which calls show() at the end.
150 script which calls show() at the end.
151
151
152 -autocall <val>
152 -autocall <val>
153 Make IPython automatically call any callable object even if you
153 Make IPython automatically call any callable object even if you
154 didn't type explicit parentheses. For example, 'str 43' becomes
154 didn't type explicit parentheses. For example, 'str 43' becomes
155 'str(43)' automatically. The value can be '0' to disable the
155 'str(43)' automatically. The value can be '0' to disable the
156 feature, '1' for 'smart' autocall, where it is not applied if
156 feature, '1' for 'smart' autocall, where it is not applied if
157 there are no more arguments on the line, and '2' for 'full'
157 there are no more arguments on the line, and '2' for 'full'
158 autocall, where all callable objects are automatically called
158 autocall, where all callable objects are automatically called
159 (even if no arguments are present). The default is '1'.
159 (even if no arguments are present). The default is '1'.
160
160
161 -[no]autoindent
161 -[no]autoindent
162 Turn automatic indentation on/off.
162 Turn automatic indentation on/off.
163
163
164 -[no]automagic
164 -[no]automagic
165 Make magic commands automatic (without needing their first char-
165 Make magic commands automatic (without needing their first char-
166 acter to be %). Type %magic at the IPython prompt for more
166 acter to be %). Type %magic at the IPython prompt for more
167 information.
167 information.
168
168
169 -[no]autoedit_syntax
169 -[no]autoedit_syntax
170 When a syntax error occurs after editing a file, automatically
170 When a syntax error occurs after editing a file, automatically
171 open the file to the trouble causing line for convenient fixing.
171 open the file to the trouble causing line for convenient fixing.
172
172
173 -[no]banner
173 -[no]banner
174 Print the intial information banner (default on).
174 Print the intial information banner (default on).
175
175
176 -c <command>
176 -c <command>
177 Execute the given command string, and set sys.argv to ['c'].
177 Execute the given command string, and set sys.argv to ['c'].
178 This is similar to the -c option in the normal Python inter-
178 This is similar to the -c option in the normal Python inter-
179 preter.
179 preter.
180
180
181 -cache_size|cs <n>
181 -cache_size|cs <n>
182 Size of the output cache (maximum number of entries to hold in
182 Size of the output cache (maximum number of entries to hold in
183 memory). The default is 1000, you can change it permanently in
183 memory). The default is 1000, you can change it permanently in
184 your config file. Setting it to 0 completely disables the
184 your config file. Setting it to 0 completely disables the
185 caching system, and the minimum value accepted is 20 (if you
185 caching system, and the minimum value accepted is 20 (if you
186 provide a value less than 20, it is reset to 0 and a warning is
186 provide a value less than 20, it is reset to 0 and a warning is
187 issued). This limit is defined because otherwise you'll spend
187 issued). This limit is defined because otherwise you'll spend
188 more time re-flushing a too small cache than working.
188 more time re-flushing a too small cache than working.
189
189
190 -classic|cl
190 -classic|cl
191 Gives IPython a similar feel to the classic Python prompt.
191 Gives IPython a similar feel to the classic Python prompt.
192
192
193 -colors <scheme>
193 -colors <scheme>
194 Color scheme for prompts and exception reporting. Currently
194 Color scheme for prompts and exception reporting. Currently
195 implemented: NoColor, Linux, and LightBG.
195 implemented: NoColor, Linux, and LightBG.
196
196
197 -[no]color_info
197 -[no]color_info
198 IPython can display information about objects via a set of func-
198 IPython can display information about objects via a set of func-
199 tions, and optionally can use colors for this, syntax highlight-
199 tions, and optionally can use colors for this, syntax highlight-
200 ing source code and various other elements. However, because
200 ing source code and various other elements. However, because
201 this information is passed through a pager (like 'less') and
201 this information is passed through a pager (like 'less') and
202 many pagers get confused with color codes, this option is off by
202 many pagers get confused with color codes, this option is off by
203 default. You can test it and turn it on permanently in your
203 default. You can test it and turn it on permanently in your
204 ipythonrc file if it works for you. As a reference, the 'less'
204 ipythonrc file if it works for you. As a reference, the 'less'
205 pager supplied with Mandrake 8.2 works ok, but that in RedHat
205 pager supplied with Mandrake 8.2 works ok, but that in RedHat
206 7.2 doesn't.
206 7.2 doesn't.
207
207
208 Test it and turn it on permanently if it works with your system.
208 Test it and turn it on permanently if it works with your system.
209 The magic function @color_info allows you to toggle this inter-
209 The magic function @color_info allows you to toggle this inter-
210 actively for testing.
210 actively for testing.
211
211
212 -[no]confirm_exit
212 -[no]confirm_exit
213 Set to confirm when you try to exit IPython with an EOF (Con-
213 Set to confirm when you try to exit IPython with an EOF (Con-
214 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
214 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
215 magic functions @Exit or @Quit you can force a direct exit,
215 magic functions @Exit or @Quit you can force a direct exit,
216 bypassing any confirmation.
216 bypassing any confirmation.
217
217
218 -[no]debug
218 -[no]debug
219 Show information about the loading process. Very useful to pin
219 Show information about the loading process. Very useful to pin
220 down problems with your configuration files or to get details
220 down problems with your configuration files or to get details
221 about session restores.
221 about session restores.
222
222
223 -[no]deep_reload
223 -[no]deep_reload
224 IPython can use the deep_reload module which reloads changes in
224 IPython can use the deep_reload module which reloads changes in
225 modules recursively (it replaces the reload() function, so you
225 modules recursively (it replaces the reload() function, so you
226 don't need to change anything to use it). deep_reload() forces a
226 don't need to change anything to use it). deep_reload() forces a
227 full reload of modules whose code may have changed, which the
227 full reload of modules whose code may have changed, which the
228 default reload() function does not.
228 default reload() function does not.
229
229
230 When deep_reload is off, IPython will use the normal reload(),
230 When deep_reload is off, IPython will use the normal reload(),
231 but deep_reload will still be available as dreload(). This fea-
231 but deep_reload will still be available as dreload(). This fea-
232 ture is off by default [which means that you have both normal
232 ture is off by default [which means that you have both normal
233 reload() and dreload()].
233 reload() and dreload()].
234
234
235 -editor <name>
235 -editor <name>
236 Which editor to use with the @edit command. By default, IPython
236 Which editor to use with the @edit command. By default, IPython
237 will honor your EDITOR environment variable (if not set, vi is
237 will honor your EDITOR environment variable (if not set, vi is
238 the Unix default and notepad the Windows one). Since this editor
238 the Unix default and notepad the Windows one). Since this editor
239 is invoked on the fly by IPython and is meant for editing small
239 is invoked on the fly by IPython and is meant for editing small
240 code snippets, you may want to use a small, lightweight editor
240 code snippets, you may want to use a small, lightweight editor
241 here (in case your default EDITOR is something like Emacs).
241 here (in case your default EDITOR is something like Emacs).
242
242
243 -ipythondir <name>
243 -ipythondir <name>
244 The name of your IPython configuration directory IPYTHONDIR.
244 The name of your IPython configuration directory IPYTHONDIR.
245 This can also be specified through the environment variable
245 This can also be specified through the environment variable
246 IPYTHONDIR.
246 IPYTHONDIR.
247
247
248 -log|l Generate a log file of all input. The file is named
248 -log|l Generate a log file of all input. The file is named
249 ipython_log.py in your current directory (which prevents logs
249 ipython_log.py in your current directory (which prevents logs
250 from multiple IPython sessions from trampling each other). You
250 from multiple IPython sessions from trampling each other). You
251 can use this to later restore a session by loading your logfile
251 can use this to later restore a session by loading your logfile
252 as a file to be executed with option -logplay (see below).
252 as a file to be executed with option -logplay (see below).
253
253
254 -logfile|lf
254 -logfile|lf
255 Specify the name of your logfile.
255 Specify the name of your logfile.
256
256
257 -logplay|lp
257 -logplay|lp
258 Replay a previous log. For restoring a session as close as pos-
258 Replay a previous log. For restoring a session as close as pos-
259 sible to the state you left it in, use this option (don't just
259 sible to the state you left it in, use this option (don't just
260 run the logfile). With -logplay, IPython will try to reconstruct
260 run the logfile). With -logplay, IPython will try to reconstruct
261 the previous working environment in full, not just execute the
261 the previous working environment in full, not just execute the
262 commands in the logfile.
262 commands in the logfile.
263 When a session is restored, logging is automatically turned on
263 When a session is restored, logging is automatically turned on
264 again with the name of the logfile it was invoked with (it is
264 again with the name of the logfile it was invoked with (it is
265 read from the log header). So once you've turned logging on for
265 read from the log header). So once you've turned logging on for
266 a session, you can quit IPython and reload it as many times as
266 a session, you can quit IPython and reload it as many times as
267 you want and it will continue to log its history and restore
267 you want and it will continue to log its history and restore
268 from the beginning every time.
268 from the beginning every time.
269
269
270 Caveats: there are limitations in this option. The history vari-
270 Caveats: there are limitations in this option. The history vari-
271 ables _i*,_* and _dh don't get restored properly. In the future
271 ables _i*,_* and _dh don't get restored properly. In the future
272 we will try to implement full session saving by writing and
272 we will try to implement full session saving by writing and
273 retrieving a failed because of inherent limitations of Python's
273 retrieving a failed because of inherent limitations of Python's
274 Pickle module, so this may have to wait.
274 Pickle module, so this may have to wait.
275
275
276 -[no]messages
276 -[no]messages
277 Print messages which IPython collects about its startup process
277 Print messages which IPython collects about its startup process
278 (default on).
278 (default on).
279
279
280 -[no]pdb
280 -[no]pdb
281 Automatically call the pdb debugger after every uncaught excep-
281 Automatically call the pdb debugger after every uncaught excep-
282 tion. If you are used to debugging using pdb, this puts you
282 tion. If you are used to debugging using pdb, this puts you
283 automatically inside of it after any call (either in IPython or
283 automatically inside of it after any call (either in IPython or
284 in code called by it) which triggers an exception which goes
284 in code called by it) which triggers an exception which goes
285 uncaught.
285 uncaught.
286
286
287 -[no]pprint
287 -[no]pprint
288 IPython can optionally use the pprint (pretty printer) module
288 IPython can optionally use the pprint (pretty printer) module
289 for displaying results. pprint tends to give a nicer display of
289 for displaying results. pprint tends to give a nicer display of
290 nested data structures. If you like it, you can turn it on per-
290 nested data structures. If you like it, you can turn it on per-
291 manently in your config file (default off).
291 manently in your config file (default off).
292
292
293 -profile|p <name>
293 -profile|p <name>
294 Assume that your config file is ipythonrc-<name> (looks in cur-
294 Assume that your config file is ipythonrc-<name> (looks in cur-
295 rent dir first, then in IPYTHONDIR). This is a quick way to keep
295 rent dir first, then in IPYTHONDIR). This is a quick way to keep
296 and load multiple config files for different tasks, especially
296 and load multiple config files for different tasks, especially
297 if you use the include option of config files. You can keep a
297 if you use the include option of config files. You can keep a
298 basic IPYTHONDIR/ipythonrc file and then have other 'profiles'
298 basic IPYTHONDIR/ipythonrc file and then have other 'profiles'
299 which include this one and load extra things for particular
299 which include this one and load extra things for particular
300 tasks. For example:
300 tasks. For example:
301
301
302 1) $HOME/.ipython/ipythonrc : load basic things you always want.
302 1) $HOME/.ipython/ipythonrc : load basic things you always want.
303 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
303 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
304 related modules.
304 related modules.
305 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
305 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
306 plotting modules.
306 plotting modules.
307
307
308 Since it is possible to create an endless loop by having circu-
308 Since it is possible to create an endless loop by having circu-
309 lar file inclusions, IPython will stop if it reaches 15 recur-
309 lar file inclusions, IPython will stop if it reaches 15 recur-
310 sive inclusions.
310 sive inclusions.
311
311
312 -prompt_in1|pi1 <string>
312 -prompt_in1|pi1 <string>
313 Specify the string used for input prompts. Note that if you are
313 Specify the string used for input prompts. Note that if you are
314 using numbered prompts, the number is represented with a '\#' in
314 using numbered prompts, the number is represented with a '\#' in
315 the string. Don't forget to quote strings with spaces embedded
315 the string. Don't forget to quote strings with spaces embedded
316 in them. Default: 'In [\#]: '.
316 in them. Default: 'In [\#]: '.
317
317
318 Most bash-like escapes can be used to customize IPython's
318 Most bash-like escapes can be used to customize IPython's
319 prompts, as well as a few additional ones which are IPython-spe-
319 prompts, as well as a few additional ones which are IPython-spe-
320 cific. All valid prompt escapes are described in detail in the
320 cific. All valid prompt escapes are described in detail in the
321 Customization section of the IPython HTML/PDF manual.
321 Customization section of the IPython HTML/PDF manual.
322
322
323 -prompt_in2|pi2 <string>
323 -prompt_in2|pi2 <string>
324 Similar to the previous option, but used for the continuation
324 Similar to the previous option, but used for the continuation
325 prompts. The special sequence '\D' is similar to '\#', but with
325 prompts. The special sequence '\D' is similar to '\#', but with
326 all digits replaced dots (so you can have your continuation
326 all digits replaced dots (so you can have your continuation
327 prompt aligned with your input prompt). Default: ' .\D.: '
327 prompt aligned with your input prompt). Default: ' .\D.: '
328 (note three spaces at the start for alignment with 'In [\#]').
328 (note three spaces at the start for alignment with 'In [\#]').
329
329
330 -prompt_out|po <string>
330 -prompt_out|po <string>
331 String used for output prompts, also uses numbers like
331 String used for output prompts, also uses numbers like
332 prompt_in1. Default: 'Out[\#]:'.
332 prompt_in1. Default: 'Out[\#]:'.
333
333
334 -quick Start in bare bones mode (no config file loaded).
334 -quick Start in bare bones mode (no config file loaded).
335
335
336 -rcfile <name>
336 -rcfile <name>
337 Name of your IPython resource configuration file. normally
337 Name of your IPython resource configuration file. normally
338 IPython loads ipythonrc (from current directory) or
338 IPython loads ipythonrc (from current directory) or
339 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
339 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
340 IPython starts with a bare bones configuration (no modules
340 IPython starts with a bare bones configuration (no modules
341 loaded at all).
341 loaded at all).
342
342
343 -[no]readline
343 -[no]readline
344 Use the readline library, which is needed to support name com-
344 Use the readline library, which is needed to support name com-
345 pletion and command history, among other things. It is enabled
345 pletion and command history, among other things. It is enabled
346 by default, but may cause problems for users of X/Emacs in
346 by default, but may cause problems for users of X/Emacs in
347 Python comint or shell buffers.
347 Python comint or shell buffers.
348
348
349 Note that emacs 'eterm' buffers (opened with M-x term) support
349 Note that emacs 'eterm' buffers (opened with M-x term) support
350 IPython's readline and syntax coloring fine, only 'emacs' (M-x
350 IPython's readline and syntax coloring fine, only 'emacs' (M-x
351 shell and C-c !) buffers do not.
351 shell and C-c !) buffers do not.
352
352
353 -screen_length|sl <n>
353 -screen_length|sl <n>
354 Number of lines of your screen. This is used to control print-
354 Number of lines of your screen. This is used to control print-
355 ing of very long strings. Strings longer than this number of
355 ing of very long strings. Strings longer than this number of
356 lines will be sent through a pager instead of directly printed.
356 lines will be sent through a pager instead of directly printed.
357
357
358 The default value for this is 0, which means IPython will auto-
358 The default value for this is 0, which means IPython will auto-
359 detect your screen size every time it needs to print certain
359 detect your screen size every time it needs to print certain
360 potentially long strings (this doesn't change the behavior of
360 potentially long strings (this doesn't change the behavior of
361 the 'print' keyword, it's only triggered internally). If for
361 the 'print' keyword, it's only triggered internally). If for
362 some reason this isn't working well (it needs curses support),
362 some reason this isn't working well (it needs curses support),
363 specify it yourself. Otherwise don't change the default.
363 specify it yourself. Otherwise don't change the default.
364
364
365 -separate_in|si <string>
365 -separate_in|si <string>
366 Separator before input prompts. Default '0.
366 Separator before input prompts. Default '0.
367
367
368 -separate_out|so <string>
368 -separate_out|so <string>
369 Separator before output prompts. Default: 0 (nothing).
369 Separator before output prompts. Default: 0 (nothing).
370
370
371 -separate_out2|so2 <string>
371 -separate_out2|so2 <string>
372 Separator after output prompts. Default: 0 (nothing).
372 Separator after output prompts. Default: 0 (nothing).
373
373
374 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
374 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
375 Simply removes all input/output separators.
375 Simply removes all input/output separators.
376
376
377 -upgrade
377 -upgrade
378 Allows you to upgrade your IPYTHONDIR configuration when you
378 Allows you to upgrade your IPYTHONDIR configuration when you
379 install a new version of IPython. Since new versions may
379 install a new version of IPython. Since new versions may
380 include new command lines options or example files, this copies
380 include new command lines options or example files, this copies
381 updated ipythonrc-type files. However, it backs up (with a .old
381 updated ipythonrc-type files. However, it backs up (with a .old
382 extension) all files which it overwrites so that you can merge
382 extension) all files which it overwrites so that you can merge
383 back any custimizations you might have in your personal files.
383 back any custimizations you might have in your personal files.
384
384
385 -Version
385 -Version
386 Print version information and exit.
386 Print version information and exit.
387
387
388 -wxversion <string>
388 -wxversion <string>
389 Select a specific version of wxPython (used in conjunction with
389 Select a specific version of wxPython (used in conjunction with
390 -wthread). Requires the wxversion module, part of recent
390 -wthread). Requires the wxversion module, part of recent
391 wxPython distributions.
391 wxPython distributions.
392
392
393 -xmode <modename>
393 -xmode <modename>
394 Mode for exception reporting. The valid modes are Plain, Con-
394 Mode for exception reporting. The valid modes are Plain, Con-
395 text, and Verbose.
395 text, and Verbose.
396
396
397 - Plain: similar to python's normal traceback printing.
397 - Plain: similar to python's normal traceback printing.
398
398
399 - Context: prints 5 lines of context source code around each
399 - Context: prints 5 lines of context source code around each
400 line in the traceback.
400 line in the traceback.
401
401
402 - Verbose: similar to Context, but additionally prints the vari-
402 - Verbose: similar to Context, but additionally prints the vari-
403 ables currently visible where the exception happened (shortening
403 ables currently visible where the exception happened (shortening
404 their strings if too long). This can potentially be very slow,
404 their strings if too long). This can potentially be very slow,
405 if you happen to have a huge data structure whose string repre-
405 if you happen to have a huge data structure whose string repre-
406 sentation is complex to compute. Your computer may appear to
406 sentation is complex to compute. Your computer may appear to
407 freeze for a while with cpu usage at 100%. If this occurs, you
407 freeze for a while with cpu usage at 100%. If this occurs, you
408 can cancel the traceback with Ctrl-C (maybe hitting it more than
408 can cancel the traceback with Ctrl-C (maybe hitting it more than
409 once).
409 once).
410
410
411
411
412 EMBEDDING
412 EMBEDDING
413 It is possible to start an IPython instance inside your own Python pro-
413 It is possible to start an IPython instance inside your own Python pro-
414 grams. In the documentation example files there are some illustrations
414 grams. In the documentation example files there are some illustrations
415 on how to do this.
415 on how to do this.
416
416
417 This feature allows you to evalutate dynamically the state of your
417 This feature allows you to evalutate dynamically the state of your
418 code, operate with your variables, analyze them, etc. Note however
418 code, operate with your variables, analyze them, etc. Note however
419 that any changes you make to values while in the shell do NOT propagate
419 that any changes you make to values while in the shell do NOT propagate
420 back to the running code, so it is safe to modify your values because
420 back to the running code, so it is safe to modify your values because
421 you won't break your code in bizarre ways by doing so.
421 you won't break your code in bizarre ways by doing so.
422 """
422 """
423
423
424 cmd_line_usage = __doc__
424 cmd_line_usage = __doc__
425
425
426 #---------------------------------------------------------------------------
426 #---------------------------------------------------------------------------
427 interactive_usage = """
427 interactive_usage = """
428 IPython -- An enhanced Interactive Python
428 IPython -- An enhanced Interactive Python
429 =========================================
429 =========================================
430
430
431 IPython offers a combination of convenient shell features, special commands
431 IPython offers a combination of convenient shell features, special commands
432 and a history mechanism for both input (command history) and output (results
432 and a history mechanism for both input (command history) and output (results
433 caching, similar to Mathematica). It is intended to be a fully compatible
433 caching, similar to Mathematica). It is intended to be a fully compatible
434 replacement for the standard Python interpreter, while offering vastly
434 replacement for the standard Python interpreter, while offering vastly
435 improved functionality and flexibility.
435 improved functionality and flexibility.
436
436
437 At your system command line, type 'ipython -help' to see the command line
437 At your system command line, type 'ipython -help' to see the command line
438 options available. This document only describes interactive features.
438 options available. This document only describes interactive features.
439
439
440 Warning: IPython relies on the existence of a global variable called __IP which
440 Warning: IPython relies on the existence of a global variable called __IP which
441 controls the shell itself. If you redefine __IP to anything, bizarre behavior
441 controls the shell itself. If you redefine __IP to anything, bizarre behavior
442 will quickly occur.
442 will quickly occur.
443
443
444 MAIN FEATURES
444 MAIN FEATURES
445
445
446 * Access to the standard Python help. As of Python 2.1, a help system is
446 * Access to the standard Python help. As of Python 2.1, a help system is
447 available with access to object docstrings and the Python manuals. Simply
447 available with access to object docstrings and the Python manuals. Simply
448 type 'help' (no quotes) to access it.
448 type 'help' (no quotes) to access it.
449
449
450 * Magic commands: type %magic for information on the magic subsystem.
450 * Magic commands: type %magic for information on the magic subsystem.
451
451
452 * System command aliases, via the %alias command or the ipythonrc config file.
452 * System command aliases, via the %alias command or the ipythonrc config file.
453
453
454 * Dynamic object information:
454 * Dynamic object information:
455
455
456 Typing ?word or word? prints detailed information about an object. If
456 Typing ?word or word? prints detailed information about an object. If
457 certain strings in the object are too long (docstrings, code, etc.) they get
457 certain strings in the object are too long (docstrings, code, etc.) they get
458 snipped in the center for brevity.
458 snipped in the center for brevity.
459
459
460 Typing ??word or word?? gives access to the full information without
460 Typing ??word or word?? gives access to the full information without
461 snipping long strings. Long strings are sent to the screen through the less
461 snipping long strings. Long strings are sent to the screen through the less
462 pager if longer than the screen, printed otherwise.
462 pager if longer than the screen, printed otherwise.
463
463
464 The ?/?? system gives access to the full source code for any object (if
464 The ?/?? system gives access to the full source code for any object (if
465 available), shows function prototypes and other useful information.
465 available), shows function prototypes and other useful information.
466
466
467 If you just want to see an object's docstring, type '%pdoc object' (without
467 If you just want to see an object's docstring, type '%pdoc object' (without
468 quotes, and without % if you have automagic on).
468 quotes, and without % if you have automagic on).
469
469
470 Both %pdoc and ?/?? give you access to documentation even on things which are
470 Both %pdoc and ?/?? give you access to documentation even on things which are
471 not explicitely defined. Try for example typing {}.get? or after import os,
471 not explicitely defined. Try for example typing {}.get? or after import os,
472 type os.path.abspath??. The magic functions %pdef, %source and %file operate
472 type os.path.abspath??. The magic functions %pdef, %source and %file operate
473 similarly.
473 similarly.
474
474
475 * Completion in the local namespace, by typing TAB at the prompt.
475 * Completion in the local namespace, by typing TAB at the prompt.
476
476
477 At any time, hitting tab will complete any available python commands or
477 At any time, hitting tab will complete any available python commands or
478 variable names, and show you a list of the possible completions if there's
478 variable names, and show you a list of the possible completions if there's
479 no unambiguous one. It will also complete filenames in the current directory.
479 no unambiguous one. It will also complete filenames in the current directory.
480
480
481 This feature requires the readline and rlcomplete modules, so it won't work
481 This feature requires the readline and rlcomplete modules, so it won't work
482 if your Python lacks readline support (such as under Windows).
482 if your Python lacks readline support (such as under Windows).
483
483
484 * Search previous command history in two ways (also requires readline):
484 * Search previous command history in two ways (also requires readline):
485
485
486 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
486 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
487 search through only the history items that match what you've typed so
487 search through only the history items that match what you've typed so
488 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
488 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
489 normal arrow keys.
489 normal arrow keys.
490
490
491 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
491 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
492 your history for lines that match what you've typed so far, completing as
492 your history for lines that match what you've typed so far, completing as
493 much as it can.
493 much as it can.
494
494
495 * Persistent command history across sessions (readline required).
495 * Persistent command history across sessions (readline required).
496
496
497 * Logging of input with the ability to save and restore a working session.
497 * Logging of input with the ability to save and restore a working session.
498
498
499 * System escape with !. Typing !ls will run 'ls' in the current directory.
499 * System escape with !. Typing !ls will run 'ls' in the current directory.
500
500
501 * The reload command does a 'deep' reload of a module: changes made to the
501 * The reload command does a 'deep' reload of a module: changes made to the
502 module since you imported will actually be available without having to exit.
502 module since you imported will actually be available without having to exit.
503
503
504 * Verbose and colored exception traceback printouts. See the magic xmode and
504 * Verbose and colored exception traceback printouts. See the magic xmode and
505 xcolor functions for details (just type %magic).
505 xcolor functions for details (just type %magic).
506
506
507 * Input caching system:
507 * Input caching system:
508
508
509 IPython offers numbered prompts (In/Out) with input and output caching. All
509 IPython offers numbered prompts (In/Out) with input and output caching. All
510 input is saved and can be retrieved as variables (besides the usual arrow
510 input is saved and can be retrieved as variables (besides the usual arrow
511 key recall).
511 key recall).
512
512
513 The following GLOBAL variables always exist (so don't overwrite them!):
513 The following GLOBAL variables always exist (so don't overwrite them!):
514 _i: stores previous input.
514 _i: stores previous input.
515 _ii: next previous.
515 _ii: next previous.
516 _iii: next-next previous.
516 _iii: next-next previous.
517 _ih : a list of all input _ih[n] is the input from line n.
517 _ih : a list of all input _ih[n] is the input from line n.
518
518
519 Additionally, global variables named _i<n> are dynamically created (<n>
519 Additionally, global variables named _i<n> are dynamically created (<n>
520 being the prompt counter), such that _i<n> == _ih[<n>]
520 being the prompt counter), such that _i<n> == _ih[<n>]
521
521
522 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
522 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
523
523
524 You can create macros which contain multiple input lines from this history,
524 You can create macros which contain multiple input lines from this history,
525 for later re-execution, with the %macro function.
525 for later re-execution, with the %macro function.
526
526
527 The history function %hist allows you to see any part of your input history
527 The history function %hist allows you to see any part of your input history
528 by printing a range of the _i variables. Note that inputs which contain
528 by printing a range of the _i variables. Note that inputs which contain
529 magic functions (%) appear in the history with a prepended comment. This is
529 magic functions (%) appear in the history with a prepended comment. This is
530 because they aren't really valid Python code, so you can't exec them.
530 because they aren't really valid Python code, so you can't exec them.
531
531
532 * Output caching system:
532 * Output caching system:
533
533
534 For output that is returned from actions, a system similar to the input
534 For output that is returned from actions, a system similar to the input
535 cache exists but using _ instead of _i. Only actions that produce a result
535 cache exists but using _ instead of _i. Only actions that produce a result
536 (NOT assignments, for example) are cached. If you are familiar with
536 (NOT assignments, for example) are cached. If you are familiar with
537 Mathematica, IPython's _ variables behave exactly like Mathematica's %
537 Mathematica, IPython's _ variables behave exactly like Mathematica's %
538 variables.
538 variables.
539
539
540 The following GLOBAL variables always exist (so don't overwrite them!):
540 The following GLOBAL variables always exist (so don't overwrite them!):
541 _ (one underscore): previous output.
541 _ (one underscore): previous output.
542 __ (two underscores): next previous.
542 __ (two underscores): next previous.
543 ___ (three underscores): next-next previous.
543 ___ (three underscores): next-next previous.
544
544
545 Global variables named _<n> are dynamically created (<n> being the prompt
545 Global variables named _<n> are dynamically created (<n> being the prompt
546 counter), such that the result of output <n> is always available as _<n>.
546 counter), such that the result of output <n> is always available as _<n>.
547
547
548 Finally, a global dictionary named _oh exists with entries for all lines
548 Finally, a global dictionary named _oh exists with entries for all lines
549 which generated output.
549 which generated output.
550
550
551 * Directory history:
551 * Directory history:
552
552
553 Your history of visited directories is kept in the global list _dh, and the
553 Your history of visited directories is kept in the global list _dh, and the
554 magic %cd command can be used to go to any entry in that list.
554 magic %cd command can be used to go to any entry in that list.
555
555
556 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
556 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
557
557
558 1. Auto-parentheses
558 1. Auto-parentheses
559 Callable objects (i.e. functions, methods, etc) can be invoked like
559 Callable objects (i.e. functions, methods, etc) can be invoked like
560 this (notice the commas between the arguments):
560 this (notice the commas between the arguments):
561 >>> callable_ob arg1, arg2, arg3
561 >>> callable_ob arg1, arg2, arg3
562 and the input will be translated to this:
562 and the input will be translated to this:
563 --> callable_ob(arg1, arg2, arg3)
563 --> callable_ob(arg1, arg2, arg3)
564 You can force auto-parentheses by using '/' as the first character
564 You can force auto-parentheses by using '/' as the first character
565 of a line. For example:
565 of a line. For example:
566 >>> /globals # becomes 'globals()'
566 >>> /globals # becomes 'globals()'
567 Note that the '/' MUST be the first character on the line! This
567 Note that the '/' MUST be the first character on the line! This
568 won't work:
568 won't work:
569 >>> print /globals # syntax error
569 >>> print /globals # syntax error
570
570
571 In most cases the automatic algorithm should work, so you should
571 In most cases the automatic algorithm should work, so you should
572 rarely need to explicitly invoke /. One notable exception is if you
572 rarely need to explicitly invoke /. One notable exception is if you
573 are trying to call a function with a list of tuples as arguments (the
573 are trying to call a function with a list of tuples as arguments (the
574 parenthesis will confuse IPython):
574 parenthesis will confuse IPython):
575 In [1]: zip (1,2,3),(4,5,6) # won't work
575 In [1]: zip (1,2,3),(4,5,6) # won't work
576 but this will work:
576 but this will work:
577 In [2]: /zip (1,2,3),(4,5,6)
577 In [2]: /zip (1,2,3),(4,5,6)
578 ------> zip ((1,2,3),(4,5,6))
578 ------> zip ((1,2,3),(4,5,6))
579 Out[2]= [(1, 4), (2, 5), (3, 6)]
579 Out[2]= [(1, 4), (2, 5), (3, 6)]
580
580
581 IPython tells you that it has altered your command line by
581 IPython tells you that it has altered your command line by
582 displaying the new command line preceded by -->. e.g.:
582 displaying the new command line preceded by -->. e.g.:
583 In [18]: callable list
583 In [18]: callable list
584 -------> callable (list)
584 -------> callable (list)
585
585
586 2. Auto-Quoting
586 2. Auto-Quoting
587 You can force auto-quoting of a function's arguments by using ',' as
587 You can force auto-quoting of a function's arguments by using ',' as
588 the first character of a line. For example:
588 the first character of a line. For example:
589 >>> ,my_function /home/me # becomes my_function("/home/me")
589 >>> ,my_function /home/me # becomes my_function("/home/me")
590
590
591 If you use ';' instead, the whole argument is quoted as a single
591 If you use ';' instead, the whole argument is quoted as a single
592 string (while ',' splits on whitespace):
592 string (while ',' splits on whitespace):
593 >>> ,my_function a b c # becomes my_function("a","b","c")
593 >>> ,my_function a b c # becomes my_function("a","b","c")
594 >>> ;my_function a b c # becomes my_function("a b c")
594 >>> ;my_function a b c # becomes my_function("a b c")
595
595
596 Note that the ',' MUST be the first character on the line! This
596 Note that the ',' MUST be the first character on the line! This
597 won't work:
597 won't work:
598 >>> x = ,my_function /home/me # syntax error
598 >>> x = ,my_function /home/me # syntax error
599 """
599 """
600
600
601 quick_reference = r"""
601 quick_reference = r"""
602 IPython -- An enhanced Interactive Python - Quick Reference Card
602 IPython -- An enhanced Interactive Python - Quick Reference Card
603 ================================================================
603 ================================================================
604
604
605 obj?, obj??, ?obj,??obj : Get help, or more help for object
605 obj?, obj??, ?obj,??obj : Get help, or more help for object
606 ?os.p* : List names in os starting with p
606 ?os.p* : List names in os starting with p
607
607
608 Example magic:
608 Example magic:
609
609
610 %alias d ls -F : 'd' is now an alias for 'ls -F'
610 %alias d ls -F : 'd' is now an alias for 'ls -F'
611 alias d ls -F : Works if 'alias' not a python name
611 alias d ls -F : Works if 'alias' not a python name
612 alist = %alias : Get list of aliases to 'alist'
612 alist = %alias : Get list of aliases to 'alist'
613
613
614 System commands:
614 System commands:
615
615
616 !cp a.txt b/ : System command escape, calls os.system()
616 !cp a.txt b/ : System command escape, calls os.system()
617 cp a.txt b/ : after %rehashx, most system commands work without !
617 cp a.txt b/ : after %rehashx, most system commands work without !
618 cp ${f}.txt $bar : Variable expansion in magics and system commands
618 cp ${f}.txt $bar : Variable expansion in magics and system commands
619 files = !ls /usr : Capture sytem command output
619 files = !ls /usr : Capture sytem command output
620 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
620 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
621 cd /usr/share : Obvious, also 'cd d:\home\_ipython' works
621 cd /usr/share : Obvious, also 'cd d:\home\_ipython' works
622
622
623 History:
623 History:
624
624
625 _i, _ii, _iii : Previous, next previous, next next previous input
625 _i, _ii, _iii : Previous, next previous, next next previous input
626 _i4, _ih[2:5] : Input history line 4, lines 2-4
626 _i4, _ih[2:5] : Input history line 4, lines 2-4
627 exec _i81 : Execute input history line #81 again
627 exec _i81 : Execute input history line #81 again
628 _, __, ___ : previous, next previous, next next previous output
628 _, __, ___ : previous, next previous, next next previous output
629 _dh : Directory history
629 _dh : Directory history
630 _oh : Output history
630 _oh : Output history
631 %hist : Command history
631 %hist : Command history
632
632
633 Autocall:
633 Autocall:
634
634
635 f 1,2 : f(1,2)
635 f 1,2 : f(1,2)
636 /f 1,2 : f(1,2) (forced autoparen)
636 /f 1,2 : f(1,2) (forced autoparen)
637 ,f 1 2 : f("1","2")
637 ,f 1 2 : f("1","2")
638 ;f 1 2 : f("1 2")
638 ;f 1 2 : f("1 2")
639
639
640 """
640 """
641
641
642
642
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,406 +1,406 b''
1 .\" Hey, EMACS: -*- nroff -*-
1 .\" Hey, EMACS: -*- nroff -*-
2 .\" First parameter, NAME, should be all caps
2 .\" First parameter, NAME, should be all caps
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
4 .\" other parameters are allowed: see man(7), man(1)
4 .\" other parameters are allowed: see man(7), man(1)
5 .TH IPYTHON 1 "November 30, 2004"
5 .TH IPYTHON 1 "November 30, 2004"
6 .\" Please adjust this date whenever revising the manpage.
6 .\" Please adjust this date whenever revising the manpage.
7 .\"
7 .\"
8 .\" Some roff macros, for reference:
8 .\" Some roff macros, for reference:
9 .\" .nh disable hyphenation
9 .\" .nh disable hyphenation
10 .\" .hy enable hyphenation
10 .\" .hy enable hyphenation
11 .\" .ad l left justify
11 .\" .ad l left justify
12 .\" .ad b justify to both left and right margins
12 .\" .ad b justify to both left and right margins
13 .\" .nf disable filling
13 .\" .nf disable filling
14 .\" .fi enable filling
14 .\" .fi enable filling
15 .\" .br insert line break
15 .\" .br insert line break
16 .\" .sp <n> insert n+1 empty lines
16 .\" .sp <n> insert n+1 empty lines
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
18 .\" .SH section heading
18 .\" .SH section heading
19 .\" .SS secondary section heading
19 .\" .SS secondary section heading
20 .\"
20 .\"
21 .\"
21 .\"
22 .\" To preview this page as plain text: nroff -man ipython.1
22 .\" To preview this page as plain text: nroff -man ipython.1
23 .\"
23 .\"
24 .SH NAME
24 .SH NAME
25 ipython \- An Enhanced Interactive Python
25 ipython \- An Enhanced Interactive Python
26 .SH SYNOPSIS
26 .SH SYNOPSIS
27 .B ipython
27 .B ipython
28 .RI [ options ] " files" ...
28 .RI [ options ] " files" ...
29 .SH DESCRIPTION
29 .SH DESCRIPTION
30 An interactive Python shell with automatic history (input and output),
30 An interactive Python shell with automatic history (input and output),
31 dynamic object introspection, easier configuration, command
31 dynamic object introspection, easier configuration, command
32 completion, access to the system shell, integration with numerical and
32 completion, access to the system shell, integration with numerical and
33 scientific computing tools, and more.
33 scientific computing tools, and more.
34 .SH SPECIAL THREADING OPTIONS
34 .SH SPECIAL THREADING OPTIONS
35 The following special options are ONLY valid at the beginning of the command
35 The following special options are ONLY valid at the beginning of the command
36 line, and not later. This is because they control the initialization of
36 line, and not later. This is because they control the initialization of
37 ipython itself, before the normal option-handling mechanism is active.
37 ipython itself, before the normal option-handling mechanism is active.
38 .TP
38 .TP
39 .B \-gthread, \-qthread, \-wthread, \-pylab
39 .B \-gthread, \-qthread, \-q4thread, \-wthread, \-pylab
40 Only ONE of these can be given, and it can only be given as the first option
40 Only ONE of these can be given, and it can only be given as the first option
41 passed to IPython (it will have no effect in any other position). They
41 passed to IPython (it will have no effect in any other position). They provide
42 provide threading support for the GTK, QT and WXWidgets toolkits, and for the
42 threading support for the GTK, QT3, QT4 and WXWidgets toolkits, and for the
43 matplotlib library.
43 matplotlib library.
44 .br
44 .br
45 .sp 1
45 .sp 1
46 With any of the first three options, IPython starts running a separate thread
46 With any of the first four options, IPython starts running a separate thread
47 for the graphical toolkit's operation, so that you can open and control
47 for the graphical toolkit's operation, so that you can open and control
48 graphical elements from within an IPython command line, without blocking. All
48 graphical elements from within an IPython command line, without blocking. All
49 three provide essentially the same functionality, respectively for GTK, QT and
49 four provide essentially the same functionality, respectively for GTK, QT3, QT4
50 WXWidgets (via their Python interfaces).
50 and WXWidgets (via their Python interfaces).
51 .br
51 .br
52 .sp 1
52 .sp 1
53 Note that with \-wthread, you can additionally use the \-wxversion option to
53 Note that with \-wthread, you can additionally use the \-wxversion option to
54 request a specific version of wx to be used. This requires that you have the
54 request a specific version of wx to be used. This requires that you have the
55 'wxversion' Python module installed, which is part of recent wxPython
55 'wxversion' Python module installed, which is part of recent wxPython
56 distributions.
56 distributions.
57 .br
57 .br
58 .sp 1
58 .sp 1
59 If \-pylab is given, IPython loads special support for the matplotlib library
59 If \-pylab is given, IPython loads special support for the matplotlib library
60 (http://matplotlib.sourceforge.net), allowing interactive usage of any of its
60 (http://matplotlib.sourceforge.net), allowing interactive usage of any of its
61 backends as defined in the user's .matplotlibrc file. It automatically
61 backends as defined in the user's .matplotlibrc file. It automatically
62 activates GTK, QT or WX threading for IPyhton if the choice of matplotlib
62 activates GTK, QT or WX threading for IPyhton if the choice of matplotlib
63 backend requires it. It also modifies the %run command to correctly execute
63 backend requires it. It also modifies the %run command to correctly execute
64 (without blocking) any matplotlib-based script which calls show() at the end.
64 (without blocking) any matplotlib-based script which calls show() at the end.
65 .TP
65 .TP
66 .B \-tk
66 .B \-tk
67 The \-g/q/wthread options, and \-pylab (if matplotlib is configured to use
67 The \-g/q/q4/wthread options, and \-pylab (if matplotlib is configured to use
68 GTK, QT or WX), will normally block Tk graphical interfaces. This means that
68 GTK, QT or WX), will normally block Tk graphical interfaces. This means that
69 when GTK, QT or WX threading is active, any attempt to open a Tk GUI will
69 when GTK, QT or WX threading is active, any attempt to open a Tk GUI will
70 result in a dead window, and possibly cause the Python interpreter to crash.
70 result in a dead window, and possibly cause the Python interpreter to crash.
71 An extra option, \-tk, is available to address this issue. It can ONLY be
71 An extra option, \-tk, is available to address this issue. It can ONLY be
72 given as a SECOND option after any of the above (\-gthread, \-qthread,
72 given as a SECOND option after any of the above (\-gthread, \-qthread,
73 \-wthread or \-pylab).
73 \-wthread or \-pylab).
74 .br
74 .br
75 .sp 1
75 .sp 1
76 If \-tk is given, IPython will try to coordinate Tk threading with GTK, QT or
76 If \-tk is given, IPython will try to coordinate Tk threading with GTK, QT or
77 WX. This is however potentially unreliable, and you will have to test on your
77 WX. This is however potentially unreliable, and you will have to test on your
78 platform and Python configuration to determine whether it works for you.
78 platform and Python configuration to determine whether it works for you.
79 Debian users have reported success, apparently due to the fact that Debian
79 Debian users have reported success, apparently due to the fact that Debian
80 builds all of Tcl, Tk, Tkinter and Python with pthreads support. Under other
80 builds all of Tcl, Tk, Tkinter and Python with pthreads support. Under other
81 Linux environments (such as Fedora Core 2), this option has caused random
81 Linux environments (such as Fedora Core 2), this option has caused random
82 crashes and lockups of the Python interpreter. Under other operating systems
82 crashes and lockups of the Python interpreter. Under other operating systems
83 (Mac OSX and Windows), you'll need to try it to find out, since currently no
83 (Mac OSX and Windows), you'll need to try it to find out, since currently no
84 user reports are available.
84 user reports are available.
85 .br
85 .br
86 .sp 1
86 .sp 1
87 There is unfortunately no way for IPython to determine at runtime whether \-tk
87 There is unfortunately no way for IPython to determine at runtime whether \-tk
88 will work reliably or not, so you will need to do some experiments before
88 will work reliably or not, so you will need to do some experiments before
89 relying on it for regular work.
89 relying on it for regular work.
90 .
90 .
91 .SS A WARNING ABOUT SIGNALS AND THREADS
91 .SS A WARNING ABOUT SIGNALS AND THREADS
92 When any of the thread systems (GTK, QT or WX) are active, either directly or
92 When any of the thread systems (GTK, QT or WX) are active, either directly or
93 via \-pylab with a threaded backend, it is impossible to interrupt
93 via \-pylab with a threaded backend, it is impossible to interrupt
94 long-running Python code via Ctrl\-C. IPython can not pass the
94 long-running Python code via Ctrl\-C. IPython can not pass the
95 KeyboardInterrupt exception (or the underlying SIGINT) across threads, so any
95 KeyboardInterrupt exception (or the underlying SIGINT) across threads, so any
96 long-running process started from IPython will run to completion, or will have
96 long-running process started from IPython will run to completion, or will have
97 to be killed via an external (OS-based) mechanism.
97 to be killed via an external (OS-based) mechanism.
98 .br
98 .br
99 .sp 1
99 .sp 1
100 To the best of my knowledge, this limitation is imposed by the Python
100 To the best of my knowledge, this limitation is imposed by the Python
101 interpreter itself, and it comes from the difficulty of writing portable
101 interpreter itself, and it comes from the difficulty of writing portable
102 signal/threaded code. If any user is an expert on this topic and can suggest
102 signal/threaded code. If any user is an expert on this topic and can suggest
103 a better solution, I would love to hear about it. In the IPython sources,
103 a better solution, I would love to hear about it. In the IPython sources,
104 look at the Shell.py module, and in particular at the runcode() method.
104 look at the Shell.py module, and in particular at the runcode() method.
105 .
105 .
106 .SH REGULAR OPTIONS
106 .SH REGULAR OPTIONS
107 After the above threading options have been given, regular options can follow
107 After the above threading options have been given, regular options can follow
108 in any order. All options can be abbreviated to their shortest non-ambiguous
108 in any order. All options can be abbreviated to their shortest non-ambiguous
109 form and are case-sensitive. One or two dashes can be used. Some options
109 form and are case-sensitive. One or two dashes can be used. Some options
110 have an alternate short form, indicated after a |.
110 have an alternate short form, indicated after a |.
111 .br
111 .br
112 .sp 1
112 .sp 1
113 Most options can also be set from your ipythonrc configuration file.
113 Most options can also be set from your ipythonrc configuration file.
114 See the provided examples for assistance. Options given on the
114 See the provided examples for assistance. Options given on the
115 commandline override the values set in the ipythonrc file.
115 commandline override the values set in the ipythonrc file.
116 .br
116 .br
117 .sp 1
117 .sp 1
118 All options with a [no] prepended can be specified in negated form
118 All options with a [no] prepended can be specified in negated form
119 (\-nooption instead of \-option) to turn the feature off.
119 (\-nooption instead of \-option) to turn the feature off.
120 .TP
120 .TP
121 .B \-h, \-\-help
121 .B \-h, \-\-help
122 Show summary of options.
122 Show summary of options.
123 .TP
123 .TP
124 .B \-autocall <val>
124 .B \-autocall <val>
125 Make IPython automatically call any callable object even if you didn't type
125 Make IPython automatically call any callable object even if you didn't type
126 explicit parentheses. For example, 'str 43' becomes
126 explicit parentheses. For example, 'str 43' becomes
127 'str(43)' automatically. The value can be '0' to disable the
127 'str(43)' automatically. The value can be '0' to disable the
128 feature, '1' for 'smart' autocall, where it is not applied if
128 feature, '1' for 'smart' autocall, where it is not applied if
129 there are no more arguments on the line, and '2' for 'full'
129 there are no more arguments on the line, and '2' for 'full'
130 autocall, where all callable objects are automatically called
130 autocall, where all callable objects are automatically called
131 (even if no arguments are present). The default is '1'.
131 (even if no arguments are present). The default is '1'.
132 .TP
132 .TP
133 .B \-[no]autoindent
133 .B \-[no]autoindent
134 Turn automatic indentation on/off.
134 Turn automatic indentation on/off.
135 .TP
135 .TP
136 .B \-[no]automagic
136 .B \-[no]automagic
137 Make magic commands automatic (without needing their first character
137 Make magic commands automatic (without needing their first character
138 to be %). Type %magic at the IPython prompt for more information.
138 to be %). Type %magic at the IPython prompt for more information.
139 .TP
139 .TP
140 .B \-[no]autoedit_syntax
140 .B \-[no]autoedit_syntax
141 When a syntax error occurs after editing a file, automatically open the file
141 When a syntax error occurs after editing a file, automatically open the file
142 to the trouble causing line for convenient fixing.
142 to the trouble causing line for convenient fixing.
143 .TP
143 .TP
144 .B \-[no]banner
144 .B \-[no]banner
145 Print the intial information banner (default on).
145 Print the intial information banner (default on).
146 .TP
146 .TP
147 .B \-c <command>
147 .B \-c <command>
148 Execute the given command string, and set sys.argv to ['c']. This is similar
148 Execute the given command string, and set sys.argv to ['c']. This is similar
149 to the \-c option in the normal Python interpreter.
149 to the \-c option in the normal Python interpreter.
150 .TP
150 .TP
151 .B \-cache_size|cs <n>
151 .B \-cache_size|cs <n>
152 Size of the output cache (maximum number of entries to hold in
152 Size of the output cache (maximum number of entries to hold in
153 memory). The default is 1000, you can change it permanently in your
153 memory). The default is 1000, you can change it permanently in your
154 config file. Setting it to 0 completely disables the caching system,
154 config file. Setting it to 0 completely disables the caching system,
155 and the minimum value accepted is 20 (if you provide a value less than
155 and the minimum value accepted is 20 (if you provide a value less than
156 20, it is reset to 0 and a warning is issued). This limit is defined
156 20, it is reset to 0 and a warning is issued). This limit is defined
157 because otherwise you'll spend more time re-flushing a too small cache
157 because otherwise you'll spend more time re-flushing a too small cache
158 than working.
158 than working.
159 .TP
159 .TP
160 .B \-classic|cl
160 .B \-classic|cl
161 Gives IPython a similar feel to the classic Python prompt.
161 Gives IPython a similar feel to the classic Python prompt.
162 .TP
162 .TP
163 .B \-colors <scheme>
163 .B \-colors <scheme>
164 Color scheme for prompts and exception reporting. Currently
164 Color scheme for prompts and exception reporting. Currently
165 implemented: NoColor, Linux, and LightBG.
165 implemented: NoColor, Linux, and LightBG.
166 .TP
166 .TP
167 .B \-[no]color_info
167 .B \-[no]color_info
168 IPython can display information about objects via a set of functions,
168 IPython can display information about objects via a set of functions,
169 and optionally can use colors for this, syntax highlighting source
169 and optionally can use colors for this, syntax highlighting source
170 code and various other elements. However, because this information is
170 code and various other elements. However, because this information is
171 passed through a pager (like 'less') and many pagers get confused with
171 passed through a pager (like 'less') and many pagers get confused with
172 color codes, this option is off by default. You can test it and turn
172 color codes, this option is off by default. You can test it and turn
173 it on permanently in your ipythonrc file if it works for you. As a
173 it on permanently in your ipythonrc file if it works for you. As a
174 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
174 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
175 that in RedHat 7.2 doesn't.
175 that in RedHat 7.2 doesn't.
176 .br
176 .br
177 .sp 1
177 .sp 1
178 Test it and turn it on permanently if it works with your system. The
178 Test it and turn it on permanently if it works with your system. The
179 magic function @color_info allows you to toggle this interactively for
179 magic function @color_info allows you to toggle this interactively for
180 testing.
180 testing.
181 .TP
181 .TP
182 .B \-[no]confirm_exit
182 .B \-[no]confirm_exit
183 Set to confirm when you try to exit IPython with an EOF (Control-D in
183 Set to confirm when you try to exit IPython with an EOF (Control-D in
184 Unix, Control-Z/Enter in Windows). Note that using the magic functions
184 Unix, Control-Z/Enter in Windows). Note that using the magic functions
185 @Exit or @Quit you can force a direct exit, bypassing any
185 @Exit or @Quit you can force a direct exit, bypassing any
186 confirmation.
186 confirmation.
187 .TP
187 .TP
188 .B \-[no]debug
188 .B \-[no]debug
189 Show information about the loading process. Very useful to pin down
189 Show information about the loading process. Very useful to pin down
190 problems with your configuration files or to get details about session
190 problems with your configuration files or to get details about session
191 restores.
191 restores.
192 .TP
192 .TP
193 .B \-[no]deep_reload
193 .B \-[no]deep_reload
194 IPython can use the deep_reload module which reloads changes in
194 IPython can use the deep_reload module which reloads changes in
195 modules recursively (it replaces the reload() function, so you don't
195 modules recursively (it replaces the reload() function, so you don't
196 need to change anything to use it). deep_reload() forces a full reload
196 need to change anything to use it). deep_reload() forces a full reload
197 of modules whose code may have changed, which the default reload()
197 of modules whose code may have changed, which the default reload()
198 function does not.
198 function does not.
199 .br
199 .br
200 .sp 1
200 .sp 1
201 When deep_reload is off, IPython will use the normal reload(), but
201 When deep_reload is off, IPython will use the normal reload(), but
202 deep_reload will still be available as dreload(). This feature is off
202 deep_reload will still be available as dreload(). This feature is off
203 by default [which means that you have both normal reload() and
203 by default [which means that you have both normal reload() and
204 dreload()].
204 dreload()].
205 .TP
205 .TP
206 .B \-editor <name>
206 .B \-editor <name>
207 Which editor to use with the @edit command. By default, IPython will
207 Which editor to use with the @edit command. By default, IPython will
208 honor your EDITOR environment variable (if not set, vi is the Unix
208 honor your EDITOR environment variable (if not set, vi is the Unix
209 default and notepad the Windows one). Since this editor is invoked on
209 default and notepad the Windows one). Since this editor is invoked on
210 the fly by IPython and is meant for editing small code snippets, you
210 the fly by IPython and is meant for editing small code snippets, you
211 may want to use a small, lightweight editor here (in case your default
211 may want to use a small, lightweight editor here (in case your default
212 EDITOR is something like Emacs).
212 EDITOR is something like Emacs).
213 .TP
213 .TP
214 .B \-ipythondir <name>
214 .B \-ipythondir <name>
215 The name of your IPython configuration directory IPYTHONDIR. This can
215 The name of your IPython configuration directory IPYTHONDIR. This can
216 also be specified through the environment variable IPYTHONDIR.
216 also be specified through the environment variable IPYTHONDIR.
217 .TP
217 .TP
218 .B \-log|l
218 .B \-log|l
219 Generate a log file of all input. The file is named ipython_log.py in your
219 Generate a log file of all input. The file is named ipython_log.py in your
220 current directory (which prevents logs from multiple IPython sessions from
220 current directory (which prevents logs from multiple IPython sessions from
221 trampling each other). You can use this to later restore a session by loading
221 trampling each other). You can use this to later restore a session by loading
222 your logfile as a file to be executed with option -logplay (see below).
222 your logfile as a file to be executed with option -logplay (see below).
223 .TP
223 .TP
224 .B \-logfile|lf
224 .B \-logfile|lf
225 Specify the name of your logfile.
225 Specify the name of your logfile.
226 .TP
226 .TP
227 .B \-logplay|lp
227 .B \-logplay|lp
228 Replay a previous log. For restoring a session as close as possible to
228 Replay a previous log. For restoring a session as close as possible to
229 the state you left it in, use this option (don't just run the
229 the state you left it in, use this option (don't just run the
230 logfile). With \-logplay, IPython will try to reconstruct the previous
230 logfile). With \-logplay, IPython will try to reconstruct the previous
231 working environment in full, not just execute the commands in the
231 working environment in full, not just execute the commands in the
232 logfile.
232 logfile.
233 .br
233 .br
234 .sh 1
234 .sh 1
235 When a session is restored, logging is automatically turned on again
235 When a session is restored, logging is automatically turned on again
236 with the name of the logfile it was invoked with (it is read from the
236 with the name of the logfile it was invoked with (it is read from the
237 log header). So once you've turned logging on for a session, you can
237 log header). So once you've turned logging on for a session, you can
238 quit IPython and reload it as many times as you want and it will
238 quit IPython and reload it as many times as you want and it will
239 continue to log its history and restore from the beginning every time.
239 continue to log its history and restore from the beginning every time.
240 .br
240 .br
241 .sp 1
241 .sp 1
242 Caveats: there are limitations in this option. The history variables
242 Caveats: there are limitations in this option. The history variables
243 _i*,_* and _dh don't get restored properly. In the future we will try
243 _i*,_* and _dh don't get restored properly. In the future we will try
244 to implement full session saving by writing and retrieving a
244 to implement full session saving by writing and retrieving a
245 'snapshot' of the memory state of IPython. But our first attempts
245 'snapshot' of the memory state of IPython. But our first attempts
246 failed because of inherent limitations of Python's Pickle module, so
246 failed because of inherent limitations of Python's Pickle module, so
247 this may have to wait.
247 this may have to wait.
248 .TP
248 .TP
249 .B \-[no]messages
249 .B \-[no]messages
250 Print messages which IPython collects about its startup process
250 Print messages which IPython collects about its startup process
251 (default on).
251 (default on).
252 .TP
252 .TP
253 .B \-[no]pdb
253 .B \-[no]pdb
254 Automatically call the pdb debugger after every uncaught exception. If
254 Automatically call the pdb debugger after every uncaught exception. If
255 you are used to debugging using pdb, this puts you automatically
255 you are used to debugging using pdb, this puts you automatically
256 inside of it after any call (either in IPython or in code called by
256 inside of it after any call (either in IPython or in code called by
257 it) which triggers an exception which goes uncaught.
257 it) which triggers an exception which goes uncaught.
258 .TP
258 .TP
259 .B \-[no]pprint
259 .B \-[no]pprint
260 IPython can optionally use the pprint (pretty printer) module for
260 IPython can optionally use the pprint (pretty printer) module for
261 displaying results. pprint tends to give a nicer display of nested
261 displaying results. pprint tends to give a nicer display of nested
262 data structures. If you like it, you can turn it on permanently in
262 data structures. If you like it, you can turn it on permanently in
263 your config file (default off).
263 your config file (default off).
264 .TP
264 .TP
265 .B \-profile|p <name>
265 .B \-profile|p <name>
266 Assume that your config file is ipythonrc-<name> (looks in current dir
266 Assume that your config file is ipythonrc-<name> (looks in current dir
267 first, then in IPYTHONDIR). This is a quick way to keep and load
267 first, then in IPYTHONDIR). This is a quick way to keep and load
268 multiple config files for different tasks, especially if you use the
268 multiple config files for different tasks, especially if you use the
269 include option of config files. You can keep a basic
269 include option of config files. You can keep a basic
270 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
270 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
271 this one and load extra things for particular tasks. For example:
271 this one and load extra things for particular tasks. For example:
272 .br
272 .br
273 .sp 1
273 .sp 1
274 1) $HOME/.ipython/ipythonrc : load basic things you always want.
274 1) $HOME/.ipython/ipythonrc : load basic things you always want.
275 .br
275 .br
276 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
276 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
277 modules.
277 modules.
278 .br
278 .br
279 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
279 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
280 plotting modules.
280 plotting modules.
281 .br
281 .br
282 .sp 1
282 .sp 1
283 Since it is possible to create an endless loop by having circular file
283 Since it is possible to create an endless loop by having circular file
284 inclusions, IPython will stop if it reaches 15 recursive inclusions.
284 inclusions, IPython will stop if it reaches 15 recursive inclusions.
285 .TP
285 .TP
286 .B \-prompt_in1|pi1 <string>
286 .B \-prompt_in1|pi1 <string>
287 Specify the string used for input prompts. Note that if you are using
287 Specify the string used for input prompts. Note that if you are using
288 numbered prompts, the number is represented with a '\\#' in the
288 numbered prompts, the number is represented with a '\\#' in the
289 string. Don't forget to quote strings with spaces embedded in
289 string. Don't forget to quote strings with spaces embedded in
290 them. Default: 'In [\\#]: '.
290 them. Default: 'In [\\#]: '.
291 .br
291 .br
292 .sp 1
292 .sp 1
293 Most bash-like escapes can be used to customize IPython's prompts, as well as
293 Most bash-like escapes can be used to customize IPython's prompts, as well as
294 a few additional ones which are IPython-specific. All valid prompt escapes
294 a few additional ones which are IPython-specific. All valid prompt escapes
295 are described in detail in the Customization section of the IPython HTML/PDF
295 are described in detail in the Customization section of the IPython HTML/PDF
296 manual.
296 manual.
297 .TP
297 .TP
298 .B \-prompt_in2|pi2 <string>
298 .B \-prompt_in2|pi2 <string>
299 Similar to the previous option, but used for the continuation prompts. The
299 Similar to the previous option, but used for the continuation prompts. The
300 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
300 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
301 (so you can have your continuation prompt aligned with your input
301 (so you can have your continuation prompt aligned with your input
302 prompt). Default: ' .\\D.: ' (note three spaces at the start for alignment
302 prompt). Default: ' .\\D.: ' (note three spaces at the start for alignment
303 with 'In [\\#]').
303 with 'In [\\#]').
304 .TP
304 .TP
305 .B \-prompt_out|po <string>
305 .B \-prompt_out|po <string>
306 String used for output prompts, also uses numbers like prompt_in1.
306 String used for output prompts, also uses numbers like prompt_in1.
307 Default: 'Out[\\#]:'.
307 Default: 'Out[\\#]:'.
308 .TP
308 .TP
309 .B \-quick
309 .B \-quick
310 Start in bare bones mode (no config file loaded).
310 Start in bare bones mode (no config file loaded).
311 .TP
311 .TP
312 .B \-rcfile <name>
312 .B \-rcfile <name>
313 Name of your IPython resource configuration file. normally IPython
313 Name of your IPython resource configuration file. normally IPython
314 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
314 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
315 the loading of your config file fails, IPython starts with a bare
315 the loading of your config file fails, IPython starts with a bare
316 bones configuration (no modules loaded at all).
316 bones configuration (no modules loaded at all).
317 .TP
317 .TP
318 .B \-[no]readline
318 .B \-[no]readline
319 Use the readline library, which is needed to support name completion
319 Use the readline library, which is needed to support name completion
320 and command history, among other things. It is enabled by default, but
320 and command history, among other things. It is enabled by default, but
321 may cause problems for users of X/Emacs in Python comint or shell
321 may cause problems for users of X/Emacs in Python comint or shell
322 buffers.
322 buffers.
323 .br
323 .br
324 .sp 1
324 .sp 1
325 Note that emacs 'eterm' buffers (opened with M-x term) support
325 Note that emacs 'eterm' buffers (opened with M-x term) support
326 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
326 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
327 and C-c !) buffers do not.
327 and C-c !) buffers do not.
328 .TP
328 .TP
329 .B \-screen_length|sl <n>
329 .B \-screen_length|sl <n>
330 Number of lines of your screen. This is used to control printing of
330 Number of lines of your screen. This is used to control printing of
331 very long strings. Strings longer than this number of lines will be
331 very long strings. Strings longer than this number of lines will be
332 sent through a pager instead of directly printed.
332 sent through a pager instead of directly printed.
333 .br
333 .br
334 .sp 1
334 .sp 1
335 The default value for this is 0, which means IPython will auto-detect
335 The default value for this is 0, which means IPython will auto-detect
336 your screen size every time it needs to print certain potentially long
336 your screen size every time it needs to print certain potentially long
337 strings (this doesn't change the behavior of the 'print' keyword, it's
337 strings (this doesn't change the behavior of the 'print' keyword, it's
338 only triggered internally). If for some reason this isn't working well
338 only triggered internally). If for some reason this isn't working well
339 (it needs curses support), specify it yourself. Otherwise don't change
339 (it needs curses support), specify it yourself. Otherwise don't change
340 the default.
340 the default.
341 .TP
341 .TP
342 .B \-separate_in|si <string>
342 .B \-separate_in|si <string>
343 Separator before input prompts. Default '\n'.
343 Separator before input prompts. Default '\n'.
344 .TP
344 .TP
345 .B \-separate_out|so <string>
345 .B \-separate_out|so <string>
346 Separator before output prompts. Default: 0 (nothing).
346 Separator before output prompts. Default: 0 (nothing).
347 .TP
347 .TP
348 .B \-separate_out2|so2 <string>
348 .B \-separate_out2|so2 <string>
349 Separator after output prompts. Default: 0 (nothing).
349 Separator after output prompts. Default: 0 (nothing).
350 .TP
350 .TP
351 .B \-nosep
351 .B \-nosep
352 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
352 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
353 Simply removes all input/output separators.
353 Simply removes all input/output separators.
354 .TP
354 .TP
355 .B \-upgrade
355 .B \-upgrade
356 Allows you to upgrade your IPYTHONDIR configuration when you install a
356 Allows you to upgrade your IPYTHONDIR configuration when you install a
357 new version of IPython. Since new versions may include new command
357 new version of IPython. Since new versions may include new command
358 lines options or example files, this copies updated ipythonrc-type
358 lines options or example files, this copies updated ipythonrc-type
359 files. However, it backs up (with a .old extension) all files which
359 files. However, it backs up (with a .old extension) all files which
360 it overwrites so that you can merge back any custimizations you might
360 it overwrites so that you can merge back any custimizations you might
361 have in your personal files.
361 have in your personal files.
362 .TP
362 .TP
363 .B \-Version
363 .B \-Version
364 Print version information and exit.
364 Print version information and exit.
365 .TP
365 .TP
366 .B -wxversion <string>
366 .B -wxversion <string>
367 Select a specific version of wxPython (used in conjunction with
367 Select a specific version of wxPython (used in conjunction with
368 \-wthread). Requires the wxversion module, part of recent wxPython
368 \-wthread). Requires the wxversion module, part of recent wxPython
369 distributions.
369 distributions.
370 .TP
370 .TP
371 .B \-xmode <modename>
371 .B \-xmode <modename>
372 Mode for exception reporting. The valid modes are Plain, Context, and
372 Mode for exception reporting. The valid modes are Plain, Context, and
373 Verbose.
373 Verbose.
374 .br
374 .br
375 .sp 1
375 .sp 1
376 \- Plain: similar to python's normal traceback printing.
376 \- Plain: similar to python's normal traceback printing.
377 .br
377 .br
378 .sp 1
378 .sp 1
379 \- Context: prints 5 lines of context source code around each line in the
379 \- Context: prints 5 lines of context source code around each line in the
380 traceback.
380 traceback.
381 .br
381 .br
382 .sp 1
382 .sp 1
383 \- Verbose: similar to Context, but additionally prints the variables
383 \- Verbose: similar to Context, but additionally prints the variables
384 currently visible where the exception happened (shortening their strings if
384 currently visible where the exception happened (shortening their strings if
385 too long). This can potentially be very slow, if you happen to have a huge
385 too long). This can potentially be very slow, if you happen to have a huge
386 data structure whose string representation is complex to compute. Your
386 data structure whose string representation is complex to compute. Your
387 computer may appear to freeze for a while with cpu usage at 100%. If this
387 computer may appear to freeze for a while with cpu usage at 100%. If this
388 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
388 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
389 once).
389 once).
390 .
390 .
391 .SH EMBEDDING
391 .SH EMBEDDING
392 It is possible to start an IPython instance inside your own Python
392 It is possible to start an IPython instance inside your own Python
393 programs. In the documentation example files there are some
393 programs. In the documentation example files there are some
394 illustrations on how to do this.
394 illustrations on how to do this.
395 .br
395 .br
396 .sp 1
396 .sp 1
397 This feature allows you to evalutate dynamically the state of your
397 This feature allows you to evalutate dynamically the state of your
398 code, operate with your variables, analyze them, etc. Note however
398 code, operate with your variables, analyze them, etc. Note however
399 that any changes you make to values while in the shell do NOT
399 that any changes you make to values while in the shell do NOT
400 propagate back to the running code, so it is safe to modify your
400 propagate back to the running code, so it is safe to modify your
401 values because you won't break your code in bizarre ways by doing so.
401 values because you won't break your code in bizarre ways by doing so.
402 .SH AUTHOR
402 .SH AUTHOR
403 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
403 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
404 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
404 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
405 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
405 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
406 <jack@xiph.org>, for the Debian project (but may be used by others).
406 <jack@xiph.org>, for the Debian project (but may be used by others).
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now