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