Show More
@@ -0,0 +1,1 b'' | |||||
|
1 | doc/ChangeLog No newline at end of file |
@@ -1,546 +1,550 b'' | |||||
1 | # -*- Mode: Shell-Script -*- Not really, but shows comments correctly |
|
1 | # -*- Mode: Shell-Script -*- Not really, but shows comments correctly | |
2 |
# $Id: ipythonrc |
|
2 | # $Id: ipythonrc 633 2005-07-17 01:03:15Z tzanko $ | |
3 |
|
3 | |||
4 | #*************************************************************************** |
|
4 | #*************************************************************************** | |
5 | # |
|
5 | # | |
6 | # Configuration file for IPython -- ipythonrc format |
|
6 | # Configuration file for IPython -- ipythonrc format | |
7 | # |
|
7 | # | |
8 | # The format of this file is simply one of 'key value' lines. |
|
8 | # The format of this file is simply one of 'key value' lines. | |
9 | # Lines containing only whitespace at the beginning and then a # are ignored |
|
9 | # Lines containing only whitespace at the beginning and then a # are ignored | |
10 | # as comments. But comments can NOT be put on lines with data. |
|
10 | # as comments. But comments can NOT be put on lines with data. | |
11 |
|
11 | |||
12 | # The meaning and use of each key are explained below. |
|
12 | # The meaning and use of each key are explained below. | |
13 |
|
13 | |||
14 | #--------------------------------------------------------------------------- |
|
14 | #--------------------------------------------------------------------------- | |
15 | # Section: included files |
|
15 | # Section: included files | |
16 |
|
16 | |||
17 | # Put one or more *config* files (with the syntax of this file) you want to |
|
17 | # Put one or more *config* files (with the syntax of this file) you want to | |
18 | # include. For keys with a unique value the outermost file has precedence. For |
|
18 | # include. For keys with a unique value the outermost file has precedence. For | |
19 | # keys with multiple values, they all get assembled into a list which then |
|
19 | # keys with multiple values, they all get assembled into a list which then | |
20 | # gets loaded by IPython. |
|
20 | # gets loaded by IPython. | |
21 |
|
21 | |||
22 | # In this file, all lists of things should simply be space-separated. |
|
22 | # In this file, all lists of things should simply be space-separated. | |
23 |
|
23 | |||
24 | # This allows you to build hierarchies of files which recursively load |
|
24 | # This allows you to build hierarchies of files which recursively load | |
25 | # lower-level services. If this is your main ~/.ipython/ipythonrc file, you |
|
25 | # lower-level services. If this is your main ~/.ipython/ipythonrc file, you | |
26 | # should only keep here basic things you always want available. Then you can |
|
26 | # should only keep here basic things you always want available. Then you can | |
27 | # include it in every other special-purpose config file you create. |
|
27 | # include it in every other special-purpose config file you create. | |
28 | include |
|
28 | include | |
29 |
|
29 | |||
30 | #--------------------------------------------------------------------------- |
|
30 | #--------------------------------------------------------------------------- | |
31 | # Section: startup setup |
|
31 | # Section: startup setup | |
32 |
|
32 | |||
33 | # These are mostly things which parallel a command line option of the same |
|
33 | # These are mostly things which parallel a command line option of the same | |
34 | # name. |
|
34 | # name. | |
35 |
|
35 | |||
36 | # Keys in this section should only appear once. If any key from this section |
|
36 | # Keys in this section should only appear once. If any key from this section | |
37 | # is encountered more than once, the last value remains, all earlier ones get |
|
37 | # is encountered more than once, the last value remains, all earlier ones get | |
38 | # discarded. |
|
38 | # discarded. | |
39 |
|
39 | |||
40 | # Automatic calling of callable objects. If set to true, callable objects are |
|
40 | # Automatic calling of callable objects. If set to true, callable objects are | |
41 | # automatically called when invoked at the command line, even if you don't |
|
41 | # automatically called when invoked at the command line, even if you don't | |
42 | # type parentheses. IPython adds the parentheses for you. For example: |
|
42 | # type parentheses. IPython adds the parentheses for you. For example: | |
43 |
|
43 | |||
44 | #In [1]: str 45 |
|
44 | #In [1]: str 45 | |
45 | #------> str(45) |
|
45 | #------> str(45) | |
46 | #Out[1]: '45' |
|
46 | #Out[1]: '45' | |
47 |
|
47 | |||
48 | # IPython reprints your line with '---->' indicating that it added |
|
48 | # IPython reprints your line with '---->' indicating that it added | |
49 | # parentheses. While this option is very convenient for interactive use, it |
|
49 | # parentheses. While this option is very convenient for interactive use, it | |
50 | # may occasionally cause problems with objects which have side-effects if |
|
50 | # may occasionally cause problems with objects which have side-effects if | |
51 | # called unexpectedly. Set it to 0 if you want to disable it. |
|
51 | # called unexpectedly. Set it to 0 if you want to disable it. | |
52 |
|
52 | |||
53 | # Note that even with autocall off, you can still use '/' at the start of a |
|
53 | # Note that even with autocall off, you can still use '/' at the start of a | |
54 | # line to treat the first argument on the command line as a function and add |
|
54 | # line to treat the first argument on the command line as a function and add | |
55 | # parentheses to it: |
|
55 | # parentheses to it: | |
56 |
|
56 | |||
57 | #In [8]: /str 43 |
|
57 | #In [8]: /str 43 | |
58 | #------> str(43) |
|
58 | #------> str(43) | |
59 | #Out[8]: '43' |
|
59 | #Out[8]: '43' | |
60 |
|
60 | |||
61 | autocall 1 |
|
61 | autocall 1 | |
62 |
|
62 | |||
63 | # Auto-indent. IPython can recognize lines ending in ':' and indent the next |
|
63 | # Auto-indent. IPython can recognize lines ending in ':' and indent the next | |
64 | # line, while also un-indenting automatically after 'raise' or 'return'. |
|
64 | # line, while also un-indenting automatically after 'raise' or 'return'. | |
65 |
|
65 | |||
66 | # This feature uses the readline library, so it will honor your ~/.inputrc |
|
66 | # This feature uses the readline library, so it will honor your ~/.inputrc | |
67 | # configuration (or whatever file your INPUTRC variable points to). Adding |
|
67 | # configuration (or whatever file your INPUTRC variable points to). Adding | |
68 | # the following lines to your .inputrc file can make indent/unindenting more |
|
68 | # the following lines to your .inputrc file can make indent/unindenting more | |
69 | # convenient (M-i indents, M-u unindents): |
|
69 | # convenient (M-i indents, M-u unindents): | |
70 |
|
70 | |||
71 | # $if Python |
|
71 | # $if Python | |
72 | # "\M-i": " " |
|
72 | # "\M-i": " " | |
73 | # "\M-u": "\d\d\d\d" |
|
73 | # "\M-u": "\d\d\d\d" | |
74 | # $endif |
|
74 | # $endif | |
75 |
|
75 | |||
76 | # The feature is potentially a bit dangerous, because it can cause problems |
|
76 | # The feature is potentially a bit dangerous, because it can cause problems | |
77 | # with pasting of indented code (the pasted code gets re-indented on each |
|
77 | # with pasting of indented code (the pasted code gets re-indented on each | |
78 | # line). But it's a huge time-saver when working interactively. The magic |
|
78 | # line). But it's a huge time-saver when working interactively. The magic | |
79 | # function @autoindent allows you to toggle it on/off at runtime. |
|
79 | # function @autoindent allows you to toggle it on/off at runtime. | |
80 |
|
80 | |||
81 | autoindent 1 |
|
81 | autoindent 1 | |
82 |
|
82 | |||
83 | # Auto-magic. This gives you access to all the magic functions without having |
|
83 | # Auto-magic. This gives you access to all the magic functions without having | |
84 | # to prepend them with an @ sign. If you define a variable with the same name |
|
84 | # to prepend them with an @ sign. If you define a variable with the same name | |
85 | # as a magic function (say who=1), you will need to access the magic function |
|
85 | # as a magic function (say who=1), you will need to access the magic function | |
86 | # with @ (@who in this example). However, if later you delete your variable |
|
86 | # with @ (@who in this example). However, if later you delete your variable | |
87 | # (del who), you'll recover the automagic calling form. |
|
87 | # (del who), you'll recover the automagic calling form. | |
88 |
|
88 | |||
89 | # Considering that many magic functions provide a lot of shell-like |
|
89 | # Considering that many magic functions provide a lot of shell-like | |
90 | # functionality, automagic gives you something close to a full Python+system |
|
90 | # functionality, automagic gives you something close to a full Python+system | |
91 | # shell environment (and you can extend it further if you want). |
|
91 | # shell environment (and you can extend it further if you want). | |
92 |
|
92 | |||
93 | automagic 1 |
|
93 | automagic 1 | |
94 |
|
94 | |||
95 | # Size of the output cache. After this many entries are stored, the cache will |
|
95 | # Size of the output cache. After this many entries are stored, the cache will | |
96 | # get flushed. Depending on the size of your intermediate calculations, you |
|
96 | # get flushed. Depending on the size of your intermediate calculations, you | |
97 | # may have memory problems if you make it too big, since keeping things in the |
|
97 | # may have memory problems if you make it too big, since keeping things in the | |
98 | # cache prevents Python from reclaiming the memory for old results. Experiment |
|
98 | # cache prevents Python from reclaiming the memory for old results. Experiment | |
99 | # with a value that works well for you. |
|
99 | # with a value that works well for you. | |
100 |
|
100 | |||
101 | # If you choose cache_size 0 IPython will revert to python's regular >>> |
|
101 | # If you choose cache_size 0 IPython will revert to python's regular >>> | |
102 | # unnumbered prompt. You will still have _, __ and ___ for your last three |
|
102 | # unnumbered prompt. You will still have _, __ and ___ for your last three | |
103 | # results, but that will be it. No dynamic _1, _2, etc. will be created. If |
|
103 | # results, but that will be it. No dynamic _1, _2, etc. will be created. If | |
104 | # you are running on a slow machine or with very limited memory, this may |
|
104 | # you are running on a slow machine or with very limited memory, this may | |
105 | # help. |
|
105 | # help. | |
106 |
|
106 | |||
107 | cache_size 1000 |
|
107 | cache_size 1000 | |
108 |
|
108 | |||
109 | # Classic mode: Setting 'classic 1' you lose many of IPython niceties, |
|
109 | # Classic mode: Setting 'classic 1' you lose many of IPython niceties, | |
110 | # but that's your choice! Classic 1 -> same as IPython -classic. |
|
110 | # but that's your choice! Classic 1 -> same as IPython -classic. | |
111 | # Note that this is _not_ the normal python interpreter, it's simply |
|
111 | # Note that this is _not_ the normal python interpreter, it's simply | |
112 | # IPython emulating most of the classic interpreter's behavior. |
|
112 | # IPython emulating most of the classic interpreter's behavior. | |
113 | classic 0 |
|
113 | classic 0 | |
114 |
|
114 | |||
115 | # colors - Coloring option for prompts and traceback printouts. |
|
115 | # colors - Coloring option for prompts and traceback printouts. | |
116 |
|
116 | |||
117 | # Currently available schemes: NoColor, Linux, LightBG. |
|
117 | # Currently available schemes: NoColor, Linux, LightBG. | |
118 |
|
118 | |||
119 | # This option allows coloring the prompts and traceback printouts. This |
|
119 | # This option allows coloring the prompts and traceback printouts. This | |
120 | # requires a terminal which can properly handle color escape sequences. If you |
|
120 | # requires a terminal which can properly handle color escape sequences. If you | |
121 | # are having problems with this, use the NoColor scheme (uses no color escapes |
|
121 | # are having problems with this, use the NoColor scheme (uses no color escapes | |
122 | # at all). |
|
122 | # at all). | |
123 |
|
123 | |||
124 | # The Linux option works well in linux console type environments: dark |
|
124 | # The Linux option works well in linux console type environments: dark | |
125 | # background with light fonts. |
|
125 | # background with light fonts. | |
126 |
|
126 | |||
127 | # LightBG is similar to Linux but swaps dark/light colors to be more readable |
|
127 | # LightBG is similar to Linux but swaps dark/light colors to be more readable | |
128 | # in light background terminals. |
|
128 | # in light background terminals. | |
129 |
|
129 | |||
130 | # keep uncommented only the one you want: |
|
130 | # keep uncommented only the one you want: | |
131 | colors Linux |
|
131 | colors Linux | |
132 | #colors LightBG |
|
132 | #colors LightBG | |
133 | #colors NoColor |
|
133 | #colors NoColor | |
134 |
|
134 | |||
135 | ######################## |
|
135 | ######################## | |
136 | # Note to Windows users |
|
136 | # Note to Windows users | |
137 | # |
|
137 | # | |
138 | # Color and readline support is avaialble to Windows users via Gary Bishop's |
|
138 | # Color and readline support is avaialble to Windows users via Gary Bishop's | |
139 | # readline library. You can find Gary's tools at |
|
139 | # readline library. You can find Gary's tools at | |
140 | # http://sourceforge.net/projects/uncpythontools. |
|
140 | # http://sourceforge.net/projects/uncpythontools. | |
141 | # Note that his readline module requires in turn the ctypes library, available |
|
141 | # Note that his readline module requires in turn the ctypes library, available | |
142 | # at http://starship.python.net/crew/theller/ctypes. |
|
142 | # at http://starship.python.net/crew/theller/ctypes. | |
143 | ######################## |
|
143 | ######################## | |
144 |
|
144 | |||
145 | # color_info: IPython can display information about objects via a set of |
|
145 | # color_info: IPython can display information about objects via a set of | |
146 | # functions, and optionally can use colors for this, syntax highlighting |
|
146 | # functions, and optionally can use colors for this, syntax highlighting | |
147 | # source code and various other elements. This information is passed through a |
|
147 | # source code and various other elements. This information is passed through a | |
148 | # pager (it defaults to 'less' if $PAGER is not set). |
|
148 | # pager (it defaults to 'less' if $PAGER is not set). | |
149 |
|
149 | |||
150 | # If your pager has problems, try to setting it to properly handle escapes |
|
150 | # If your pager has problems, try to setting it to properly handle escapes | |
151 | # (see the less manpage for detail), or disable this option. The magic |
|
151 | # (see the less manpage for detail), or disable this option. The magic | |
152 | # function @color_info allows you to toggle this interactively for testing. |
|
152 | # function @color_info allows you to toggle this interactively for testing. | |
153 |
|
153 | |||
154 | color_info 1 |
|
154 | color_info 1 | |
155 |
|
155 | |||
156 | # confirm_exit: set to 1 if you want IPython to confirm when you try to exit |
|
156 | # confirm_exit: set to 1 if you want IPython to confirm when you try to exit | |
157 | # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using |
|
157 | # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using | |
158 | # the magic functions @Exit or @Quit you can force a direct exit, bypassing |
|
158 | # the magic functions @Exit or @Quit you can force a direct exit, bypassing | |
159 | # any confirmation. |
|
159 | # any confirmation. | |
160 |
|
160 | |||
161 | confirm_exit 1 |
|
161 | confirm_exit 1 | |
162 |
|
162 | |||
163 | # Use deep_reload() as a substitute for reload() by default. deep_reload() is |
|
163 | # Use deep_reload() as a substitute for reload() by default. deep_reload() is | |
164 | # still available as dreload() and appears as a builtin. |
|
164 | # still available as dreload() and appears as a builtin. | |
165 |
|
165 | |||
166 | deep_reload 0 |
|
166 | deep_reload 0 | |
167 |
|
167 | |||
168 | # Which editor to use with the @edit command. If you leave this at 0, IPython |
|
168 | # Which editor to use with the @edit command. If you leave this at 0, IPython | |
169 | # will honor your EDITOR environment variable. Since this editor is invoked on |
|
169 | # will honor your EDITOR environment variable. Since this editor is invoked on | |
170 | # the fly by ipython and is meant for editing small code snippets, you may |
|
170 | # the fly by ipython and is meant for editing small code snippets, you may | |
171 | # want to use a small, lightweight editor here. |
|
171 | # want to use a small, lightweight editor here. | |
172 |
|
172 | |||
173 | # For Emacs users, setting up your Emacs server properly as described in the |
|
173 | # For Emacs users, setting up your Emacs server properly as described in the | |
174 | # manual is a good idea. An alternative is to use jed, a very light editor |
|
174 | # manual is a good idea. An alternative is to use jed, a very light editor | |
175 | # with much of the feel of Emacs (though not as powerful for heavy-duty work). |
|
175 | # with much of the feel of Emacs (though not as powerful for heavy-duty work). | |
176 |
|
176 | |||
177 | editor 0 |
|
177 | editor 0 | |
178 |
|
178 | |||
179 | # log 1 -> same as ipython -log. This automatically logs to ./ipython.log |
|
179 | # log 1 -> same as ipython -log. This automatically logs to ./ipython.log | |
180 | log 0 |
|
180 | log 0 | |
181 |
|
181 | |||
182 | # Same as ipython -Logfile YourLogfileName. |
|
182 | # Same as ipython -Logfile YourLogfileName. | |
183 | # Don't use with log 1 (use one or the other) |
|
183 | # Don't use with log 1 (use one or the other) | |
184 | logfile '' |
|
184 | logfile '' | |
185 |
|
185 | |||
186 | # banner 0 -> same as ipython -nobanner |
|
186 | # banner 0 -> same as ipython -nobanner | |
187 | banner 1 |
|
187 | banner 1 | |
188 |
|
188 | |||
189 | # messages 0 -> same as ipython -nomessages |
|
189 | # messages 0 -> same as ipython -nomessages | |
190 | messages 1 |
|
190 | messages 1 | |
191 |
|
191 | |||
192 | # Automatically call the pdb debugger after every uncaught exception. If you |
|
192 | # Automatically call the pdb debugger after every uncaught exception. If you | |
193 | # are used to debugging using pdb, this puts you automatically inside of it |
|
193 | # are used to debugging using pdb, this puts you automatically inside of it | |
194 | # after any call (either in IPython or in code called by it) which triggers an |
|
194 | # after any call (either in IPython or in code called by it) which triggers an | |
195 | # exception which goes uncaught. |
|
195 | # exception which goes uncaught. | |
196 | pdb 0 |
|
196 | pdb 0 | |
197 |
|
197 | |||
198 | # Enable the pprint module for printing. pprint tends to give a more readable |
|
198 | # Enable the pprint module for printing. pprint tends to give a more readable | |
199 | # display (than print) for complex nested data structures. |
|
199 | # display (than print) for complex nested data structures. | |
200 | pprint 1 |
|
200 | pprint 1 | |
201 |
|
201 | |||
202 | # Prompt strings |
|
202 | # Prompt strings | |
203 |
|
203 | |||
204 | # Most bash-like escapes can be used to customize IPython's prompts, as well as |
|
204 | # Most bash-like escapes can be used to customize IPython's prompts, as well as | |
205 | # a few additional ones which are IPython-specific. All valid prompt escapes |
|
205 | # a few additional ones which are IPython-specific. All valid prompt escapes | |
206 | # are described in detail in the Customization section of the IPython HTML/PDF |
|
206 | # are described in detail in the Customization section of the IPython HTML/PDF | |
207 | # manual. |
|
207 | # manual. | |
208 |
|
208 | |||
209 | # Use \# to represent the current prompt number, and quote them to protect |
|
209 | # Use \# to represent the current prompt number, and quote them to protect | |
210 | # spaces. |
|
210 | # spaces. | |
211 | prompt_in1 'In [\#]: ' |
|
211 | prompt_in1 'In [\#]: ' | |
212 |
|
212 | |||
213 | # \D is replaced by as many dots as there are digits in the |
|
213 | # \D is replaced by as many dots as there are digits in the | |
214 | # current value of \#. |
|
214 | # current value of \#. | |
215 | prompt_in2 ' .\D.: ' |
|
215 | prompt_in2 ' .\D.: ' | |
216 |
|
216 | |||
217 | prompt_out 'Out[\#]: ' |
|
217 | prompt_out 'Out[\#]: ' | |
218 |
|
218 | |||
219 | # Select whether to left-pad the output prompts to match the length of the |
|
219 | # Select whether to left-pad the output prompts to match the length of the | |
220 | # input ones. This allows you for example to use a simple '>' as an output |
|
220 | # input ones. This allows you for example to use a simple '>' as an output | |
221 | # prompt, and yet have the output line up with the input. If set to false, |
|
221 | # prompt, and yet have the output line up with the input. If set to false, | |
222 | # the output prompts will be unpadded (flush left). |
|
222 | # the output prompts will be unpadded (flush left). | |
223 | prompts_pad_left 1 |
|
223 | prompts_pad_left 1 | |
224 |
|
224 | |||
225 | # quick 1 -> same as ipython -quick |
|
225 | # quick 1 -> same as ipython -quick | |
226 | quick 0 |
|
226 | quick 0 | |
227 |
|
227 | |||
228 | # Use the readline library (1) or not (0). Most users will want this on, but |
|
228 | # Use the readline library (1) or not (0). Most users will want this on, but | |
229 | # if you experience strange problems with line management (mainly when using |
|
229 | # if you experience strange problems with line management (mainly when using | |
230 | # IPython inside Emacs buffers) you may try disabling it. Not having it on |
|
230 | # IPython inside Emacs buffers) you may try disabling it. Not having it on | |
231 | # prevents you from getting command history with the arrow keys, searching and |
|
231 | # prevents you from getting command history with the arrow keys, searching and | |
232 | # name completion using TAB. |
|
232 | # name completion using TAB. | |
233 |
|
233 | |||
234 | readline 1 |
|
234 | readline 1 | |
235 |
|
235 | |||
236 | # Screen Length: number of lines of your screen. This is used to control |
|
236 | # Screen Length: number of lines of your screen. This is used to control | |
237 | # printing of very long strings. Strings longer than this number of lines will |
|
237 | # printing of very long strings. Strings longer than this number of lines will | |
238 | # be paged with the less command instead of directly printed. |
|
238 | # be paged with the less command instead of directly printed. | |
239 |
|
239 | |||
240 | # The default value for this is 0, which means IPython will auto-detect your |
|
240 | # The default value for this is 0, which means IPython will auto-detect your | |
241 | # screen size every time it needs to print. If for some reason this isn't |
|
241 | # screen size every time it needs to print. If for some reason this isn't | |
242 | # working well (it needs curses support), specify it yourself. Otherwise don't |
|
242 | # working well (it needs curses support), specify it yourself. Otherwise don't | |
243 | # change the default. |
|
243 | # change the default. | |
244 |
|
244 | |||
245 | screen_length 0 |
|
245 | screen_length 0 | |
246 |
|
246 | |||
247 | # Prompt separators for input and output. |
|
247 | # Prompt separators for input and output. | |
248 | # Use \n for newline explicitly, without quotes. |
|
248 | # Use \n for newline explicitly, without quotes. | |
249 | # Use 0 (like at the cmd line) to turn off a given separator. |
|
249 | # Use 0 (like at the cmd line) to turn off a given separator. | |
250 |
|
250 | |||
251 | # The structure of prompt printing is: |
|
251 | # The structure of prompt printing is: | |
252 | # (SeparateIn)Input.... |
|
252 | # (SeparateIn)Input.... | |
253 | # (SeparateOut)Output... |
|
253 | # (SeparateOut)Output... | |
254 | # (SeparateOut2), # that is, no newline is printed after Out2 |
|
254 | # (SeparateOut2), # that is, no newline is printed after Out2 | |
255 | # By choosing these you can organize your output any way you want. |
|
255 | # By choosing these you can organize your output any way you want. | |
256 |
|
256 | |||
257 | separate_in \n |
|
257 | separate_in \n | |
258 | separate_out 0 |
|
258 | separate_out 0 | |
259 | separate_out2 0 |
|
259 | separate_out2 0 | |
260 |
|
260 | |||
261 | # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'. |
|
261 | # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'. | |
262 | # Simply removes all input/output separators, overriding the choices above. |
|
262 | # Simply removes all input/output separators, overriding the choices above. | |
263 | nosep 0 |
|
263 | nosep 0 | |
264 |
|
264 | |||
265 | # xmode - Exception reporting mode. |
|
265 | # xmode - Exception reporting mode. | |
266 |
|
266 | |||
267 | # Valid modes: Plain, Context and Verbose. |
|
267 | # Valid modes: Plain, Context and Verbose. | |
268 |
|
268 | |||
269 | # Plain: similar to python's normal traceback printing. |
|
269 | # Plain: similar to python's normal traceback printing. | |
270 |
|
270 | |||
271 | # Context: prints 5 lines of context source code around each line in the |
|
271 | # Context: prints 5 lines of context source code around each line in the | |
272 | # traceback. |
|
272 | # traceback. | |
273 |
|
273 | |||
274 | # Verbose: similar to Context, but additionally prints the variables currently |
|
274 | # Verbose: similar to Context, but additionally prints the variables currently | |
275 | # visible where the exception happened (shortening their strings if too |
|
275 | # visible where the exception happened (shortening their strings if too | |
276 | # long). This can potentially be very slow, if you happen to have a huge data |
|
276 | # long). This can potentially be very slow, if you happen to have a huge data | |
277 | # structure whose string representation is complex to compute. Your computer |
|
277 | # structure whose string representation is complex to compute. Your computer | |
278 | # may appear to freeze for a while with cpu usage at 100%. If this occurs, you |
|
278 | # may appear to freeze for a while with cpu usage at 100%. If this occurs, you | |
279 | # can cancel the traceback with Ctrl-C (maybe hitting it more than once). |
|
279 | # can cancel the traceback with Ctrl-C (maybe hitting it more than once). | |
280 |
|
280 | |||
281 | #xmode Plain |
|
281 | #xmode Plain | |
282 | xmode Context |
|
282 | xmode Context | |
283 | #xmode Verbose |
|
283 | #xmode Verbose | |
284 |
|
284 | |||
285 | # multi_line_specials: if true, allow magics, aliases and shell escapes (via |
|
285 | # multi_line_specials: if true, allow magics, aliases and shell escapes (via | |
286 | # !cmd) to be used in multi-line input (like for loops). For example, if you |
|
286 | # !cmd) to be used in multi-line input (like for loops). For example, if you | |
287 | # have this active, the following is valid in IPython: |
|
287 | # have this active, the following is valid in IPython: | |
288 | # |
|
288 | # | |
289 | #In [17]: for i in range(3): |
|
289 | #In [17]: for i in range(3): | |
290 | # ....: mkdir $i |
|
290 | # ....: mkdir $i | |
291 | # ....: !touch $i/hello |
|
291 | # ....: !touch $i/hello | |
292 | # ....: ls -l $i |
|
292 | # ....: ls -l $i | |
293 |
|
293 | |||
294 | multi_line_specials 1 |
|
294 | multi_line_specials 1 | |
295 |
|
295 | |||
296 | #--------------------------------------------------------------------------- |
|
296 | #--------------------------------------------------------------------------- | |
297 | # Section: Readline configuration (readline is not available for MS-Windows) |
|
297 | # Section: Readline configuration (readline is not available for MS-Windows) | |
298 |
|
298 | |||
299 | # This is done via the following options: |
|
299 | # This is done via the following options: | |
300 |
|
300 | |||
301 | # (i) readline_parse_and_bind: this option can appear as many times as you |
|
301 | # (i) readline_parse_and_bind: this option can appear as many times as you | |
302 | # want, each time defining a string to be executed via a |
|
302 | # want, each time defining a string to be executed via a | |
303 | # readline.parse_and_bind() command. The syntax for valid commands of this |
|
303 | # readline.parse_and_bind() command. The syntax for valid commands of this | |
304 | # kind can be found by reading the documentation for the GNU readline library, |
|
304 | # kind can be found by reading the documentation for the GNU readline library, | |
305 | # as these commands are of the kind which readline accepts in its |
|
305 | # as these commands are of the kind which readline accepts in its | |
306 | # configuration file. |
|
306 | # configuration file. | |
307 |
|
307 | |||
308 | # The TAB key can be used to complete names at the command line in one of two |
|
308 | # The TAB key can be used to complete names at the command line in one of two | |
309 | # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only |
|
309 | # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only | |
310 | # completes as much as possible while 'menu-complete' cycles through all |
|
310 | # completes as much as possible while 'menu-complete' cycles through all | |
311 | # possible completions. Leave the one you prefer uncommented. |
|
311 | # possible completions. Leave the one you prefer uncommented. | |
312 |
|
312 | |||
313 | readline_parse_and_bind tab: complete |
|
313 | readline_parse_and_bind tab: complete | |
314 | #readline_parse_and_bind tab: menu-complete |
|
314 | #readline_parse_and_bind tab: menu-complete | |
315 |
|
315 | |||
316 | # This binds Control-l to printing the list of all possible completions when |
|
316 | # This binds Control-l to printing the list of all possible completions when | |
317 | # there is more than one (what 'complete' does when hitting TAB twice, or at |
|
317 | # there is more than one (what 'complete' does when hitting TAB twice, or at | |
318 | # the first TAB if show-all-if-ambiguous is on) |
|
318 | # the first TAB if show-all-if-ambiguous is on) | |
319 | readline_parse_and_bind "\C-l": possible-completions |
|
319 | readline_parse_and_bind "\C-l": possible-completions | |
320 |
|
320 | |||
321 | # This forces readline to automatically print the above list when tab |
|
321 | # This forces readline to automatically print the above list when tab | |
322 | # completion is set to 'complete'. You can still get this list manually by |
|
322 | # completion is set to 'complete'. You can still get this list manually by | |
323 | # using the key bound to 'possible-completions' (Control-l by default) or by |
|
323 | # using the key bound to 'possible-completions' (Control-l by default) or by | |
324 | # hitting TAB twice. Turning this on makes the printing happen at the first |
|
324 | # hitting TAB twice. Turning this on makes the printing happen at the first | |
325 | # TAB. |
|
325 | # TAB. | |
326 | readline_parse_and_bind set show-all-if-ambiguous on |
|
326 | readline_parse_and_bind set show-all-if-ambiguous on | |
327 |
|
327 | |||
328 | # If you have TAB set to complete names, you can rebind any key (Control-o by |
|
328 | # If you have TAB set to complete names, you can rebind any key (Control-o by | |
329 | # default) to insert a true TAB character. |
|
329 | # default) to insert a true TAB character. | |
330 | readline_parse_and_bind "\C-o": tab-insert |
|
330 | readline_parse_and_bind "\C-o": tab-insert | |
331 |
|
331 | |||
332 | # These commands allow you to indent/unindent easily, with the 4-space |
|
332 | # These commands allow you to indent/unindent easily, with the 4-space | |
333 | # convention of the Python coding standards. Since IPython's internal |
|
333 | # convention of the Python coding standards. Since IPython's internal | |
334 | # auto-indent system also uses 4 spaces, you should not change the number of |
|
334 | # auto-indent system also uses 4 spaces, you should not change the number of | |
335 | # spaces in the code below. |
|
335 | # spaces in the code below. | |
336 | readline_parse_and_bind "\M-i": " " |
|
336 | readline_parse_and_bind "\M-i": " " | |
337 | readline_parse_and_bind "\M-o": "\d\d\d\d" |
|
337 | readline_parse_and_bind "\M-o": "\d\d\d\d" | |
338 | readline_parse_and_bind "\M-I": "\d\d\d\d" |
|
338 | readline_parse_and_bind "\M-I": "\d\d\d\d" | |
339 |
|
339 | |||
340 | # Bindings for incremental searches in the history. These searches use the |
|
340 | # Bindings for incremental searches in the history. These searches use the | |
341 | # string typed so far on the command line and search anything in the previous |
|
341 | # string typed so far on the command line and search anything in the previous | |
342 | # input history containing them. |
|
342 | # input history containing them. | |
343 | readline_parse_and_bind "\C-r": reverse-search-history |
|
343 | readline_parse_and_bind "\C-r": reverse-search-history | |
344 | readline_parse_and_bind "\C-s": forward-search-history |
|
344 | readline_parse_and_bind "\C-s": forward-search-history | |
345 |
|
345 | |||
346 | # Bindings for completing the current line in the history of previous |
|
346 | # Bindings for completing the current line in the history of previous | |
347 | # commands. This allows you to recall any previous command by typing its first |
|
347 | # commands. This allows you to recall any previous command by typing its first | |
348 | # few letters and hitting Control-p, bypassing all intermediate commands which |
|
348 | # few letters and hitting Control-p, bypassing all intermediate commands which | |
349 | # may be in the history (much faster than hitting up-arrow 50 times!) |
|
349 | # may be in the history (much faster than hitting up-arrow 50 times!) | |
350 | readline_parse_and_bind "\C-p": history-search-backward |
|
350 | readline_parse_and_bind "\C-p": history-search-backward | |
351 | readline_parse_and_bind "\C-n": history-search-forward |
|
351 | readline_parse_and_bind "\C-n": history-search-forward | |
352 |
|
352 | |||
353 | # I also like to have the same functionality on the plain arrow keys. If you'd |
|
353 | # I also like to have the same functionality on the plain arrow keys. If you'd | |
354 | # rather have the arrows use all the history (and not just match what you've |
|
354 | # rather have the arrows use all the history (and not just match what you've | |
355 | # typed so far), comment out or delete the next two lines. |
|
355 | # typed so far), comment out or delete the next two lines. | |
356 | readline_parse_and_bind "\e[A": history-search-backward |
|
356 | readline_parse_and_bind "\e[A": history-search-backward | |
357 | readline_parse_and_bind "\e[B": history-search-forward |
|
357 | readline_parse_and_bind "\e[B": history-search-forward | |
358 |
|
358 | |||
|
359 | # These are typically on by default under *nix, but not win32. | |||
|
360 | readline_parse_and_bind "\C-k": kill-line | |||
|
361 | readline_parse_and_bind "\C-u": unix-line-discard | |||
|
362 | ||||
359 | # (ii) readline_remove_delims: a string of characters to be removed from the |
|
363 | # (ii) readline_remove_delims: a string of characters to be removed from the | |
360 | # default word-delimiters list used by readline, so that completions may be |
|
364 | # default word-delimiters list used by readline, so that completions may be | |
361 | # performed on strings which contain them. |
|
365 | # performed on strings which contain them. | |
362 |
|
366 | |||
363 | readline_remove_delims -/~ |
|
367 | readline_remove_delims -/~ | |
364 |
|
368 | |||
365 | # (iii) readline_merge_completions: whether to merge the result of all |
|
369 | # (iii) readline_merge_completions: whether to merge the result of all | |
366 | # possible completions or not. If true, IPython will complete filenames, |
|
370 | # possible completions or not. If true, IPython will complete filenames, | |
367 | # python names and aliases and return all possible completions. If you set it |
|
371 | # python names and aliases and return all possible completions. If you set it | |
368 | # to false, each completer is used at a time, and only if it doesn't return |
|
372 | # to false, each completer is used at a time, and only if it doesn't return | |
369 | # any completions is the next one used. |
|
373 | # any completions is the next one used. | |
370 |
|
374 | |||
371 | # The default order is: [python_matches, file_matches, alias_matches] |
|
375 | # The default order is: [python_matches, file_matches, alias_matches] | |
372 |
|
376 | |||
373 | readline_merge_completions 1 |
|
377 | readline_merge_completions 1 | |
374 |
|
378 | |||
375 | # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name |
|
379 | # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name | |
376 | # will complete all attributes of an object, including all the special methods |
|
380 | # will complete all attributes of an object, including all the special methods | |
377 | # whose names start with single or double underscores (like __getitem__ or |
|
381 | # whose names start with single or double underscores (like __getitem__ or | |
378 | # __class__). |
|
382 | # __class__). | |
379 |
|
383 | |||
380 | # This variable allows you to control this completion behavior: |
|
384 | # This variable allows you to control this completion behavior: | |
381 |
|
385 | |||
382 | # readline_omit__names 1 -> completion will omit showing any names starting |
|
386 | # readline_omit__names 1 -> completion will omit showing any names starting | |
383 | # with two __, but it will still show names starting with one _. |
|
387 | # with two __, but it will still show names starting with one _. | |
384 |
|
388 | |||
385 | # readline_omit__names 2 -> completion will omit all names beginning with one |
|
389 | # readline_omit__names 2 -> completion will omit all names beginning with one | |
386 | # _ (which obviously means filtering out the double __ ones). |
|
390 | # _ (which obviously means filtering out the double __ ones). | |
387 |
|
391 | |||
388 | # Even when this option is set, you can still see those names by explicitly |
|
392 | # Even when this option is set, you can still see those names by explicitly | |
389 | # typing a _ after the period and hitting <tab>: 'name._<tab>' will always |
|
393 | # typing a _ after the period and hitting <tab>: 'name._<tab>' will always | |
390 | # complete attribute names starting with '_'. |
|
394 | # complete attribute names starting with '_'. | |
391 |
|
395 | |||
392 | # This option is off by default so that new users see all attributes of any |
|
396 | # This option is off by default so that new users see all attributes of any | |
393 | # objects they are dealing with. |
|
397 | # objects they are dealing with. | |
394 |
|
398 | |||
395 | readline_omit__names 0 |
|
399 | readline_omit__names 0 | |
396 |
|
400 | |||
397 | #--------------------------------------------------------------------------- |
|
401 | #--------------------------------------------------------------------------- | |
398 | # Section: modules to be loaded with 'import ...' |
|
402 | # Section: modules to be loaded with 'import ...' | |
399 |
|
403 | |||
400 | # List, separated by spaces, the names of the modules you want to import |
|
404 | # List, separated by spaces, the names of the modules you want to import | |
401 |
|
405 | |||
402 | # Example: |
|
406 | # Example: | |
403 | # import_mod sys os |
|
407 | # import_mod sys os | |
404 | # will produce internally the statements |
|
408 | # will produce internally the statements | |
405 | # import sys |
|
409 | # import sys | |
406 | # import os |
|
410 | # import os | |
407 |
|
411 | |||
408 | # Each import is executed in its own try/except block, so if one module |
|
412 | # Each import is executed in its own try/except block, so if one module | |
409 | # fails to load the others will still be ok. |
|
413 | # fails to load the others will still be ok. | |
410 |
|
414 | |||
411 | import_mod |
|
415 | import_mod | |
412 |
|
416 | |||
413 | #--------------------------------------------------------------------------- |
|
417 | #--------------------------------------------------------------------------- | |
414 | # Section: modules to import some functions from: 'from ... import ...' |
|
418 | # Section: modules to import some functions from: 'from ... import ...' | |
415 |
|
419 | |||
416 | # List, one per line, the modules for which you want only to import some |
|
420 | # List, one per line, the modules for which you want only to import some | |
417 | # functions. Give the module name first and then the name of functions to be |
|
421 | # functions. Give the module name first and then the name of functions to be | |
418 | # imported from that module. |
|
422 | # imported from that module. | |
419 |
|
423 | |||
420 | # Example: |
|
424 | # Example: | |
421 |
|
425 | |||
422 | # import_some IPython.genutils timing timings |
|
426 | # import_some IPython.genutils timing timings | |
423 | # will produce internally the statement |
|
427 | # will produce internally the statement | |
424 | # from IPython.genutils import timing, timings |
|
428 | # from IPython.genutils import timing, timings | |
425 |
|
429 | |||
426 | # timing() and timings() are two IPython utilities for timing the execution of |
|
430 | # timing() and timings() are two IPython utilities for timing the execution of | |
427 | # your own functions, which you may find useful. Just commment out the above |
|
431 | # your own functions, which you may find useful. Just commment out the above | |
428 | # line if you want to test them. |
|
432 | # line if you want to test them. | |
429 |
|
433 | |||
430 | # If you have more than one modules_some line, each gets its own try/except |
|
434 | # If you have more than one modules_some line, each gets its own try/except | |
431 | # block (like modules, see above). |
|
435 | # block (like modules, see above). | |
432 |
|
436 | |||
433 | import_some |
|
437 | import_some | |
434 |
|
438 | |||
435 | #--------------------------------------------------------------------------- |
|
439 | #--------------------------------------------------------------------------- | |
436 | # Section: modules to import all from : 'from ... import *' |
|
440 | # Section: modules to import all from : 'from ... import *' | |
437 |
|
441 | |||
438 | # List (same syntax as import_mod above) those modules for which you want to |
|
442 | # List (same syntax as import_mod above) those modules for which you want to | |
439 | # import all functions. Remember, this is a potentially dangerous thing to do, |
|
443 | # import all functions. Remember, this is a potentially dangerous thing to do, | |
440 | # since it is very easy to overwrite names of things you need. Use with |
|
444 | # since it is very easy to overwrite names of things you need. Use with | |
441 | # caution. |
|
445 | # caution. | |
442 |
|
446 | |||
443 | # Example: |
|
447 | # Example: | |
444 | # import_all sys os |
|
448 | # import_all sys os | |
445 | # will produce internally the statements |
|
449 | # will produce internally the statements | |
446 | # from sys import * |
|
450 | # from sys import * | |
447 | # from os import * |
|
451 | # from os import * | |
448 |
|
452 | |||
449 | # As before, each will be called in a separate try/except block. |
|
453 | # As before, each will be called in a separate try/except block. | |
450 |
|
454 | |||
451 | import_all |
|
455 | import_all | |
452 |
|
456 | |||
453 | #--------------------------------------------------------------------------- |
|
457 | #--------------------------------------------------------------------------- | |
454 | # Section: Python code to execute. |
|
458 | # Section: Python code to execute. | |
455 |
|
459 | |||
456 | # Put here code to be explicitly executed (keep it simple!) |
|
460 | # Put here code to be explicitly executed (keep it simple!) | |
457 | # Put one line of python code per line. All whitespace is removed (this is a |
|
461 | # Put one line of python code per line. All whitespace is removed (this is a | |
458 | # feature, not a bug), so don't get fancy building loops here. |
|
462 | # feature, not a bug), so don't get fancy building loops here. | |
459 | # This is just for quick convenient creation of things you want available. |
|
463 | # This is just for quick convenient creation of things you want available. | |
460 |
|
464 | |||
461 | # Example: |
|
465 | # Example: | |
462 | # execute x = 1 |
|
466 | # execute x = 1 | |
463 | # execute print 'hello world'; y = z = 'a' |
|
467 | # execute print 'hello world'; y = z = 'a' | |
464 | # will produce internally |
|
468 | # will produce internally | |
465 | # x = 1 |
|
469 | # x = 1 | |
466 | # print 'hello world'; y = z = 'a' |
|
470 | # print 'hello world'; y = z = 'a' | |
467 | # and each *line* (not each statement, we don't do python syntax parsing) is |
|
471 | # and each *line* (not each statement, we don't do python syntax parsing) is | |
468 | # executed in its own try/except block. |
|
472 | # executed in its own try/except block. | |
469 |
|
473 | |||
470 | execute |
|
474 | execute | |
471 |
|
475 | |||
472 | # Note for the adventurous: you can use this to define your own names for the |
|
476 | # Note for the adventurous: you can use this to define your own names for the | |
473 | # magic functions, by playing some namespace tricks: |
|
477 | # magic functions, by playing some namespace tricks: | |
474 |
|
478 | |||
475 | # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
479 | # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
476 |
|
480 | |||
477 | # defines @pf as a new name for @profile. |
|
481 | # defines @pf as a new name for @profile. | |
478 |
|
482 | |||
479 | #--------------------------------------------------------------------------- |
|
483 | #--------------------------------------------------------------------------- | |
480 | # Section: Pyhton files to load and execute. |
|
484 | # Section: Pyhton files to load and execute. | |
481 |
|
485 | |||
482 | # Put here the full names of files you want executed with execfile(file). If |
|
486 | # Put here the full names of files you want executed with execfile(file). If | |
483 | # you want complicated initialization, just write whatever you want in a |
|
487 | # you want complicated initialization, just write whatever you want in a | |
484 | # regular python file and load it from here. |
|
488 | # regular python file and load it from here. | |
485 |
|
489 | |||
486 | # Filenames defined here (which *must* include the extension) are searched for |
|
490 | # Filenames defined here (which *must* include the extension) are searched for | |
487 | # through all of sys.path. Since IPython adds your .ipython directory to |
|
491 | # through all of sys.path. Since IPython adds your .ipython directory to | |
488 | # sys.path, they can also be placed in your .ipython dir and will be |
|
492 | # sys.path, they can also be placed in your .ipython dir and will be | |
489 | # found. Otherwise (if you want to execute things not in .ipyton nor in |
|
493 | # found. Otherwise (if you want to execute things not in .ipyton nor in | |
490 | # sys.path) give a full path (you can use ~, it gets expanded) |
|
494 | # sys.path) give a full path (you can use ~, it gets expanded) | |
491 |
|
495 | |||
492 | # Example: |
|
496 | # Example: | |
493 | # execfile file1.py ~/file2.py |
|
497 | # execfile file1.py ~/file2.py | |
494 | # will generate |
|
498 | # will generate | |
495 | # execfile('file1.py') |
|
499 | # execfile('file1.py') | |
496 | # execfile('_path_to_your_home/file2.py') |
|
500 | # execfile('_path_to_your_home/file2.py') | |
497 |
|
501 | |||
498 | # As before, each file gets its own try/except block. |
|
502 | # As before, each file gets its own try/except block. | |
499 |
|
503 | |||
500 | execfile |
|
504 | execfile | |
501 |
|
505 | |||
502 | # If you are feeling adventurous, you can even add functionality to IPython |
|
506 | # If you are feeling adventurous, you can even add functionality to IPython | |
503 | # through here. IPython works through a global variable called __ip which |
|
507 | # through here. IPython works through a global variable called __ip which | |
504 | # exists at the time when these files are read. If you know what you are doing |
|
508 | # exists at the time when these files are read. If you know what you are doing | |
505 | # (read the source) you can add functions to __ip in files loaded here. |
|
509 | # (read the source) you can add functions to __ip in files loaded here. | |
506 |
|
510 | |||
507 | # The file example-magic.py contains a simple but correct example. Try it: |
|
511 | # The file example-magic.py contains a simple but correct example. Try it: | |
508 |
|
512 | |||
509 | # execfile example-magic.py |
|
513 | # execfile example-magic.py | |
510 |
|
514 | |||
511 | # Look at the examples in IPython/iplib.py for more details on how these magic |
|
515 | # Look at the examples in IPython/iplib.py for more details on how these magic | |
512 | # functions need to process their arguments. |
|
516 | # functions need to process their arguments. | |
513 |
|
517 | |||
514 | #--------------------------------------------------------------------------- |
|
518 | #--------------------------------------------------------------------------- | |
515 | # Section: aliases for system shell commands |
|
519 | # Section: aliases for system shell commands | |
516 |
|
520 | |||
517 | # Here you can define your own names for system commands. The syntax is |
|
521 | # Here you can define your own names for system commands. The syntax is | |
518 | # similar to that of the builtin @alias function: |
|
522 | # similar to that of the builtin @alias function: | |
519 |
|
523 | |||
520 | # alias alias_name command_string |
|
524 | # alias alias_name command_string | |
521 |
|
525 | |||
522 | # The resulting aliases are auto-generated magic functions (hence usable as |
|
526 | # The resulting aliases are auto-generated magic functions (hence usable as | |
523 | # @alias_name) |
|
527 | # @alias_name) | |
524 |
|
528 | |||
525 | # For example: |
|
529 | # For example: | |
526 |
|
530 | |||
527 | # alias myls ls -la |
|
531 | # alias myls ls -la | |
528 |
|
532 | |||
529 | # will define 'myls' as an alias for executing the system command 'ls -la'. |
|
533 | # will define 'myls' as an alias for executing the system command 'ls -la'. | |
530 | # This allows you to customize IPython's environment to have the same aliases |
|
534 | # This allows you to customize IPython's environment to have the same aliases | |
531 | # you are accustomed to from your own shell. |
|
535 | # you are accustomed to from your own shell. | |
532 |
|
536 | |||
533 | # You can also define aliases with parameters using %s specifiers (one per |
|
537 | # You can also define aliases with parameters using %s specifiers (one per | |
534 | # parameter): |
|
538 | # parameter): | |
535 |
|
539 | |||
536 | # alias parts echo first %s second %s |
|
540 | # alias parts echo first %s second %s | |
537 |
|
541 | |||
538 | # will give you in IPython: |
|
542 | # will give you in IPython: | |
539 | # >>> @parts A B |
|
543 | # >>> @parts A B | |
540 | # first A second B |
|
544 | # first A second B | |
541 |
|
545 | |||
542 | # Use one 'alias' statement per alias you wish to define. |
|
546 | # Use one 'alias' statement per alias you wish to define. | |
543 |
|
547 | |||
544 | # alias |
|
548 | # alias | |
545 |
|
549 | |||
546 | #************************* end of file <ipythonrc> ************************ |
|
550 | #************************* end of file <ipythonrc> ************************ |
@@ -1,1519 +1,1519 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | General purpose utilities. |
|
3 | General purpose utilities. | |
4 |
|
4 | |||
5 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
5 | This is a grab-bag of stuff I find useful in most programs I write. Some of | |
6 | these things are also convenient when working at the command line. |
|
6 | these things are also convenient when working at the command line. | |
7 |
|
7 | |||
8 |
$Id: genutils.py |
|
8 | $Id: genutils.py 633 2005-07-17 01:03:15Z tzanko $""" | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> |
|
11 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
19 | __license__ = Release.license |
|
19 | __license__ = Release.license | |
20 |
|
20 | |||
21 | #**************************************************************************** |
|
21 | #**************************************************************************** | |
22 | # required modules |
|
22 | # required modules | |
23 | import __main__ |
|
23 | import __main__ | |
24 | import types,commands,time,sys,os,re,shutil |
|
24 | import types,commands,time,sys,os,re,shutil | |
25 | import tempfile |
|
25 | import tempfile | |
26 | from IPython.Itpl import Itpl,itpl,printpl |
|
26 | from IPython.Itpl import Itpl,itpl,printpl | |
27 | from IPython import DPyGetOpt |
|
27 | from IPython import DPyGetOpt | |
28 |
|
28 | |||
29 | #**************************************************************************** |
|
29 | #**************************************************************************** | |
30 | # Exceptions |
|
30 | # Exceptions | |
31 | class Error(Exception): |
|
31 | class Error(Exception): | |
32 | """Base class for exceptions in this module.""" |
|
32 | """Base class for exceptions in this module.""" | |
33 | pass |
|
33 | pass | |
34 |
|
34 | |||
35 | #---------------------------------------------------------------------------- |
|
35 | #---------------------------------------------------------------------------- | |
36 | class Stream: |
|
36 | class Stream: | |
37 | """Simple class to hold the various I/O streams in Term""" |
|
37 | """Simple class to hold the various I/O streams in Term""" | |
38 |
|
38 | |||
39 | def __init__(self,stream,name): |
|
39 | def __init__(self,stream,name): | |
40 | self.stream = stream |
|
40 | self.stream = stream | |
41 | self.name = name |
|
41 | self.name = name | |
42 | try: |
|
42 | try: | |
43 | self.fileno = stream.fileno() |
|
43 | self.fileno = stream.fileno() | |
44 | except AttributeError: |
|
44 | except AttributeError: | |
45 | msg = ("Stream <%s> looks suspicious: it lacks a 'fileno' attribute." |
|
45 | msg = ("Stream <%s> looks suspicious: it lacks a 'fileno' attribute." | |
46 | % name) |
|
46 | % name) | |
47 | print >> sys.stderr, 'WARNING:',msg |
|
47 | print >> sys.stderr, 'WARNING:',msg | |
48 | try: |
|
48 | try: | |
49 | self.mode = stream.mode |
|
49 | self.mode = stream.mode | |
50 | except AttributeError: |
|
50 | except AttributeError: | |
51 | msg = ("Stream <%s> looks suspicious: it lacks a 'mode' attribute." |
|
51 | msg = ("Stream <%s> looks suspicious: it lacks a 'mode' attribute." | |
52 | % name) |
|
52 | % name) | |
53 | print >> sys.stderr, 'WARNING:',msg |
|
53 | print >> sys.stderr, 'WARNING:',msg | |
54 |
|
54 | |||
55 | class Term: |
|
55 | class Term: | |
56 | """ Term holds the file or file-like objects for handling I/O operations. |
|
56 | """ Term holds the file or file-like objects for handling I/O operations. | |
57 |
|
57 | |||
58 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
58 | These are normally just sys.stdin, sys.stdout and sys.stderr but for | |
59 | Windows they can can replaced to allow editing the strings before they are |
|
59 | Windows they can can replaced to allow editing the strings before they are | |
60 | displayed.""" |
|
60 | displayed.""" | |
61 |
|
61 | |||
62 | # In the future, having IPython channel all its I/O operations through |
|
62 | # In the future, having IPython channel all its I/O operations through | |
63 | # this class will make it easier to embed it into other environments which |
|
63 | # this class will make it easier to embed it into other environments which | |
64 | # are not a normal terminal (such as a GUI-based shell) |
|
64 | # are not a normal terminal (such as a GUI-based shell) | |
65 | in_s = Stream(sys.stdin,'cin') |
|
65 | in_s = Stream(sys.stdin,'cin') | |
66 | out_s = Stream(sys.stdout,'cout') |
|
66 | out_s = Stream(sys.stdout,'cout') | |
67 | err_s = Stream(sys.stderr,'cerr') |
|
67 | err_s = Stream(sys.stderr,'cerr') | |
68 |
|
68 | |||
69 | # Store the three streams in (err,out,in) order so that if we need to reopen |
|
69 | # Store the three streams in (err,out,in) order so that if we need to reopen | |
70 | # them, the error channel is reopened first to provide info. |
|
70 | # them, the error channel is reopened first to provide info. | |
71 | streams = [err_s,out_s,in_s] |
|
71 | streams = [err_s,out_s,in_s] | |
72 |
|
72 | |||
73 | # The class globals should be the actual 'bare' streams for normal I/O to work |
|
73 | # The class globals should be the actual 'bare' streams for normal I/O to work | |
74 | cin = streams[2].stream |
|
74 | cin = streams[2].stream | |
75 | cout = streams[1].stream |
|
75 | cout = streams[1].stream | |
76 | cerr = streams[0].stream |
|
76 | cerr = streams[0].stream | |
77 |
|
77 | |||
78 | def reopen_all(cls): |
|
78 | def reopen_all(cls): | |
79 | """Reopen all streams if necessary. |
|
79 | """Reopen all streams if necessary. | |
80 |
|
80 | |||
81 | This should only be called if it is suspected that someting closed |
|
81 | This should only be called if it is suspected that someting closed | |
82 | accidentally one of the I/O streams.""" |
|
82 | accidentally one of the I/O streams.""" | |
83 |
|
83 | |||
84 | any_closed = 0 |
|
84 | any_closed = 0 | |
85 |
|
85 | |||
86 | for sn in range(len(cls.streams)): |
|
86 | for sn in range(len(cls.streams)): | |
87 | st = cls.streams[sn] |
|
87 | st = cls.streams[sn] | |
88 | if st.stream.closed: |
|
88 | if st.stream.closed: | |
89 | any_closed = 1 |
|
89 | any_closed = 1 | |
90 | new_stream = os.fdopen(os.dup(st.fileno), st.mode,0) |
|
90 | new_stream = os.fdopen(os.dup(st.fileno), st.mode,0) | |
91 | cls.streams[sn] = Stream(new_stream,st.name) |
|
91 | cls.streams[sn] = Stream(new_stream,st.name) | |
92 | print >> cls.streams[0].stream, \ |
|
92 | print >> cls.streams[0].stream, \ | |
93 | '\nWARNING:\nStream Term.%s had to be reopened!' % st.name |
|
93 | '\nWARNING:\nStream Term.%s had to be reopened!' % st.name | |
94 |
|
94 | |||
95 | # Rebuild the class globals |
|
95 | # Rebuild the class globals | |
96 | cls.cin = cls.streams[2].stream |
|
96 | cls.cin = cls.streams[2].stream | |
97 | cls.cout = cls.streams[1].stream |
|
97 | cls.cout = cls.streams[1].stream | |
98 | cls.cerr = cls.streams[0].stream |
|
98 | cls.cerr = cls.streams[0].stream | |
99 |
|
99 | |||
100 | reopen_all = classmethod(reopen_all) |
|
100 | reopen_all = classmethod(reopen_all) | |
101 |
|
101 | |||
102 | def set_stdout(cls,stream): |
|
102 | def set_stdout(cls,stream): | |
103 | """Set the stream """ |
|
103 | """Set the stream """ | |
104 | cls.cout = stream |
|
104 | cls.cout = stream | |
105 | set_stdout = classmethod(set_stdout) |
|
105 | set_stdout = classmethod(set_stdout) | |
106 |
|
106 | |||
107 | def set_stderr(cls,stream): |
|
107 | def set_stderr(cls,stream): | |
108 | cls.cerr = stream |
|
108 | cls.cerr = stream | |
109 | set_stderr = classmethod(set_stderr) |
|
109 | set_stderr = classmethod(set_stderr) | |
110 |
|
110 | |||
111 | # Windows-specific code to load Gary Bishop's readline and configure it |
|
111 | # Windows-specific code to load Gary Bishop's readline and configure it | |
112 | # automatically for the users |
|
112 | # automatically for the users | |
113 | # Note: os.name on cygwin returns posix, so this should only pick up 'native' |
|
113 | # Note: os.name on cygwin returns posix, so this should only pick up 'native' | |
114 | # windows. Cygwin returns 'cygwin' for sys.platform. |
|
114 | # windows. Cygwin returns 'cygwin' for sys.platform. | |
115 | if os.name == 'nt': |
|
115 | if os.name == 'nt': | |
116 | try: |
|
116 | try: | |
117 | import readline |
|
117 | import readline | |
118 | except ImportError: |
|
118 | except ImportError: | |
119 | pass |
|
119 | pass | |
120 | else: |
|
120 | else: | |
121 | try: |
|
121 | try: | |
122 | _out = readline.GetOutputFile() |
|
122 | _out = readline.GetOutputFile() | |
123 | except AttributeError: |
|
123 | except AttributeError: | |
124 | pass |
|
124 | pass | |
125 | else: |
|
125 | else: | |
126 | Term.set_stdout(_out) |
|
126 | Term.set_stdout(_out) | |
127 | Term.set_stderr(_out) |
|
127 | Term.set_stderr(_out) | |
128 | del _out |
|
128 | del _out | |
129 |
|
129 | |||
130 | #**************************************************************************** |
|
130 | #**************************************************************************** | |
131 | # Generic warning/error printer, used by everything else |
|
131 | # Generic warning/error printer, used by everything else | |
132 | def warn(msg,level=2,exit_val=1): |
|
132 | def warn(msg,level=2,exit_val=1): | |
133 | """Standard warning printer. Gives formatting consistency. |
|
133 | """Standard warning printer. Gives formatting consistency. | |
134 |
|
134 | |||
135 | Output is sent to Term.cerr (sys.stderr by default). |
|
135 | Output is sent to Term.cerr (sys.stderr by default). | |
136 |
|
136 | |||
137 | Options: |
|
137 | Options: | |
138 |
|
138 | |||
139 | -level(2): allows finer control: |
|
139 | -level(2): allows finer control: | |
140 | 0 -> Do nothing, dummy function. |
|
140 | 0 -> Do nothing, dummy function. | |
141 | 1 -> Print message. |
|
141 | 1 -> Print message. | |
142 | 2 -> Print 'WARNING:' + message. (Default level). |
|
142 | 2 -> Print 'WARNING:' + message. (Default level). | |
143 | 3 -> Print 'ERROR:' + message. |
|
143 | 3 -> Print 'ERROR:' + message. | |
144 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
144 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). | |
145 |
|
145 | |||
146 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
146 | -exit_val (1): exit value returned by sys.exit() for a level 4 | |
147 | warning. Ignored for all other levels.""" |
|
147 | warning. Ignored for all other levels.""" | |
148 |
|
148 | |||
149 | if level>0: |
|
149 | if level>0: | |
150 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
150 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] | |
151 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
151 | print >> Term.cerr, '%s%s' % (header[level],msg) | |
152 | if level == 4: |
|
152 | if level == 4: | |
153 | print >> Term.cerr,'Exiting.\n' |
|
153 | print >> Term.cerr,'Exiting.\n' | |
154 | sys.exit(exit_val) |
|
154 | sys.exit(exit_val) | |
155 |
|
155 | |||
156 | def info(msg): |
|
156 | def info(msg): | |
157 | """Equivalent to warn(msg,level=1).""" |
|
157 | """Equivalent to warn(msg,level=1).""" | |
158 |
|
158 | |||
159 | warn(msg,level=1) |
|
159 | warn(msg,level=1) | |
160 |
|
160 | |||
161 | def error(msg): |
|
161 | def error(msg): | |
162 | """Equivalent to warn(msg,level=3).""" |
|
162 | """Equivalent to warn(msg,level=3).""" | |
163 |
|
163 | |||
164 | warn(msg,level=3) |
|
164 | warn(msg,level=3) | |
165 |
|
165 | |||
166 | def fatal(msg,exit_val=1): |
|
166 | def fatal(msg,exit_val=1): | |
167 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
167 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" | |
168 |
|
168 | |||
169 | warn(msg,exit_val=exit_val,level=4) |
|
169 | warn(msg,exit_val=exit_val,level=4) | |
170 |
|
170 | |||
171 | #---------------------------------------------------------------------------- |
|
171 | #---------------------------------------------------------------------------- | |
172 | StringTypes = types.StringTypes |
|
172 | StringTypes = types.StringTypes | |
173 |
|
173 | |||
174 | # Basic timing functionality |
|
174 | # Basic timing functionality | |
175 |
|
175 | |||
176 | # If possible (Unix), use the resource module instead of time.clock() |
|
176 | # If possible (Unix), use the resource module instead of time.clock() | |
177 | try: |
|
177 | try: | |
178 | import resource |
|
178 | import resource | |
179 | def clock(): |
|
179 | def clock(): | |
180 | """clock() -> floating point number |
|
180 | """clock() -> floating point number | |
181 |
|
181 | |||
182 | Return the CPU time in seconds (user time only, system time is |
|
182 | Return the CPU time in seconds (user time only, system time is | |
183 | ignored) since the start of the process. This is done via a call to |
|
183 | ignored) since the start of the process. This is done via a call to | |
184 | resource.getrusage, so it avoids the wraparound problems in |
|
184 | resource.getrusage, so it avoids the wraparound problems in | |
185 | time.clock().""" |
|
185 | time.clock().""" | |
186 |
|
186 | |||
187 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
187 | return resource.getrusage(resource.RUSAGE_SELF)[0] | |
188 |
|
188 | |||
189 | def clock2(): |
|
189 | def clock2(): | |
190 | """clock2() -> (t_user,t_system) |
|
190 | """clock2() -> (t_user,t_system) | |
191 |
|
191 | |||
192 | Similar to clock(), but return a tuple of user/system times.""" |
|
192 | Similar to clock(), but return a tuple of user/system times.""" | |
193 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
193 | return resource.getrusage(resource.RUSAGE_SELF)[:2] | |
194 |
|
194 | |||
195 | except ImportError: |
|
195 | except ImportError: | |
196 | clock = time.clock |
|
196 | clock = time.clock | |
197 | def clock2(): |
|
197 | def clock2(): | |
198 | """Under windows, system CPU time can't be measured. |
|
198 | """Under windows, system CPU time can't be measured. | |
199 |
|
199 | |||
200 | This just returns clock() and zero.""" |
|
200 | This just returns clock() and zero.""" | |
201 | return time.clock(),0.0 |
|
201 | return time.clock(),0.0 | |
202 |
|
202 | |||
203 | def timings_out(reps,func,*args,**kw): |
|
203 | def timings_out(reps,func,*args,**kw): | |
204 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
204 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) | |
205 |
|
205 | |||
206 | Execute a function reps times, return a tuple with the elapsed total |
|
206 | Execute a function reps times, return a tuple with the elapsed total | |
207 | CPU time in seconds, the time per call and the function's output. |
|
207 | CPU time in seconds, the time per call and the function's output. | |
208 |
|
208 | |||
209 | Under Unix, the return value is the sum of user+system time consumed by |
|
209 | Under Unix, the return value is the sum of user+system time consumed by | |
210 | the process, computed via the resource module. This prevents problems |
|
210 | the process, computed via the resource module. This prevents problems | |
211 | related to the wraparound effect which the time.clock() function has. |
|
211 | related to the wraparound effect which the time.clock() function has. | |
212 |
|
212 | |||
213 | Under Windows the return value is in wall clock seconds. See the |
|
213 | Under Windows the return value is in wall clock seconds. See the | |
214 | documentation for the time module for more details.""" |
|
214 | documentation for the time module for more details.""" | |
215 |
|
215 | |||
216 | reps = int(reps) |
|
216 | reps = int(reps) | |
217 | assert reps >=1, 'reps must be >= 1' |
|
217 | assert reps >=1, 'reps must be >= 1' | |
218 | if reps==1: |
|
218 | if reps==1: | |
219 | start = clock() |
|
219 | start = clock() | |
220 | out = func(*args,**kw) |
|
220 | out = func(*args,**kw) | |
221 | tot_time = clock()-start |
|
221 | tot_time = clock()-start | |
222 | else: |
|
222 | else: | |
223 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
223 | rng = xrange(reps-1) # the last time is executed separately to store output | |
224 | start = clock() |
|
224 | start = clock() | |
225 | for dummy in rng: func(*args,**kw) |
|
225 | for dummy in rng: func(*args,**kw) | |
226 | out = func(*args,**kw) # one last time |
|
226 | out = func(*args,**kw) # one last time | |
227 | tot_time = clock()-start |
|
227 | tot_time = clock()-start | |
228 | av_time = tot_time / reps |
|
228 | av_time = tot_time / reps | |
229 | return tot_time,av_time,out |
|
229 | return tot_time,av_time,out | |
230 |
|
230 | |||
231 | def timings(reps,func,*args,**kw): |
|
231 | def timings(reps,func,*args,**kw): | |
232 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
232 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) | |
233 |
|
233 | |||
234 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
234 | Execute a function reps times, return a tuple with the elapsed total CPU | |
235 | time in seconds and the time per call. These are just the first two values |
|
235 | time in seconds and the time per call. These are just the first two values | |
236 | in timings_out().""" |
|
236 | in timings_out().""" | |
237 |
|
237 | |||
238 | return timings_out(reps,func,*args,**kw)[0:2] |
|
238 | return timings_out(reps,func,*args,**kw)[0:2] | |
239 |
|
239 | |||
240 | def timing(func,*args,**kw): |
|
240 | def timing(func,*args,**kw): | |
241 | """timing(func,*args,**kw) -> t_total |
|
241 | """timing(func,*args,**kw) -> t_total | |
242 |
|
242 | |||
243 | Execute a function once, return the elapsed total CPU time in |
|
243 | Execute a function once, return the elapsed total CPU time in | |
244 | seconds. This is just the first value in timings_out().""" |
|
244 | seconds. This is just the first value in timings_out().""" | |
245 |
|
245 | |||
246 | return timings_out(1,func,*args,**kw)[0] |
|
246 | return timings_out(1,func,*args,**kw)[0] | |
247 |
|
247 | |||
248 | #**************************************************************************** |
|
248 | #**************************************************************************** | |
249 | # file and system |
|
249 | # file and system | |
250 |
|
250 | |||
251 | def system(cmd,verbose=0,debug=0,header=''): |
|
251 | def system(cmd,verbose=0,debug=0,header=''): | |
252 | """Execute a system command, return its exit status. |
|
252 | """Execute a system command, return its exit status. | |
253 |
|
253 | |||
254 | Options: |
|
254 | Options: | |
255 |
|
255 | |||
256 | - verbose (0): print the command to be executed. |
|
256 | - verbose (0): print the command to be executed. | |
257 |
|
257 | |||
258 | - debug (0): only print, do not actually execute. |
|
258 | - debug (0): only print, do not actually execute. | |
259 |
|
259 | |||
260 | - header (''): Header to print on screen prior to the executed command (it |
|
260 | - header (''): Header to print on screen prior to the executed command (it | |
261 | is only prepended to the command, no newlines are added). |
|
261 | is only prepended to the command, no newlines are added). | |
262 |
|
262 | |||
263 | Note: a stateful version of this function is available through the |
|
263 | Note: a stateful version of this function is available through the | |
264 | SystemExec class.""" |
|
264 | SystemExec class.""" | |
265 |
|
265 | |||
266 | stat = 0 |
|
266 | stat = 0 | |
267 | if verbose or debug: print header+cmd |
|
267 | if verbose or debug: print header+cmd | |
268 | sys.stdout.flush() |
|
268 | sys.stdout.flush() | |
269 | if not debug: stat = os.system(cmd) |
|
269 | if not debug: stat = os.system(cmd) | |
270 | return stat |
|
270 | return stat | |
271 |
|
271 | |||
272 | def shell(cmd,verbose=0,debug=0,header=''): |
|
272 | def shell(cmd,verbose=0,debug=0,header=''): | |
273 | """Execute a command in the system shell, always return None. |
|
273 | """Execute a command in the system shell, always return None. | |
274 |
|
274 | |||
275 | Options: |
|
275 | Options: | |
276 |
|
276 | |||
277 | - verbose (0): print the command to be executed. |
|
277 | - verbose (0): print the command to be executed. | |
278 |
|
278 | |||
279 | - debug (0): only print, do not actually execute. |
|
279 | - debug (0): only print, do not actually execute. | |
280 |
|
280 | |||
281 | - header (''): Header to print on screen prior to the executed command (it |
|
281 | - header (''): Header to print on screen prior to the executed command (it | |
282 | is only prepended to the command, no newlines are added). |
|
282 | is only prepended to the command, no newlines are added). | |
283 |
|
283 | |||
284 | Note: this is similar to genutils.system(), but it returns None so it can |
|
284 | Note: this is similar to genutils.system(), but it returns None so it can | |
285 | be conveniently used in interactive loops without getting the return value |
|
285 | be conveniently used in interactive loops without getting the return value | |
286 | (typically 0) printed many times.""" |
|
286 | (typically 0) printed many times.""" | |
287 |
|
287 | |||
288 | stat = 0 |
|
288 | stat = 0 | |
289 | if verbose or debug: print header+cmd |
|
289 | if verbose or debug: print header+cmd | |
290 | # flush stdout so we don't mangle python's buffering |
|
290 | # flush stdout so we don't mangle python's buffering | |
291 | sys.stdout.flush() |
|
291 | sys.stdout.flush() | |
292 | if not debug: |
|
292 | if not debug: | |
293 | os.system(cmd) |
|
293 | os.system(cmd) | |
294 |
|
294 | |||
295 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
295 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): | |
296 | """Dummy substitute for perl's backquotes. |
|
296 | """Dummy substitute for perl's backquotes. | |
297 |
|
297 | |||
298 | Executes a command and returns the output. |
|
298 | Executes a command and returns the output. | |
299 |
|
299 | |||
300 | Accepts the same arguments as system(), plus: |
|
300 | Accepts the same arguments as system(), plus: | |
301 |
|
301 | |||
302 | - split(0): if true, the output is returned as a list split on newlines. |
|
302 | - split(0): if true, the output is returned as a list split on newlines. | |
303 |
|
303 | |||
304 | Note: a stateful version of this function is available through the |
|
304 | Note: a stateful version of this function is available through the | |
305 | SystemExec class.""" |
|
305 | SystemExec class.""" | |
306 |
|
306 | |||
307 | if verbose or debug: print header+cmd |
|
307 | if verbose or debug: print header+cmd | |
308 | if not debug: |
|
308 | if not debug: | |
309 | output = commands.getoutput(cmd) |
|
309 | output = commands.getoutput(cmd) | |
310 | if split: |
|
310 | if split: | |
311 | return output.split('\n') |
|
311 | return output.split('\n') | |
312 | else: |
|
312 | else: | |
313 | return output |
|
313 | return output | |
314 |
|
314 | |||
315 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
315 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): | |
316 | """Return (standard output,standard error) of executing cmd in a shell. |
|
316 | """Return (standard output,standard error) of executing cmd in a shell. | |
317 |
|
317 | |||
318 | Accepts the same arguments as system(), plus: |
|
318 | Accepts the same arguments as system(), plus: | |
319 |
|
319 | |||
320 | - split(0): if true, each of stdout/err is returned as a list split on |
|
320 | - split(0): if true, each of stdout/err is returned as a list split on | |
321 | newlines. |
|
321 | newlines. | |
322 |
|
322 | |||
323 | Note: a stateful version of this function is available through the |
|
323 | Note: a stateful version of this function is available through the | |
324 | SystemExec class.""" |
|
324 | SystemExec class.""" | |
325 |
|
325 | |||
326 | if verbose or debug: print header+cmd |
|
326 | if verbose or debug: print header+cmd | |
327 | if not cmd: |
|
327 | if not cmd: | |
328 | if split: |
|
328 | if split: | |
329 | return [],[] |
|
329 | return [],[] | |
330 | else: |
|
330 | else: | |
331 | return '','' |
|
331 | return '','' | |
332 | if not debug: |
|
332 | if not debug: | |
333 | pin,pout,perr = os.popen3(cmd) |
|
333 | pin,pout,perr = os.popen3(cmd) | |
334 | tout = pout.read().rstrip() |
|
334 | tout = pout.read().rstrip() | |
335 | terr = perr.read().rstrip() |
|
335 | terr = perr.read().rstrip() | |
336 | pin.close() |
|
336 | pin.close() | |
337 | pout.close() |
|
337 | pout.close() | |
338 | perr.close() |
|
338 | perr.close() | |
339 | if split: |
|
339 | if split: | |
340 | return tout.split('\n'),terr.split('\n') |
|
340 | return tout.split('\n'),terr.split('\n') | |
341 | else: |
|
341 | else: | |
342 | return tout,terr |
|
342 | return tout,terr | |
343 |
|
343 | |||
344 | # for compatibility with older naming conventions |
|
344 | # for compatibility with older naming conventions | |
345 | xsys = system |
|
345 | xsys = system | |
346 | bq = getoutput |
|
346 | bq = getoutput | |
347 |
|
347 | |||
348 | class SystemExec: |
|
348 | class SystemExec: | |
349 | """Access the system and getoutput functions through a stateful interface. |
|
349 | """Access the system and getoutput functions through a stateful interface. | |
350 |
|
350 | |||
351 | Note: here we refer to the system and getoutput functions from this |
|
351 | Note: here we refer to the system and getoutput functions from this | |
352 | library, not the ones from the standard python library. |
|
352 | library, not the ones from the standard python library. | |
353 |
|
353 | |||
354 | This class offers the system and getoutput functions as methods, but the |
|
354 | This class offers the system and getoutput functions as methods, but the | |
355 | verbose, debug and header parameters can be set for the instance (at |
|
355 | verbose, debug and header parameters can be set for the instance (at | |
356 | creation time or later) so that they don't need to be specified on each |
|
356 | creation time or later) so that they don't need to be specified on each | |
357 | call. |
|
357 | call. | |
358 |
|
358 | |||
359 | For efficiency reasons, there's no way to override the parameters on a |
|
359 | For efficiency reasons, there's no way to override the parameters on a | |
360 | per-call basis other than by setting instance attributes. If you need |
|
360 | per-call basis other than by setting instance attributes. If you need | |
361 | local overrides, it's best to directly call system() or getoutput(). |
|
361 | local overrides, it's best to directly call system() or getoutput(). | |
362 |
|
362 | |||
363 | The following names are provided as alternate options: |
|
363 | The following names are provided as alternate options: | |
364 | - xsys: alias to system |
|
364 | - xsys: alias to system | |
365 | - bq: alias to getoutput |
|
365 | - bq: alias to getoutput | |
366 |
|
366 | |||
367 | An instance can then be created as: |
|
367 | An instance can then be created as: | |
368 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
368 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') | |
369 |
|
369 | |||
370 | And used as: |
|
370 | And used as: | |
371 | >>> sysexec.xsys('pwd') |
|
371 | >>> sysexec.xsys('pwd') | |
372 | >>> dirlist = sysexec.bq('ls -l') |
|
372 | >>> dirlist = sysexec.bq('ls -l') | |
373 | """ |
|
373 | """ | |
374 |
|
374 | |||
375 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
375 | def __init__(self,verbose=0,debug=0,header='',split=0): | |
376 | """Specify the instance's values for verbose, debug and header.""" |
|
376 | """Specify the instance's values for verbose, debug and header.""" | |
377 | setattr_list(self,'verbose debug header split') |
|
377 | setattr_list(self,'verbose debug header split') | |
378 |
|
378 | |||
379 | def system(self,cmd): |
|
379 | def system(self,cmd): | |
380 | """Stateful interface to system(), with the same keyword parameters.""" |
|
380 | """Stateful interface to system(), with the same keyword parameters.""" | |
381 |
|
381 | |||
382 | system(cmd,self.verbose,self.debug,self.header) |
|
382 | system(cmd,self.verbose,self.debug,self.header) | |
383 |
|
383 | |||
384 | def shell(self,cmd): |
|
384 | def shell(self,cmd): | |
385 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
385 | """Stateful interface to shell(), with the same keyword parameters.""" | |
386 |
|
386 | |||
387 | shell(cmd,self.verbose,self.debug,self.header) |
|
387 | shell(cmd,self.verbose,self.debug,self.header) | |
388 |
|
388 | |||
389 | xsys = system # alias |
|
389 | xsys = system # alias | |
390 |
|
390 | |||
391 | def getoutput(self,cmd): |
|
391 | def getoutput(self,cmd): | |
392 | """Stateful interface to getoutput().""" |
|
392 | """Stateful interface to getoutput().""" | |
393 |
|
393 | |||
394 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
394 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) | |
395 |
|
395 | |||
396 | def getoutputerror(self,cmd): |
|
396 | def getoutputerror(self,cmd): | |
397 | """Stateful interface to getoutputerror().""" |
|
397 | """Stateful interface to getoutputerror().""" | |
398 |
|
398 | |||
399 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
399 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) | |
400 |
|
400 | |||
401 | bq = getoutput # alias |
|
401 | bq = getoutput # alias | |
402 |
|
402 | |||
403 | #----------------------------------------------------------------------------- |
|
403 | #----------------------------------------------------------------------------- | |
404 | def mutex_opts(dict,ex_op): |
|
404 | def mutex_opts(dict,ex_op): | |
405 | """Check for presence of mutually exclusive keys in a dict. |
|
405 | """Check for presence of mutually exclusive keys in a dict. | |
406 |
|
406 | |||
407 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
407 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" | |
408 | for op1,op2 in ex_op: |
|
408 | for op1,op2 in ex_op: | |
409 | if op1 in dict and op2 in dict: |
|
409 | if op1 in dict and op2 in dict: | |
410 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
410 | raise ValueError,'\n*** ERROR in Arguments *** '\ | |
411 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
411 | 'Options '+op1+' and '+op2+' are mutually exclusive.' | |
412 |
|
412 | |||
413 | #----------------------------------------------------------------------------- |
|
413 | #----------------------------------------------------------------------------- | |
414 | def filefind(fname,alt_dirs = None): |
|
414 | def filefind(fname,alt_dirs = None): | |
415 | """Return the given filename either in the current directory, if it |
|
415 | """Return the given filename either in the current directory, if it | |
416 | exists, or in a specified list of directories. |
|
416 | exists, or in a specified list of directories. | |
417 |
|
417 | |||
418 | ~ expansion is done on all file and directory names. |
|
418 | ~ expansion is done on all file and directory names. | |
419 |
|
419 | |||
420 | Upon an unsuccessful search, raise an IOError exception.""" |
|
420 | Upon an unsuccessful search, raise an IOError exception.""" | |
421 |
|
421 | |||
422 | if alt_dirs is None: |
|
422 | if alt_dirs is None: | |
423 | try: |
|
423 | try: | |
424 | alt_dirs = get_home_dir() |
|
424 | alt_dirs = get_home_dir() | |
425 | except HomeDirError: |
|
425 | except HomeDirError: | |
426 | alt_dirs = os.getcwd() |
|
426 | alt_dirs = os.getcwd() | |
427 | search = [fname] + list_strings(alt_dirs) |
|
427 | search = [fname] + list_strings(alt_dirs) | |
428 | search = map(os.path.expanduser,search) |
|
428 | search = map(os.path.expanduser,search) | |
429 | #print 'search list for',fname,'list:',search # dbg |
|
429 | #print 'search list for',fname,'list:',search # dbg | |
430 | fname = search[0] |
|
430 | fname = search[0] | |
431 | if os.path.isfile(fname): |
|
431 | if os.path.isfile(fname): | |
432 | return fname |
|
432 | return fname | |
433 | for direc in search[1:]: |
|
433 | for direc in search[1:]: | |
434 | testname = os.path.join(direc,fname) |
|
434 | testname = os.path.join(direc,fname) | |
435 | #print 'testname',testname # dbg |
|
435 | #print 'testname',testname # dbg | |
436 | if os.path.isfile(testname): |
|
436 | if os.path.isfile(testname): | |
437 | return testname |
|
437 | return testname | |
438 | raise IOError,'File' + `fname` + \ |
|
438 | raise IOError,'File' + `fname` + \ | |
439 | ' not found in current or supplied directories:' + `alt_dirs` |
|
439 | ' not found in current or supplied directories:' + `alt_dirs` | |
440 |
|
440 | |||
441 | #---------------------------------------------------------------------------- |
|
441 | #---------------------------------------------------------------------------- | |
442 | def target_outdated(target,deps): |
|
442 | def target_outdated(target,deps): | |
443 | """Determine whether a target is out of date. |
|
443 | """Determine whether a target is out of date. | |
444 |
|
444 | |||
445 | target_outdated(target,deps) -> 1/0 |
|
445 | target_outdated(target,deps) -> 1/0 | |
446 |
|
446 | |||
447 | deps: list of filenames which MUST exist. |
|
447 | deps: list of filenames which MUST exist. | |
448 | target: single filename which may or may not exist. |
|
448 | target: single filename which may or may not exist. | |
449 |
|
449 | |||
450 | If target doesn't exist or is older than any file listed in deps, return |
|
450 | If target doesn't exist or is older than any file listed in deps, return | |
451 | true, otherwise return false. |
|
451 | true, otherwise return false. | |
452 | """ |
|
452 | """ | |
453 | try: |
|
453 | try: | |
454 | target_time = os.path.getmtime(target) |
|
454 | target_time = os.path.getmtime(target) | |
455 | except os.error: |
|
455 | except os.error: | |
456 | return 1 |
|
456 | return 1 | |
457 | for dep in deps: |
|
457 | for dep in deps: | |
458 | dep_time = os.path.getmtime(dep) |
|
458 | dep_time = os.path.getmtime(dep) | |
459 | if dep_time > target_time: |
|
459 | if dep_time > target_time: | |
460 | #print "For target",target,"Dep failed:",dep # dbg |
|
460 | #print "For target",target,"Dep failed:",dep # dbg | |
461 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
461 | #print "times (dep,tar):",dep_time,target_time # dbg | |
462 | return 1 |
|
462 | return 1 | |
463 | return 0 |
|
463 | return 0 | |
464 |
|
464 | |||
465 | #----------------------------------------------------------------------------- |
|
465 | #----------------------------------------------------------------------------- | |
466 | def target_update(target,deps,cmd): |
|
466 | def target_update(target,deps,cmd): | |
467 | """Update a target with a given command given a list of dependencies. |
|
467 | """Update a target with a given command given a list of dependencies. | |
468 |
|
468 | |||
469 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
469 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
470 |
|
470 | |||
471 | This is just a wrapper around target_outdated() which calls the given |
|
471 | This is just a wrapper around target_outdated() which calls the given | |
472 | command if target is outdated.""" |
|
472 | command if target is outdated.""" | |
473 |
|
473 | |||
474 | if target_outdated(target,deps): |
|
474 | if target_outdated(target,deps): | |
475 | xsys(cmd) |
|
475 | xsys(cmd) | |
476 |
|
476 | |||
477 | #---------------------------------------------------------------------------- |
|
477 | #---------------------------------------------------------------------------- | |
478 | def unquote_ends(istr): |
|
478 | def unquote_ends(istr): | |
479 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
479 | """Remove a single pair of quotes from the endpoints of a string.""" | |
480 |
|
480 | |||
481 | if not istr: |
|
481 | if not istr: | |
482 | return istr |
|
482 | return istr | |
483 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
483 | if (istr[0]=="'" and istr[-1]=="'") or \ | |
484 | (istr[0]=='"' and istr[-1]=='"'): |
|
484 | (istr[0]=='"' and istr[-1]=='"'): | |
485 | return istr[1:-1] |
|
485 | return istr[1:-1] | |
486 | else: |
|
486 | else: | |
487 | return istr |
|
487 | return istr | |
488 |
|
488 | |||
489 | #---------------------------------------------------------------------------- |
|
489 | #---------------------------------------------------------------------------- | |
490 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
490 | def process_cmdline(argv,names=[],defaults={},usage=''): | |
491 | """ Process command-line options and arguments. |
|
491 | """ Process command-line options and arguments. | |
492 |
|
492 | |||
493 | Arguments: |
|
493 | Arguments: | |
494 |
|
494 | |||
495 | - argv: list of arguments, typically sys.argv. |
|
495 | - argv: list of arguments, typically sys.argv. | |
496 |
|
496 | |||
497 | - names: list of option names. See DPyGetOpt docs for details on options |
|
497 | - names: list of option names. See DPyGetOpt docs for details on options | |
498 | syntax. |
|
498 | syntax. | |
499 |
|
499 | |||
500 | - defaults: dict of default values. |
|
500 | - defaults: dict of default values. | |
501 |
|
501 | |||
502 | - usage: optional usage notice to print if a wrong argument is passed. |
|
502 | - usage: optional usage notice to print if a wrong argument is passed. | |
503 |
|
503 | |||
504 | Return a dict of options and a list of free arguments.""" |
|
504 | Return a dict of options and a list of free arguments.""" | |
505 |
|
505 | |||
506 | getopt = DPyGetOpt.DPyGetOpt() |
|
506 | getopt = DPyGetOpt.DPyGetOpt() | |
507 | getopt.setIgnoreCase(0) |
|
507 | getopt.setIgnoreCase(0) | |
508 | getopt.parseConfiguration(names) |
|
508 | getopt.parseConfiguration(names) | |
509 |
|
509 | |||
510 | try: |
|
510 | try: | |
511 | getopt.processArguments(argv) |
|
511 | getopt.processArguments(argv) | |
512 | except: |
|
512 | except: | |
513 | print usage |
|
513 | print usage | |
514 | warn(`sys.exc_value`,level=4) |
|
514 | warn(`sys.exc_value`,level=4) | |
515 |
|
515 | |||
516 | defaults.update(getopt.optionValues) |
|
516 | defaults.update(getopt.optionValues) | |
517 | args = getopt.freeValues |
|
517 | args = getopt.freeValues | |
518 |
|
518 | |||
519 | return defaults,args |
|
519 | return defaults,args | |
520 |
|
520 | |||
521 | #---------------------------------------------------------------------------- |
|
521 | #---------------------------------------------------------------------------- | |
522 | def optstr2types(ostr): |
|
522 | def optstr2types(ostr): | |
523 | """Convert a string of option names to a dict of type mappings. |
|
523 | """Convert a string of option names to a dict of type mappings. | |
524 |
|
524 | |||
525 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
525 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} | |
526 |
|
526 | |||
527 | This is used to get the types of all the options in a string formatted |
|
527 | This is used to get the types of all the options in a string formatted | |
528 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
528 | with the conventions of DPyGetOpt. The 'type' None is used for options | |
529 | which are strings (they need no further conversion). This function's main |
|
529 | which are strings (they need no further conversion). This function's main | |
530 | use is to get a typemap for use with read_dict(). |
|
530 | use is to get a typemap for use with read_dict(). | |
531 | """ |
|
531 | """ | |
532 |
|
532 | |||
533 | typeconv = {None:'',int:'',float:''} |
|
533 | typeconv = {None:'',int:'',float:''} | |
534 | typemap = {'s':None,'i':int,'f':float} |
|
534 | typemap = {'s':None,'i':int,'f':float} | |
535 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
535 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') | |
536 |
|
536 | |||
537 | for w in ostr.split(): |
|
537 | for w in ostr.split(): | |
538 | oname,alias,otype = opt_re.match(w).groups() |
|
538 | oname,alias,otype = opt_re.match(w).groups() | |
539 | if otype == '' or alias == '!': # simple switches are integers too |
|
539 | if otype == '' or alias == '!': # simple switches are integers too | |
540 | otype = 'i' |
|
540 | otype = 'i' | |
541 | typeconv[typemap[otype]] += oname + ' ' |
|
541 | typeconv[typemap[otype]] += oname + ' ' | |
542 | return typeconv |
|
542 | return typeconv | |
543 |
|
543 | |||
544 | #---------------------------------------------------------------------------- |
|
544 | #---------------------------------------------------------------------------- | |
545 | def read_dict(filename,type_conv=None,**opt): |
|
545 | def read_dict(filename,type_conv=None,**opt): | |
546 |
|
546 | |||
547 | """Read a dictionary of key=value pairs from an input file, optionally |
|
547 | """Read a dictionary of key=value pairs from an input file, optionally | |
548 | performing conversions on the resulting values. |
|
548 | performing conversions on the resulting values. | |
549 |
|
549 | |||
550 | read_dict(filename,type_conv,**opt) -> dict |
|
550 | read_dict(filename,type_conv,**opt) -> dict | |
551 |
|
551 | |||
552 | Only one value per line is accepted, the format should be |
|
552 | Only one value per line is accepted, the format should be | |
553 | # optional comments are ignored |
|
553 | # optional comments are ignored | |
554 | key value\n |
|
554 | key value\n | |
555 |
|
555 | |||
556 | Args: |
|
556 | Args: | |
557 |
|
557 | |||
558 | - type_conv: A dictionary specifying which keys need to be converted to |
|
558 | - type_conv: A dictionary specifying which keys need to be converted to | |
559 | which types. By default all keys are read as strings. This dictionary |
|
559 | which types. By default all keys are read as strings. This dictionary | |
560 | should have as its keys valid conversion functions for strings |
|
560 | should have as its keys valid conversion functions for strings | |
561 | (int,long,float,complex, or your own). The value for each key |
|
561 | (int,long,float,complex, or your own). The value for each key | |
562 | (converter) should be a whitespace separated string containing the names |
|
562 | (converter) should be a whitespace separated string containing the names | |
563 | of all the entries in the file to be converted using that function. For |
|
563 | of all the entries in the file to be converted using that function. For | |
564 | keys to be left alone, use None as the conversion function (only needed |
|
564 | keys to be left alone, use None as the conversion function (only needed | |
565 | with purge=1, see below). |
|
565 | with purge=1, see below). | |
566 |
|
566 | |||
567 | - opt: dictionary with extra options as below (default in parens) |
|
567 | - opt: dictionary with extra options as below (default in parens) | |
568 |
|
568 | |||
569 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
569 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out | |
570 | of the dictionary to be returned. If purge is going to be used, the |
|
570 | of the dictionary to be returned. If purge is going to be used, the | |
571 | set of keys to be left as strings also has to be explicitly specified |
|
571 | set of keys to be left as strings also has to be explicitly specified | |
572 | using the (non-existent) conversion function None. |
|
572 | using the (non-existent) conversion function None. | |
573 |
|
573 | |||
574 | fs(None): field separator. This is the key/value separator to be used |
|
574 | fs(None): field separator. This is the key/value separator to be used | |
575 | when parsing the file. The None default means any whitespace [behavior |
|
575 | when parsing the file. The None default means any whitespace [behavior | |
576 | of string.split()]. |
|
576 | of string.split()]. | |
577 |
|
577 | |||
578 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
578 | strip(0): if 1, strip string values of leading/trailinig whitespace. | |
579 |
|
579 | |||
580 | warn(1): warning level if requested keys are not found in file. |
|
580 | warn(1): warning level if requested keys are not found in file. | |
581 | - 0: silently ignore. |
|
581 | - 0: silently ignore. | |
582 | - 1: inform but proceed. |
|
582 | - 1: inform but proceed. | |
583 | - 2: raise KeyError exception. |
|
583 | - 2: raise KeyError exception. | |
584 |
|
584 | |||
585 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
585 | no_empty(0): if 1, remove keys with whitespace strings as a value. | |
586 |
|
586 | |||
587 | unique([]): list of keys (or space separated string) which can't be |
|
587 | unique([]): list of keys (or space separated string) which can't be | |
588 | repeated. If one such key is found in the file, each new instance |
|
588 | repeated. If one such key is found in the file, each new instance | |
589 | overwrites the previous one. For keys not listed here, the behavior is |
|
589 | overwrites the previous one. For keys not listed here, the behavior is | |
590 | to make a list of all appearances. |
|
590 | to make a list of all appearances. | |
591 |
|
591 | |||
592 | Example: |
|
592 | Example: | |
593 | If the input file test.ini has: |
|
593 | If the input file test.ini has: | |
594 | i 3 |
|
594 | i 3 | |
595 | x 4.5 |
|
595 | x 4.5 | |
596 | y 5.5 |
|
596 | y 5.5 | |
597 | s hi ho |
|
597 | s hi ho | |
598 | Then: |
|
598 | Then: | |
599 |
|
599 | |||
600 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
600 | >>> type_conv={int:'i',float:'x',None:'s'} | |
601 | >>> read_dict('test.ini') |
|
601 | >>> read_dict('test.ini') | |
602 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} |
|
602 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} | |
603 | >>> read_dict('test.ini',type_conv) |
|
603 | >>> read_dict('test.ini',type_conv) | |
604 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} |
|
604 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} | |
605 | >>> read_dict('test.ini',type_conv,purge=1) |
|
605 | >>> read_dict('test.ini',type_conv,purge=1) | |
606 | {'i': 3, 's': 'hi ho', 'x': 4.5} |
|
606 | {'i': 3, 's': 'hi ho', 'x': 4.5} | |
607 | """ |
|
607 | """ | |
608 |
|
608 | |||
609 | # starting config |
|
609 | # starting config | |
610 | opt.setdefault('purge',0) |
|
610 | opt.setdefault('purge',0) | |
611 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
611 | opt.setdefault('fs',None) # field sep defaults to any whitespace | |
612 | opt.setdefault('strip',0) |
|
612 | opt.setdefault('strip',0) | |
613 | opt.setdefault('warn',1) |
|
613 | opt.setdefault('warn',1) | |
614 | opt.setdefault('no_empty',0) |
|
614 | opt.setdefault('no_empty',0) | |
615 | opt.setdefault('unique','') |
|
615 | opt.setdefault('unique','') | |
616 | if type(opt['unique']) in StringTypes: |
|
616 | if type(opt['unique']) in StringTypes: | |
617 | unique_keys = qw(opt['unique']) |
|
617 | unique_keys = qw(opt['unique']) | |
618 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
618 | elif type(opt['unique']) in (types.TupleType,types.ListType): | |
619 | unique_keys = opt['unique'] |
|
619 | unique_keys = opt['unique'] | |
620 | else: |
|
620 | else: | |
621 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
621 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' | |
622 |
|
622 | |||
623 | dict = {} |
|
623 | dict = {} | |
624 | # first read in table of values as strings |
|
624 | # first read in table of values as strings | |
625 | file = open(filename,'r') |
|
625 | file = open(filename,'r') | |
626 | for line in file.readlines(): |
|
626 | for line in file.readlines(): | |
627 | line = line.strip() |
|
627 | line = line.strip() | |
628 | if len(line) and line[0]=='#': continue |
|
628 | if len(line) and line[0]=='#': continue | |
629 | if len(line)>0: |
|
629 | if len(line)>0: | |
630 | lsplit = line.split(opt['fs'],1) |
|
630 | lsplit = line.split(opt['fs'],1) | |
631 | try: |
|
631 | try: | |
632 | key,val = lsplit |
|
632 | key,val = lsplit | |
633 | except ValueError: |
|
633 | except ValueError: | |
634 | key,val = lsplit[0],'' |
|
634 | key,val = lsplit[0],'' | |
635 | key = key.strip() |
|
635 | key = key.strip() | |
636 | if opt['strip']: val = val.strip() |
|
636 | if opt['strip']: val = val.strip() | |
637 | if val == "''" or val == '""': val = '' |
|
637 | if val == "''" or val == '""': val = '' | |
638 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
638 | if opt['no_empty'] and (val=='' or val.isspace()): | |
639 | continue |
|
639 | continue | |
640 | # if a key is found more than once in the file, build a list |
|
640 | # if a key is found more than once in the file, build a list | |
641 | # unless it's in the 'unique' list. In that case, last found in file |
|
641 | # unless it's in the 'unique' list. In that case, last found in file | |
642 | # takes precedence. User beware. |
|
642 | # takes precedence. User beware. | |
643 | try: |
|
643 | try: | |
644 | if dict[key] and key in unique_keys: |
|
644 | if dict[key] and key in unique_keys: | |
645 | dict[key] = val |
|
645 | dict[key] = val | |
646 | elif type(dict[key]) is types.ListType: |
|
646 | elif type(dict[key]) is types.ListType: | |
647 | dict[key].append(val) |
|
647 | dict[key].append(val) | |
648 | else: |
|
648 | else: | |
649 | dict[key] = [dict[key],val] |
|
649 | dict[key] = [dict[key],val] | |
650 | except KeyError: |
|
650 | except KeyError: | |
651 | dict[key] = val |
|
651 | dict[key] = val | |
652 | # purge if requested |
|
652 | # purge if requested | |
653 | if opt['purge']: |
|
653 | if opt['purge']: | |
654 | accepted_keys = qwflat(type_conv.values()) |
|
654 | accepted_keys = qwflat(type_conv.values()) | |
655 | for key in dict.keys(): |
|
655 | for key in dict.keys(): | |
656 | if key in accepted_keys: continue |
|
656 | if key in accepted_keys: continue | |
657 | del(dict[key]) |
|
657 | del(dict[key]) | |
658 | # now convert if requested |
|
658 | # now convert if requested | |
659 | if type_conv==None: return dict |
|
659 | if type_conv==None: return dict | |
660 | conversions = type_conv.keys() |
|
660 | conversions = type_conv.keys() | |
661 | try: conversions.remove(None) |
|
661 | try: conversions.remove(None) | |
662 | except: pass |
|
662 | except: pass | |
663 | for convert in conversions: |
|
663 | for convert in conversions: | |
664 | for val in qw(type_conv[convert]): |
|
664 | for val in qw(type_conv[convert]): | |
665 | try: |
|
665 | try: | |
666 | dict[val] = convert(dict[val]) |
|
666 | dict[val] = convert(dict[val]) | |
667 | except KeyError,e: |
|
667 | except KeyError,e: | |
668 | if opt['warn'] == 0: |
|
668 | if opt['warn'] == 0: | |
669 | pass |
|
669 | pass | |
670 | elif opt['warn'] == 1: |
|
670 | elif opt['warn'] == 1: | |
671 | print >>sys.stderr, 'Warning: key',val,\ |
|
671 | print >>sys.stderr, 'Warning: key',val,\ | |
672 | 'not found in file',filename |
|
672 | 'not found in file',filename | |
673 | elif opt['warn'] == 2: |
|
673 | elif opt['warn'] == 2: | |
674 | raise KeyError,e |
|
674 | raise KeyError,e | |
675 | else: |
|
675 | else: | |
676 | raise ValueError,'Warning level must be 0,1 or 2' |
|
676 | raise ValueError,'Warning level must be 0,1 or 2' | |
677 |
|
677 | |||
678 | return dict |
|
678 | return dict | |
679 |
|
679 | |||
680 | #---------------------------------------------------------------------------- |
|
680 | #---------------------------------------------------------------------------- | |
681 | def flag_calls(func): |
|
681 | def flag_calls(func): | |
682 | """Wrap a function to detect and flag when it gets called. |
|
682 | """Wrap a function to detect and flag when it gets called. | |
683 |
|
683 | |||
684 | This is a decorator which takes a function and wraps it in a function with |
|
684 | This is a decorator which takes a function and wraps it in a function with | |
685 | a 'called' attribute. wrapper.called is initialized to False. |
|
685 | a 'called' attribute. wrapper.called is initialized to False. | |
686 |
|
686 | |||
687 | The wrapper.called attribute is set to False right before each call to the |
|
687 | The wrapper.called attribute is set to False right before each call to the | |
688 | wrapped function, so if the call fails it remains False. After the call |
|
688 | wrapped function, so if the call fails it remains False. After the call | |
689 | completes, wrapper.called is set to True and the output is returned. |
|
689 | completes, wrapper.called is set to True and the output is returned. | |
690 |
|
690 | |||
691 | Testing for truth in wrapper.called allows you to determine if a call to |
|
691 | Testing for truth in wrapper.called allows you to determine if a call to | |
692 | func() was attempted and succeeded.""" |
|
692 | func() was attempted and succeeded.""" | |
693 |
|
693 | |||
694 | def wrapper(*args,**kw): |
|
694 | def wrapper(*args,**kw): | |
695 | wrapper.called = False |
|
695 | wrapper.called = False | |
696 | out = func(*args,**kw) |
|
696 | out = func(*args,**kw) | |
697 | wrapper.called = True |
|
697 | wrapper.called = True | |
698 | return out |
|
698 | return out | |
699 |
|
699 | |||
700 | wrapper.called = False |
|
700 | wrapper.called = False | |
701 | wrapper.__doc__ = func.__doc__ |
|
701 | wrapper.__doc__ = func.__doc__ | |
702 | return wrapper |
|
702 | return wrapper | |
703 |
|
703 | |||
704 | #---------------------------------------------------------------------------- |
|
704 | #---------------------------------------------------------------------------- | |
705 | class HomeDirError(Error): |
|
705 | class HomeDirError(Error): | |
706 | pass |
|
706 | pass | |
707 |
|
707 | |||
708 | def get_home_dir(): |
|
708 | def get_home_dir(): | |
709 | """Return the closest possible equivalent to a 'home' directory. |
|
709 | """Return the closest possible equivalent to a 'home' directory. | |
710 |
|
710 | |||
711 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
711 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. | |
712 |
|
712 | |||
713 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
713 | Currently only Posix and NT are implemented, a HomeDirError exception is | |
714 |
raised for all other OSes. """ |
|
714 | raised for all other OSes. """ | |
715 |
|
715 | |||
716 | try: |
|
716 | try: | |
717 | return os.environ['HOME'] |
|
717 | return os.environ['HOME'] | |
718 | except KeyError: |
|
718 | except KeyError: | |
719 | if os.name == 'posix': |
|
719 | if os.name == 'posix': | |
720 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
720 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' | |
721 | elif os.name == 'nt': |
|
721 | elif os.name == 'nt': | |
722 | # For some strange reason, win9x returns 'nt' for os.name. |
|
722 | # For some strange reason, win9x returns 'nt' for os.name. | |
723 | try: |
|
723 | try: | |
724 | return os.path.join(os.environ['HOMEDRIVE'],os.environ['HOMEPATH']) |
|
724 | return os.path.join(os.environ['HOMEDRIVE'],os.environ['HOMEPATH']) | |
725 | except: |
|
725 | except: | |
726 | try: |
|
726 | try: | |
727 | # Use the registry to get the 'My Documents' folder. |
|
727 | # Use the registry to get the 'My Documents' folder. | |
728 | import _winreg as wreg |
|
728 | import _winreg as wreg | |
729 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
729 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, | |
730 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
730 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") | |
731 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
731 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
732 | key.Close() |
|
732 | key.Close() | |
733 | return homedir |
|
733 | return homedir | |
734 | except: |
|
734 | except: | |
735 | return 'C:\\' |
|
735 | return 'C:\\' | |
736 | elif os.name == 'dos': |
|
736 | elif os.name == 'dos': | |
737 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
737 | # Desperate, may do absurd things in classic MacOS. May work under DOS. | |
738 | return 'C:\\' |
|
738 | return 'C:\\' | |
739 | else: |
|
739 | else: | |
740 | raise HomeDirError,'support for your operating system not implemented.' |
|
740 | raise HomeDirError,'support for your operating system not implemented.' | |
741 |
|
741 | |||
742 | #**************************************************************************** |
|
742 | #**************************************************************************** | |
743 | # strings and text |
|
743 | # strings and text | |
744 |
|
744 | |||
745 | class LSString(str): |
|
745 | class LSString(str): | |
746 | """String derivative with a special access attributes. |
|
746 | """String derivative with a special access attributes. | |
747 |
|
747 | |||
748 | These are normal strings, but with the special attributes: |
|
748 | These are normal strings, but with the special attributes: | |
749 |
|
749 | |||
750 | .l (or .list) : value as list (split on newlines). |
|
750 | .l (or .list) : value as list (split on newlines). | |
751 | .n (or .nlstr): original value (the string itself). |
|
751 | .n (or .nlstr): original value (the string itself). | |
752 | .s (or .spstr): value as whitespace-separated string. |
|
752 | .s (or .spstr): value as whitespace-separated string. | |
753 |
|
753 | |||
754 | Any values which require transformations are computed only once and |
|
754 | Any values which require transformations are computed only once and | |
755 | cached. |
|
755 | cached. | |
756 |
|
756 | |||
757 | Such strings are very useful to efficiently interact with the shell, which |
|
757 | Such strings are very useful to efficiently interact with the shell, which | |
758 | typically only understands whitespace-separated options for commands.""" |
|
758 | typically only understands whitespace-separated options for commands.""" | |
759 |
|
759 | |||
760 | def get_list(self): |
|
760 | def get_list(self): | |
761 | try: |
|
761 | try: | |
762 | return self.__list |
|
762 | return self.__list | |
763 | except AttributeError: |
|
763 | except AttributeError: | |
764 | self.__list = self.split('\n') |
|
764 | self.__list = self.split('\n') | |
765 | return self.__list |
|
765 | return self.__list | |
766 |
|
766 | |||
767 | l = list = property(get_list) |
|
767 | l = list = property(get_list) | |
768 |
|
768 | |||
769 | def get_spstr(self): |
|
769 | def get_spstr(self): | |
770 | try: |
|
770 | try: | |
771 | return self.__spstr |
|
771 | return self.__spstr | |
772 | except AttributeError: |
|
772 | except AttributeError: | |
773 | self.__spstr = self.replace('\n',' ') |
|
773 | self.__spstr = self.replace('\n',' ') | |
774 | return self.__spstr |
|
774 | return self.__spstr | |
775 |
|
775 | |||
776 | s = spstr = property(get_spstr) |
|
776 | s = spstr = property(get_spstr) | |
777 |
|
777 | |||
778 | def get_nlstr(self): |
|
778 | def get_nlstr(self): | |
779 | return self |
|
779 | return self | |
780 |
|
780 | |||
781 | n = nlstr = property(get_nlstr) |
|
781 | n = nlstr = property(get_nlstr) | |
782 |
|
782 | |||
783 | class SList(list): |
|
783 | class SList(list): | |
784 | """List derivative with a special access attributes. |
|
784 | """List derivative with a special access attributes. | |
785 |
|
785 | |||
786 | These are normal lists, but with the special attributes: |
|
786 | These are normal lists, but with the special attributes: | |
787 |
|
787 | |||
788 | .l (or .list) : value as list (the list itself). |
|
788 | .l (or .list) : value as list (the list itself). | |
789 | .n (or .nlstr): value as a string, joined on newlines. |
|
789 | .n (or .nlstr): value as a string, joined on newlines. | |
790 | .s (or .spstr): value as a string, joined on spaces. |
|
790 | .s (or .spstr): value as a string, joined on spaces. | |
791 |
|
791 | |||
792 | Any values which require transformations are computed only once and |
|
792 | Any values which require transformations are computed only once and | |
793 | cached.""" |
|
793 | cached.""" | |
794 |
|
794 | |||
795 | def get_list(self): |
|
795 | def get_list(self): | |
796 | return self |
|
796 | return self | |
797 |
|
797 | |||
798 | l = list = property(get_list) |
|
798 | l = list = property(get_list) | |
799 |
|
799 | |||
800 | def get_spstr(self): |
|
800 | def get_spstr(self): | |
801 | try: |
|
801 | try: | |
802 | return self.__spstr |
|
802 | return self.__spstr | |
803 | except AttributeError: |
|
803 | except AttributeError: | |
804 | self.__spstr = ' '.join(self) |
|
804 | self.__spstr = ' '.join(self) | |
805 | return self.__spstr |
|
805 | return self.__spstr | |
806 |
|
806 | |||
807 | s = spstr = property(get_spstr) |
|
807 | s = spstr = property(get_spstr) | |
808 |
|
808 | |||
809 | def get_nlstr(self): |
|
809 | def get_nlstr(self): | |
810 | try: |
|
810 | try: | |
811 | return self.__nlstr |
|
811 | return self.__nlstr | |
812 | except AttributeError: |
|
812 | except AttributeError: | |
813 | self.__nlstr = '\n'.join(self) |
|
813 | self.__nlstr = '\n'.join(self) | |
814 | return self.__nlstr |
|
814 | return self.__nlstr | |
815 |
|
815 | |||
816 | n = nlstr = property(get_nlstr) |
|
816 | n = nlstr = property(get_nlstr) | |
817 |
|
817 | |||
818 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
818 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): | |
819 | """Take multiple lines of input. |
|
819 | """Take multiple lines of input. | |
820 |
|
820 | |||
821 | A list with each line of input as a separate element is returned when a |
|
821 | A list with each line of input as a separate element is returned when a | |
822 | termination string is entered (defaults to a single '.'). Input can also |
|
822 | termination string is entered (defaults to a single '.'). Input can also | |
823 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
823 | terminate via EOF (^D in Unix, ^Z-RET in Windows). | |
824 |
|
824 | |||
825 | Lines of input which end in \\ are joined into single entries (and a |
|
825 | Lines of input which end in \\ are joined into single entries (and a | |
826 | secondary continuation prompt is issued as long as the user terminates |
|
826 | secondary continuation prompt is issued as long as the user terminates | |
827 | lines with \\). This allows entering very long strings which are still |
|
827 | lines with \\). This allows entering very long strings which are still | |
828 | meant to be treated as single entities. |
|
828 | meant to be treated as single entities. | |
829 | """ |
|
829 | """ | |
830 |
|
830 | |||
831 | try: |
|
831 | try: | |
832 | if header: |
|
832 | if header: | |
833 | header += '\n' |
|
833 | header += '\n' | |
834 | lines = [raw_input(header + ps1)] |
|
834 | lines = [raw_input(header + ps1)] | |
835 | except EOFError: |
|
835 | except EOFError: | |
836 | return [] |
|
836 | return [] | |
837 | terminate = [terminate_str] |
|
837 | terminate = [terminate_str] | |
838 | try: |
|
838 | try: | |
839 | while lines[-1:] != terminate: |
|
839 | while lines[-1:] != terminate: | |
840 | new_line = raw_input(ps1) |
|
840 | new_line = raw_input(ps1) | |
841 | while new_line.endswith('\\'): |
|
841 | while new_line.endswith('\\'): | |
842 | new_line = new_line[:-1] + raw_input(ps2) |
|
842 | new_line = new_line[:-1] + raw_input(ps2) | |
843 | lines.append(new_line) |
|
843 | lines.append(new_line) | |
844 |
|
844 | |||
845 | return lines[:-1] # don't return the termination command |
|
845 | return lines[:-1] # don't return the termination command | |
846 | except EOFError: |
|
846 | except EOFError: | |
847 |
|
847 | |||
848 | return lines |
|
848 | return lines | |
849 |
|
849 | |||
850 | #---------------------------------------------------------------------------- |
|
850 | #---------------------------------------------------------------------------- | |
851 | def raw_input_ext(prompt='', ps2='... '): |
|
851 | def raw_input_ext(prompt='', ps2='... '): | |
852 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
852 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" | |
853 |
|
853 | |||
854 | line = raw_input(prompt) |
|
854 | line = raw_input(prompt) | |
855 | while line.endswith('\\'): |
|
855 | while line.endswith('\\'): | |
856 | line = line[:-1] + raw_input(ps2) |
|
856 | line = line[:-1] + raw_input(ps2) | |
857 | return line |
|
857 | return line | |
858 |
|
858 | |||
859 | #---------------------------------------------------------------------------- |
|
859 | #---------------------------------------------------------------------------- | |
860 | def ask_yes_no(prompt,default=None): |
|
860 | def ask_yes_no(prompt,default=None): | |
861 | """Asks a question and returns an integer 1/0 (y/n) answer. |
|
861 | """Asks a question and returns an integer 1/0 (y/n) answer. | |
862 |
|
862 | |||
863 | If default is given (one of 'y','n'), it is used if the user input is |
|
863 | If default is given (one of 'y','n'), it is used if the user input is | |
864 | empty. Otherwise the question is repeated until an answer is given. |
|
864 | empty. Otherwise the question is repeated until an answer is given. | |
865 | If EOF occurs 20 times consecutively, the default answer is assumed, |
|
865 | If EOF occurs 20 times consecutively, the default answer is assumed, | |
866 | or if there is no default, an exception is raised to prevent infinite |
|
866 | or if there is no default, an exception is raised to prevent infinite | |
867 | loops. |
|
867 | loops. | |
868 |
|
868 | |||
869 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
869 | Valid answers are: y/yes/n/no (match is not case sensitive).""" | |
870 |
|
870 | |||
871 | answers = {'y':1,'n':0,'yes':1,'no':0} |
|
871 | answers = {'y':1,'n':0,'yes':1,'no':0} | |
872 | ans = None |
|
872 | ans = None | |
873 | eofs, max_eofs = 0, 20 |
|
873 | eofs, max_eofs = 0, 20 | |
874 | while ans not in answers.keys(): |
|
874 | while ans not in answers.keys(): | |
875 | try: |
|
875 | try: | |
876 | ans = raw_input(prompt+' ').lower() |
|
876 | ans = raw_input(prompt+' ').lower() | |
877 | if not ans: # response was an empty string |
|
877 | if not ans: # response was an empty string | |
878 | ans = default |
|
878 | ans = default | |
879 | eofs = 0 |
|
879 | eofs = 0 | |
880 | except (EOFError,KeyboardInterrupt): |
|
880 | except (EOFError,KeyboardInterrupt): | |
881 | eofs = eofs + 1 |
|
881 | eofs = eofs + 1 | |
882 | if eofs >= max_eofs: |
|
882 | if eofs >= max_eofs: | |
883 | if default in answers.keys(): |
|
883 | if default in answers.keys(): | |
884 | ans = default |
|
884 | ans = default | |
885 | else: |
|
885 | else: | |
886 | raise |
|
886 | raise | |
887 |
|
887 | |||
888 | return answers[ans] |
|
888 | return answers[ans] | |
889 |
|
889 | |||
890 | #---------------------------------------------------------------------------- |
|
890 | #---------------------------------------------------------------------------- | |
891 | class EvalDict: |
|
891 | class EvalDict: | |
892 | """ |
|
892 | """ | |
893 | Emulate a dict which evaluates its contents in the caller's frame. |
|
893 | Emulate a dict which evaluates its contents in the caller's frame. | |
894 |
|
894 | |||
895 | Usage: |
|
895 | Usage: | |
896 | >>>number = 19 |
|
896 | >>>number = 19 | |
897 | >>>text = "python" |
|
897 | >>>text = "python" | |
898 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
898 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() | |
899 | """ |
|
899 | """ | |
900 |
|
900 | |||
901 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
901 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a | |
902 | # modified (shorter) version of: |
|
902 | # modified (shorter) version of: | |
903 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
903 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by | |
904 | # Skip Montanaro (skip@pobox.com). |
|
904 | # Skip Montanaro (skip@pobox.com). | |
905 |
|
905 | |||
906 | def __getitem__(self, name): |
|
906 | def __getitem__(self, name): | |
907 | frame = sys._getframe(1) |
|
907 | frame = sys._getframe(1) | |
908 | return eval(name, frame.f_globals, frame.f_locals) |
|
908 | return eval(name, frame.f_globals, frame.f_locals) | |
909 |
|
909 | |||
910 | EvalString = EvalDict # for backwards compatibility |
|
910 | EvalString = EvalDict # for backwards compatibility | |
911 | #---------------------------------------------------------------------------- |
|
911 | #---------------------------------------------------------------------------- | |
912 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
912 | def qw(words,flat=0,sep=None,maxsplit=-1): | |
913 | """Similar to Perl's qw() operator, but with some more options. |
|
913 | """Similar to Perl's qw() operator, but with some more options. | |
914 |
|
914 | |||
915 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
915 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) | |
916 |
|
916 | |||
917 | words can also be a list itself, and with flat=1, the output will be |
|
917 | words can also be a list itself, and with flat=1, the output will be | |
918 | recursively flattened. Examples: |
|
918 | recursively flattened. Examples: | |
919 |
|
919 | |||
920 | >>> qw('1 2') |
|
920 | >>> qw('1 2') | |
921 | ['1', '2'] |
|
921 | ['1', '2'] | |
922 | >>> qw(['a b','1 2',['m n','p q']]) |
|
922 | >>> qw(['a b','1 2',['m n','p q']]) | |
923 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
923 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] | |
924 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
924 | >>> qw(['a b','1 2',['m n','p q']],flat=1) | |
925 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ |
|
925 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ | |
926 |
|
926 | |||
927 | if type(words) in StringTypes: |
|
927 | if type(words) in StringTypes: | |
928 | return [word.strip() for word in words.split(sep,maxsplit) |
|
928 | return [word.strip() for word in words.split(sep,maxsplit) | |
929 | if word and not word.isspace() ] |
|
929 | if word and not word.isspace() ] | |
930 | if flat: |
|
930 | if flat: | |
931 | return flatten(map(qw,words,[1]*len(words))) |
|
931 | return flatten(map(qw,words,[1]*len(words))) | |
932 | return map(qw,words) |
|
932 | return map(qw,words) | |
933 |
|
933 | |||
934 | #---------------------------------------------------------------------------- |
|
934 | #---------------------------------------------------------------------------- | |
935 | def qwflat(words,sep=None,maxsplit=-1): |
|
935 | def qwflat(words,sep=None,maxsplit=-1): | |
936 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
936 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" | |
937 | return qw(words,1,sep,maxsplit) |
|
937 | return qw(words,1,sep,maxsplit) | |
938 |
|
938 | |||
939 | #----------------------------------------------------------------------------- |
|
939 | #----------------------------------------------------------------------------- | |
940 | def list_strings(arg): |
|
940 | def list_strings(arg): | |
941 | """Always return a list of strings, given a string or list of strings |
|
941 | """Always return a list of strings, given a string or list of strings | |
942 | as input.""" |
|
942 | as input.""" | |
943 |
|
943 | |||
944 | if type(arg) in StringTypes: return [arg] |
|
944 | if type(arg) in StringTypes: return [arg] | |
945 | else: return arg |
|
945 | else: return arg | |
946 |
|
946 | |||
947 | #---------------------------------------------------------------------------- |
|
947 | #---------------------------------------------------------------------------- | |
948 | def grep(pat,list,case=1): |
|
948 | def grep(pat,list,case=1): | |
949 | """Simple minded grep-like function. |
|
949 | """Simple minded grep-like function. | |
950 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
950 | grep(pat,list) returns occurrences of pat in list, None on failure. | |
951 |
|
951 | |||
952 | It only does simple string matching, with no support for regexps. Use the |
|
952 | It only does simple string matching, with no support for regexps. Use the | |
953 | option case=0 for case-insensitive matching.""" |
|
953 | option case=0 for case-insensitive matching.""" | |
954 |
|
954 | |||
955 | # This is pretty crude. At least it should implement copying only references |
|
955 | # This is pretty crude. At least it should implement copying only references | |
956 | # to the original data in case it's big. Now it copies the data for output. |
|
956 | # to the original data in case it's big. Now it copies the data for output. | |
957 | out=[] |
|
957 | out=[] | |
958 | if case: |
|
958 | if case: | |
959 | for term in list: |
|
959 | for term in list: | |
960 | if term.find(pat)>-1: out.append(term) |
|
960 | if term.find(pat)>-1: out.append(term) | |
961 | else: |
|
961 | else: | |
962 | lpat=pat.lower() |
|
962 | lpat=pat.lower() | |
963 | for term in list: |
|
963 | for term in list: | |
964 | if term.lower().find(lpat)>-1: out.append(term) |
|
964 | if term.lower().find(lpat)>-1: out.append(term) | |
965 |
|
965 | |||
966 | if len(out): return out |
|
966 | if len(out): return out | |
967 | else: return None |
|
967 | else: return None | |
968 |
|
968 | |||
969 | #---------------------------------------------------------------------------- |
|
969 | #---------------------------------------------------------------------------- | |
970 | def dgrep(pat,*opts): |
|
970 | def dgrep(pat,*opts): | |
971 | """Return grep() on dir()+dir(__builtins__). |
|
971 | """Return grep() on dir()+dir(__builtins__). | |
972 |
|
972 | |||
973 | A very common use of grep() when working interactively.""" |
|
973 | A very common use of grep() when working interactively.""" | |
974 |
|
974 | |||
975 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
975 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) | |
976 |
|
976 | |||
977 | #---------------------------------------------------------------------------- |
|
977 | #---------------------------------------------------------------------------- | |
978 | def idgrep(pat): |
|
978 | def idgrep(pat): | |
979 | """Case-insensitive dgrep()""" |
|
979 | """Case-insensitive dgrep()""" | |
980 |
|
980 | |||
981 | return dgrep(pat,0) |
|
981 | return dgrep(pat,0) | |
982 |
|
982 | |||
983 | #---------------------------------------------------------------------------- |
|
983 | #---------------------------------------------------------------------------- | |
984 | def igrep(pat,list): |
|
984 | def igrep(pat,list): | |
985 | """Synonym for case-insensitive grep.""" |
|
985 | """Synonym for case-insensitive grep.""" | |
986 |
|
986 | |||
987 | return grep(pat,list,case=0) |
|
987 | return grep(pat,list,case=0) | |
988 |
|
988 | |||
989 | #---------------------------------------------------------------------------- |
|
989 | #---------------------------------------------------------------------------- | |
990 | def indent(str,nspaces=4,ntabs=0): |
|
990 | def indent(str,nspaces=4,ntabs=0): | |
991 | """Indent a string a given number of spaces or tabstops. |
|
991 | """Indent a string a given number of spaces or tabstops. | |
992 |
|
992 | |||
993 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
993 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. | |
994 | """ |
|
994 | """ | |
995 | if str is None: |
|
995 | if str is None: | |
996 | return |
|
996 | return | |
997 | ind = '\t'*ntabs+' '*nspaces |
|
997 | ind = '\t'*ntabs+' '*nspaces | |
998 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
998 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) | |
999 | if outstr.endswith(os.linesep+ind): |
|
999 | if outstr.endswith(os.linesep+ind): | |
1000 | return outstr[:-len(ind)] |
|
1000 | return outstr[:-len(ind)] | |
1001 | else: |
|
1001 | else: | |
1002 | return outstr |
|
1002 | return outstr | |
1003 |
|
1003 | |||
1004 | #----------------------------------------------------------------------------- |
|
1004 | #----------------------------------------------------------------------------- | |
1005 | def native_line_ends(filename,backup=1): |
|
1005 | def native_line_ends(filename,backup=1): | |
1006 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1006 | """Convert (in-place) a file to line-ends native to the current OS. | |
1007 |
|
1007 | |||
1008 | If the optional backup argument is given as false, no backup of the |
|
1008 | If the optional backup argument is given as false, no backup of the | |
1009 | original file is left. """ |
|
1009 | original file is left. """ | |
1010 |
|
1010 | |||
1011 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1011 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} | |
1012 |
|
1012 | |||
1013 | bak_filename = filename + backup_suffixes[os.name] |
|
1013 | bak_filename = filename + backup_suffixes[os.name] | |
1014 |
|
1014 | |||
1015 | original = open(filename).read() |
|
1015 | original = open(filename).read() | |
1016 | shutil.copy2(filename,bak_filename) |
|
1016 | shutil.copy2(filename,bak_filename) | |
1017 | try: |
|
1017 | try: | |
1018 | new = open(filename,'wb') |
|
1018 | new = open(filename,'wb') | |
1019 | new.write(os.linesep.join(original.splitlines())) |
|
1019 | new.write(os.linesep.join(original.splitlines())) | |
1020 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1020 | new.write(os.linesep) # ALWAYS put an eol at the end of the file | |
1021 | new.close() |
|
1021 | new.close() | |
1022 | except: |
|
1022 | except: | |
1023 | os.rename(bak_filename,filename) |
|
1023 | os.rename(bak_filename,filename) | |
1024 | if not backup: |
|
1024 | if not backup: | |
1025 | try: |
|
1025 | try: | |
1026 | os.remove(bak_filename) |
|
1026 | os.remove(bak_filename) | |
1027 | except: |
|
1027 | except: | |
1028 | pass |
|
1028 | pass | |
1029 |
|
1029 | |||
1030 | #---------------------------------------------------------------------------- |
|
1030 | #---------------------------------------------------------------------------- | |
1031 | def get_pager_cmd(pager_cmd = None): |
|
1031 | def get_pager_cmd(pager_cmd = None): | |
1032 | """Return a pager command. |
|
1032 | """Return a pager command. | |
1033 |
|
1033 | |||
1034 | Makes some attempts at finding an OS-correct one.""" |
|
1034 | Makes some attempts at finding an OS-correct one.""" | |
1035 |
|
1035 | |||
1036 | if os.name == 'posix': |
|
1036 | if os.name == 'posix': | |
1037 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1037 | default_pager_cmd = 'less -r' # -r for color control sequences | |
1038 | elif os.name in ['nt','dos']: |
|
1038 | elif os.name in ['nt','dos']: | |
1039 | default_pager_cmd = 'type' |
|
1039 | default_pager_cmd = 'type' | |
1040 |
|
1040 | |||
1041 | if pager_cmd is None: |
|
1041 | if pager_cmd is None: | |
1042 | try: |
|
1042 | try: | |
1043 | pager_cmd = os.environ['PAGER'] |
|
1043 | pager_cmd = os.environ['PAGER'] | |
1044 | except: |
|
1044 | except: | |
1045 | pager_cmd = default_pager_cmd |
|
1045 | pager_cmd = default_pager_cmd | |
1046 | return pager_cmd |
|
1046 | return pager_cmd | |
1047 |
|
1047 | |||
1048 | #----------------------------------------------------------------------------- |
|
1048 | #----------------------------------------------------------------------------- | |
1049 | def get_pager_start(pager,start): |
|
1049 | def get_pager_start(pager,start): | |
1050 | """Return the string for paging files with an offset. |
|
1050 | """Return the string for paging files with an offset. | |
1051 |
|
1051 | |||
1052 | This is the '+N' argument which less and more (under Unix) accept. |
|
1052 | This is the '+N' argument which less and more (under Unix) accept. | |
1053 | """ |
|
1053 | """ | |
1054 |
|
1054 | |||
1055 | if pager in ['less','more']: |
|
1055 | if pager in ['less','more']: | |
1056 | if start: |
|
1056 | if start: | |
1057 | start_string = '+' + str(start) |
|
1057 | start_string = '+' + str(start) | |
1058 | else: |
|
1058 | else: | |
1059 | start_string = '' |
|
1059 | start_string = '' | |
1060 | else: |
|
1060 | else: | |
1061 | start_string = '' |
|
1061 | start_string = '' | |
1062 | return start_string |
|
1062 | return start_string | |
1063 |
|
1063 | |||
1064 | #---------------------------------------------------------------------------- |
|
1064 | #---------------------------------------------------------------------------- | |
1065 | def page_dumb(strng,start=0,screen_lines=25): |
|
1065 | def page_dumb(strng,start=0,screen_lines=25): | |
1066 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1066 | """Very dumb 'pager' in Python, for when nothing else works. | |
1067 |
|
1067 | |||
1068 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1068 | Only moves forward, same interface as page(), except for pager_cmd and | |
1069 | mode.""" |
|
1069 | mode.""" | |
1070 |
|
1070 | |||
1071 | out_ln = strng.splitlines()[start:] |
|
1071 | out_ln = strng.splitlines()[start:] | |
1072 | screens = chop(out_ln,screen_lines-1) |
|
1072 | screens = chop(out_ln,screen_lines-1) | |
1073 | if len(screens) == 1: |
|
1073 | if len(screens) == 1: | |
1074 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1074 | print >>Term.cout, os.linesep.join(screens[0]) | |
1075 | else: |
|
1075 | else: | |
1076 | for scr in screens[0:-1]: |
|
1076 | for scr in screens[0:-1]: | |
1077 | print >>Term.cout, os.linesep.join(scr) |
|
1077 | print >>Term.cout, os.linesep.join(scr) | |
1078 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1078 | ans = raw_input('---Return to continue, q to quit--- ') | |
1079 | if ans.lower().startswith('q'): |
|
1079 | if ans.lower().startswith('q'): | |
1080 | return |
|
1080 | return | |
1081 | print >>Term.cout, os.linesep.join(screens[-1]) |
|
1081 | print >>Term.cout, os.linesep.join(screens[-1]) | |
1082 |
|
1082 | |||
1083 | #---------------------------------------------------------------------------- |
|
1083 | #---------------------------------------------------------------------------- | |
1084 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1084 | def page(strng,start=0,screen_lines=0,pager_cmd = None): | |
1085 | """Print a string, piping through a pager after a certain length. |
|
1085 | """Print a string, piping through a pager after a certain length. | |
1086 |
|
1086 | |||
1087 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1087 | The screen_lines parameter specifies the number of *usable* lines of your | |
1088 | terminal screen (total lines minus lines you need to reserve to show other |
|
1088 | terminal screen (total lines minus lines you need to reserve to show other | |
1089 | information). |
|
1089 | information). | |
1090 |
|
1090 | |||
1091 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1091 | If you set screen_lines to a number <=0, page() will try to auto-determine | |
1092 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1092 | your screen size and will only use up to (screen_size+screen_lines) for | |
1093 | printing, paging after that. That is, if you want auto-detection but need |
|
1093 | printing, paging after that. That is, if you want auto-detection but need | |
1094 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1094 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for | |
1095 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1095 | auto-detection without any lines reserved simply use screen_lines = 0. | |
1096 |
|
1096 | |||
1097 | If a string won't fit in the allowed lines, it is sent through the |
|
1097 | If a string won't fit in the allowed lines, it is sent through the | |
1098 | specified pager command. If none given, look for PAGER in the environment, |
|
1098 | specified pager command. If none given, look for PAGER in the environment, | |
1099 | and ultimately default to less. |
|
1099 | and ultimately default to less. | |
1100 |
|
1100 | |||
1101 | If no system pager works, the string is sent through a 'dumb pager' |
|
1101 | If no system pager works, the string is sent through a 'dumb pager' | |
1102 | written in python, very simplistic. |
|
1102 | written in python, very simplistic. | |
1103 | """ |
|
1103 | """ | |
1104 |
|
1104 | |||
1105 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1105 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs | |
1106 | TERM = os.environ.get('TERM','dumb') |
|
1106 | TERM = os.environ.get('TERM','dumb') | |
1107 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1107 | if TERM in ['dumb','emacs'] and os.name != 'nt': | |
1108 | print strng |
|
1108 | print strng | |
1109 | return |
|
1109 | return | |
1110 | # chop off the topmost part of the string we don't want to see |
|
1110 | # chop off the topmost part of the string we don't want to see | |
1111 | str_lines = strng.split(os.linesep)[start:] |
|
1111 | str_lines = strng.split(os.linesep)[start:] | |
1112 | str_toprint = os.linesep.join(str_lines) |
|
1112 | str_toprint = os.linesep.join(str_lines) | |
1113 | num_newlines = len(str_lines) |
|
1113 | num_newlines = len(str_lines) | |
1114 | len_str = len(str_toprint) |
|
1114 | len_str = len(str_toprint) | |
1115 |
|
1115 | |||
1116 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1116 | # Dumb heuristics to guesstimate number of on-screen lines the string | |
1117 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1117 | # takes. Very basic, but good enough for docstrings in reasonable | |
1118 | # terminals. If someone later feels like refining it, it's not hard. |
|
1118 | # terminals. If someone later feels like refining it, it's not hard. | |
1119 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1119 | numlines = max(num_newlines,int(len_str/80)+1) | |
1120 |
|
1120 | |||
1121 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1121 | screen_lines_def = 25 # default value if we can't auto-determine | |
1122 |
|
1122 | |||
1123 | # auto-determine screen size |
|
1123 | # auto-determine screen size | |
1124 | if screen_lines <= 0: |
|
1124 | if screen_lines <= 0: | |
1125 | if TERM=='xterm': |
|
1125 | if TERM=='xterm': | |
1126 | try: |
|
1126 | try: | |
1127 | import curses |
|
1127 | import curses | |
1128 | if hasattr(curses,'initscr'): |
|
1128 | if hasattr(curses,'initscr'): | |
1129 | use_curses = 1 |
|
1129 | use_curses = 1 | |
1130 | else: |
|
1130 | else: | |
1131 | use_curses = 0 |
|
1131 | use_curses = 0 | |
1132 | except ImportError: |
|
1132 | except ImportError: | |
1133 | use_curses = 0 |
|
1133 | use_curses = 0 | |
1134 | else: |
|
1134 | else: | |
1135 | # curses causes problems on many terminals other than xterm. |
|
1135 | # curses causes problems on many terminals other than xterm. | |
1136 | use_curses = 0 |
|
1136 | use_curses = 0 | |
1137 | if use_curses: |
|
1137 | if use_curses: | |
1138 | scr = curses.initscr() |
|
1138 | scr = curses.initscr() | |
1139 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1139 | screen_lines_real,screen_cols = scr.getmaxyx() | |
1140 | curses.endwin() |
|
1140 | curses.endwin() | |
1141 | screen_lines += screen_lines_real |
|
1141 | screen_lines += screen_lines_real | |
1142 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1142 | #print '***Screen size:',screen_lines_real,'lines x',\ | |
1143 | #screen_cols,'columns.' # dbg |
|
1143 | #screen_cols,'columns.' # dbg | |
1144 | else: |
|
1144 | else: | |
1145 | screen_lines += screen_lines_def |
|
1145 | screen_lines += screen_lines_def | |
1146 |
|
1146 | |||
1147 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1147 | #print 'numlines',numlines,'screenlines',screen_lines # dbg | |
1148 | if numlines <= screen_lines : |
|
1148 | if numlines <= screen_lines : | |
1149 | #print '*** normal print' # dbg |
|
1149 | #print '*** normal print' # dbg | |
1150 | print >>Term.cout, str_toprint |
|
1150 | print >>Term.cout, str_toprint | |
1151 | else: |
|
1151 | else: | |
1152 | # Try to open pager and default to internal one if that fails. |
|
1152 | # Try to open pager and default to internal one if that fails. | |
1153 | # All failure modes are tagged as 'retval=1', to match the return |
|
1153 | # All failure modes are tagged as 'retval=1', to match the return | |
1154 | # value of a failed system command. If any intermediate attempt |
|
1154 | # value of a failed system command. If any intermediate attempt | |
1155 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1155 | # sets retval to 1, at the end we resort to our own page_dumb() pager. | |
1156 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1156 | pager_cmd = get_pager_cmd(pager_cmd) | |
1157 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1157 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1158 | if os.name == 'nt': |
|
1158 | if os.name == 'nt': | |
1159 | if pager_cmd.startswith('type'): |
|
1159 | if pager_cmd.startswith('type'): | |
1160 | # The default WinXP 'type' command is failing on complex strings. |
|
1160 | # The default WinXP 'type' command is failing on complex strings. | |
1161 | retval = 1 |
|
1161 | retval = 1 | |
1162 | else: |
|
1162 | else: | |
1163 | tmpname = tempfile.mktemp('.txt') |
|
1163 | tmpname = tempfile.mktemp('.txt') | |
1164 | tmpfile = file(tmpname,'wt') |
|
1164 | tmpfile = file(tmpname,'wt') | |
1165 | tmpfile.write(strng) |
|
1165 | tmpfile.write(strng) | |
1166 | tmpfile.close() |
|
1166 | tmpfile.close() | |
1167 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1167 | cmd = "%s < %s" % (pager_cmd,tmpname) | |
1168 | if os.system(cmd): |
|
1168 | if os.system(cmd): | |
1169 | retval = 1 |
|
1169 | retval = 1 | |
1170 | else: |
|
1170 | else: | |
1171 | retval = None |
|
1171 | retval = None | |
1172 | os.remove(tmpname) |
|
1172 | os.remove(tmpname) | |
1173 | else: |
|
1173 | else: | |
1174 | try: |
|
1174 | try: | |
1175 | retval = None |
|
1175 | retval = None | |
1176 | # if I use popen4, things hang. No idea why. |
|
1176 | # if I use popen4, things hang. No idea why. | |
1177 | #pager,shell_out = os.popen4(pager_cmd) |
|
1177 | #pager,shell_out = os.popen4(pager_cmd) | |
1178 | pager = os.popen(pager_cmd,'w') |
|
1178 | pager = os.popen(pager_cmd,'w') | |
1179 | pager.write(strng) |
|
1179 | pager.write(strng) | |
1180 | pager.close() |
|
1180 | pager.close() | |
1181 | retval = pager.close() # success returns None |
|
1181 | retval = pager.close() # success returns None | |
1182 | except IOError,msg: # broken pipe when user quits |
|
1182 | except IOError,msg: # broken pipe when user quits | |
1183 | if msg.args == (32,'Broken pipe'): |
|
1183 | if msg.args == (32,'Broken pipe'): | |
1184 | retval = None |
|
1184 | retval = None | |
1185 | else: |
|
1185 | else: | |
1186 | retval = 1 |
|
1186 | retval = 1 | |
1187 | except OSError: |
|
1187 | except OSError: | |
1188 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1188 | # Other strange problems, sometimes seen in Win2k/cygwin | |
1189 | retval = 1 |
|
1189 | retval = 1 | |
1190 | if retval is not None: |
|
1190 | if retval is not None: | |
1191 | page_dumb(strng,screen_lines=screen_lines) |
|
1191 | page_dumb(strng,screen_lines=screen_lines) | |
1192 |
|
1192 | |||
1193 | #---------------------------------------------------------------------------- |
|
1193 | #---------------------------------------------------------------------------- | |
1194 | def page_file(fname,start = 0, pager_cmd = None): |
|
1194 | def page_file(fname,start = 0, pager_cmd = None): | |
1195 | """Page a file, using an optional pager command and starting line. |
|
1195 | """Page a file, using an optional pager command and starting line. | |
1196 | """ |
|
1196 | """ | |
1197 |
|
1197 | |||
1198 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1198 | pager_cmd = get_pager_cmd(pager_cmd) | |
1199 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1199 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1200 |
|
1200 | |||
1201 | try: |
|
1201 | try: | |
1202 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1202 | if os.environ['TERM'] in ['emacs','dumb']: | |
1203 | raise EnvironmentError |
|
1203 | raise EnvironmentError | |
1204 | xsys(pager_cmd + ' ' + fname) |
|
1204 | xsys(pager_cmd + ' ' + fname) | |
1205 | except: |
|
1205 | except: | |
1206 | try: |
|
1206 | try: | |
1207 | if start > 0: |
|
1207 | if start > 0: | |
1208 | start -= 1 |
|
1208 | start -= 1 | |
1209 | page(open(fname).read(),start) |
|
1209 | page(open(fname).read(),start) | |
1210 | except: |
|
1210 | except: | |
1211 | print 'Unable to show file',`fname` |
|
1211 | print 'Unable to show file',`fname` | |
1212 |
|
1212 | |||
1213 | #---------------------------------------------------------------------------- |
|
1213 | #---------------------------------------------------------------------------- | |
1214 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1214 | def snip_print(str,width = 75,print_full = 0,header = ''): | |
1215 | """Print a string snipping the midsection to fit in width. |
|
1215 | """Print a string snipping the midsection to fit in width. | |
1216 |
|
1216 | |||
1217 | print_full: mode control: |
|
1217 | print_full: mode control: | |
1218 | - 0: only snip long strings |
|
1218 | - 0: only snip long strings | |
1219 | - 1: send to page() directly. |
|
1219 | - 1: send to page() directly. | |
1220 | - 2: snip long strings and ask for full length viewing with page() |
|
1220 | - 2: snip long strings and ask for full length viewing with page() | |
1221 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1221 | Return 1 if snipping was necessary, 0 otherwise.""" | |
1222 |
|
1222 | |||
1223 | if print_full == 1: |
|
1223 | if print_full == 1: | |
1224 | page(header+str) |
|
1224 | page(header+str) | |
1225 | return 0 |
|
1225 | return 0 | |
1226 |
|
1226 | |||
1227 | print header, |
|
1227 | print header, | |
1228 | if len(str) < width: |
|
1228 | if len(str) < width: | |
1229 | print str |
|
1229 | print str | |
1230 | snip = 0 |
|
1230 | snip = 0 | |
1231 | else: |
|
1231 | else: | |
1232 | whalf = int((width -5)/2) |
|
1232 | whalf = int((width -5)/2) | |
1233 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1233 | print str[:whalf] + ' <...> ' + str[-whalf:] | |
1234 | snip = 1 |
|
1234 | snip = 1 | |
1235 | if snip and print_full == 2: |
|
1235 | if snip and print_full == 2: | |
1236 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1236 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': | |
1237 | page(str) |
|
1237 | page(str) | |
1238 | return snip |
|
1238 | return snip | |
1239 |
|
1239 | |||
1240 | #**************************************************************************** |
|
1240 | #**************************************************************************** | |
1241 | # lists, dicts and structures |
|
1241 | # lists, dicts and structures | |
1242 |
|
1242 | |||
1243 | def belong(candidates,checklist): |
|
1243 | def belong(candidates,checklist): | |
1244 | """Check whether a list of items appear in a given list of options. |
|
1244 | """Check whether a list of items appear in a given list of options. | |
1245 |
|
1245 | |||
1246 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1246 | Returns a list of 1 and 0, one for each candidate given.""" | |
1247 |
|
1247 | |||
1248 | return [x in checklist for x in candidates] |
|
1248 | return [x in checklist for x in candidates] | |
1249 |
|
1249 | |||
1250 | #---------------------------------------------------------------------------- |
|
1250 | #---------------------------------------------------------------------------- | |
1251 | def uniq_stable(elems): |
|
1251 | def uniq_stable(elems): | |
1252 | """uniq_stable(elems) -> list |
|
1252 | """uniq_stable(elems) -> list | |
1253 |
|
1253 | |||
1254 | Return from an iterable, a list of all the unique elements in the input, |
|
1254 | Return from an iterable, a list of all the unique elements in the input, | |
1255 | but maintaining the order in which they first appear. |
|
1255 | but maintaining the order in which they first appear. | |
1256 |
|
1256 | |||
1257 | A naive solution to this problem which just makes a dictionary with the |
|
1257 | A naive solution to this problem which just makes a dictionary with the | |
1258 | elements as keys fails to respect the stability condition, since |
|
1258 | elements as keys fails to respect the stability condition, since | |
1259 | dictionaries are unsorted by nature. |
|
1259 | dictionaries are unsorted by nature. | |
1260 |
|
1260 | |||
1261 | Note: All elements in the input must be valid dictionary keys for this |
|
1261 | Note: All elements in the input must be valid dictionary keys for this | |
1262 | routine to work, as it internally uses a dictionary for efficiency |
|
1262 | routine to work, as it internally uses a dictionary for efficiency | |
1263 | reasons.""" |
|
1263 | reasons.""" | |
1264 |
|
1264 | |||
1265 | unique = [] |
|
1265 | unique = [] | |
1266 | unique_dict = {} |
|
1266 | unique_dict = {} | |
1267 | for nn in elems: |
|
1267 | for nn in elems: | |
1268 | if nn not in unique_dict: |
|
1268 | if nn not in unique_dict: | |
1269 | unique.append(nn) |
|
1269 | unique.append(nn) | |
1270 | unique_dict[nn] = None |
|
1270 | unique_dict[nn] = None | |
1271 | return unique |
|
1271 | return unique | |
1272 |
|
1272 | |||
1273 | #---------------------------------------------------------------------------- |
|
1273 | #---------------------------------------------------------------------------- | |
1274 | class NLprinter: |
|
1274 | class NLprinter: | |
1275 | """Print an arbitrarily nested list, indicating index numbers. |
|
1275 | """Print an arbitrarily nested list, indicating index numbers. | |
1276 |
|
1276 | |||
1277 | An instance of this class called nlprint is available and callable as a |
|
1277 | An instance of this class called nlprint is available and callable as a | |
1278 | function. |
|
1278 | function. | |
1279 |
|
1279 | |||
1280 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1280 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' | |
1281 | and using 'sep' to separate the index from the value. """ |
|
1281 | and using 'sep' to separate the index from the value. """ | |
1282 |
|
1282 | |||
1283 | def __init__(self): |
|
1283 | def __init__(self): | |
1284 | self.depth = 0 |
|
1284 | self.depth = 0 | |
1285 |
|
1285 | |||
1286 | def __call__(self,lst,pos='',**kw): |
|
1286 | def __call__(self,lst,pos='',**kw): | |
1287 | """Prints the nested list numbering levels.""" |
|
1287 | """Prints the nested list numbering levels.""" | |
1288 | kw.setdefault('indent',' ') |
|
1288 | kw.setdefault('indent',' ') | |
1289 | kw.setdefault('sep',': ') |
|
1289 | kw.setdefault('sep',': ') | |
1290 | kw.setdefault('start',0) |
|
1290 | kw.setdefault('start',0) | |
1291 | kw.setdefault('stop',len(lst)) |
|
1291 | kw.setdefault('stop',len(lst)) | |
1292 | # we need to remove start and stop from kw so they don't propagate |
|
1292 | # we need to remove start and stop from kw so they don't propagate | |
1293 | # into a recursive call for a nested list. |
|
1293 | # into a recursive call for a nested list. | |
1294 | start = kw['start']; del kw['start'] |
|
1294 | start = kw['start']; del kw['start'] | |
1295 | stop = kw['stop']; del kw['stop'] |
|
1295 | stop = kw['stop']; del kw['stop'] | |
1296 | if self.depth == 0 and 'header' in kw.keys(): |
|
1296 | if self.depth == 0 and 'header' in kw.keys(): | |
1297 | print kw['header'] |
|
1297 | print kw['header'] | |
1298 |
|
1298 | |||
1299 | for idx in range(start,stop): |
|
1299 | for idx in range(start,stop): | |
1300 | elem = lst[idx] |
|
1300 | elem = lst[idx] | |
1301 | if type(elem)==type([]): |
|
1301 | if type(elem)==type([]): | |
1302 | self.depth += 1 |
|
1302 | self.depth += 1 | |
1303 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1303 | self.__call__(elem,itpl('$pos$idx,'),**kw) | |
1304 | self.depth -= 1 |
|
1304 | self.depth -= 1 | |
1305 | else: |
|
1305 | else: | |
1306 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1306 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') | |
1307 |
|
1307 | |||
1308 | nlprint = NLprinter() |
|
1308 | nlprint = NLprinter() | |
1309 | #---------------------------------------------------------------------------- |
|
1309 | #---------------------------------------------------------------------------- | |
1310 | def all_belong(candidates,checklist): |
|
1310 | def all_belong(candidates,checklist): | |
1311 | """Check whether a list of items ALL appear in a given list of options. |
|
1311 | """Check whether a list of items ALL appear in a given list of options. | |
1312 |
|
1312 | |||
1313 | Returns a single 1 or 0 value.""" |
|
1313 | Returns a single 1 or 0 value.""" | |
1314 |
|
1314 | |||
1315 | return 1-(0 in [x in checklist for x in candidates]) |
|
1315 | return 1-(0 in [x in checklist for x in candidates]) | |
1316 |
|
1316 | |||
1317 | #---------------------------------------------------------------------------- |
|
1317 | #---------------------------------------------------------------------------- | |
1318 | def sort_compare(lst1,lst2,inplace = 1): |
|
1318 | def sort_compare(lst1,lst2,inplace = 1): | |
1319 | """Sort and compare two lists. |
|
1319 | """Sort and compare two lists. | |
1320 |
|
1320 | |||
1321 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1321 | By default it does it in place, thus modifying the lists. Use inplace = 0 | |
1322 | to avoid that (at the cost of temporary copy creation).""" |
|
1322 | to avoid that (at the cost of temporary copy creation).""" | |
1323 | if not inplace: |
|
1323 | if not inplace: | |
1324 | lst1 = lst1[:] |
|
1324 | lst1 = lst1[:] | |
1325 | lst2 = lst2[:] |
|
1325 | lst2 = lst2[:] | |
1326 | lst1.sort(); lst2.sort() |
|
1326 | lst1.sort(); lst2.sort() | |
1327 | return lst1 == lst2 |
|
1327 | return lst1 == lst2 | |
1328 |
|
1328 | |||
1329 | #---------------------------------------------------------------------------- |
|
1329 | #---------------------------------------------------------------------------- | |
1330 | def mkdict(**kwargs): |
|
1330 | def mkdict(**kwargs): | |
1331 | """Return a dict from a keyword list. |
|
1331 | """Return a dict from a keyword list. | |
1332 |
|
1332 | |||
1333 | It's just syntactic sugar for making ditcionary creation more convenient: |
|
1333 | It's just syntactic sugar for making ditcionary creation more convenient: | |
1334 | # the standard way |
|
1334 | # the standard way | |
1335 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } |
|
1335 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } | |
1336 | # a cleaner way |
|
1336 | # a cleaner way | |
1337 | >>>data = dict(red=1, green=2, blue=3) |
|
1337 | >>>data = dict(red=1, green=2, blue=3) | |
1338 |
|
1338 | |||
1339 | If you need more than this, look at the Struct() class.""" |
|
1339 | If you need more than this, look at the Struct() class.""" | |
1340 |
|
1340 | |||
1341 | return kwargs |
|
1341 | return kwargs | |
1342 |
|
1342 | |||
1343 | #---------------------------------------------------------------------------- |
|
1343 | #---------------------------------------------------------------------------- | |
1344 | def list2dict(lst): |
|
1344 | def list2dict(lst): | |
1345 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1345 | """Takes a list of (key,value) pairs and turns it into a dict.""" | |
1346 |
|
1346 | |||
1347 | dic = {} |
|
1347 | dic = {} | |
1348 | for k,v in lst: dic[k] = v |
|
1348 | for k,v in lst: dic[k] = v | |
1349 | return dic |
|
1349 | return dic | |
1350 |
|
1350 | |||
1351 | #---------------------------------------------------------------------------- |
|
1351 | #---------------------------------------------------------------------------- | |
1352 | def list2dict2(lst,default=''): |
|
1352 | def list2dict2(lst,default=''): | |
1353 | """Takes a list and turns it into a dict. |
|
1353 | """Takes a list and turns it into a dict. | |
1354 | Much slower than list2dict, but more versatile. This version can take |
|
1354 | Much slower than list2dict, but more versatile. This version can take | |
1355 | lists with sublists of arbitrary length (including sclars).""" |
|
1355 | lists with sublists of arbitrary length (including sclars).""" | |
1356 |
|
1356 | |||
1357 | dic = {} |
|
1357 | dic = {} | |
1358 | for elem in lst: |
|
1358 | for elem in lst: | |
1359 | if type(elem) in (types.ListType,types.TupleType): |
|
1359 | if type(elem) in (types.ListType,types.TupleType): | |
1360 | size = len(elem) |
|
1360 | size = len(elem) | |
1361 | if size == 0: |
|
1361 | if size == 0: | |
1362 | pass |
|
1362 | pass | |
1363 | elif size == 1: |
|
1363 | elif size == 1: | |
1364 | dic[elem] = default |
|
1364 | dic[elem] = default | |
1365 | else: |
|
1365 | else: | |
1366 | k,v = elem[0], elem[1:] |
|
1366 | k,v = elem[0], elem[1:] | |
1367 | if len(v) == 1: v = v[0] |
|
1367 | if len(v) == 1: v = v[0] | |
1368 | dic[k] = v |
|
1368 | dic[k] = v | |
1369 | else: |
|
1369 | else: | |
1370 | dic[elem] = default |
|
1370 | dic[elem] = default | |
1371 | return dic |
|
1371 | return dic | |
1372 |
|
1372 | |||
1373 | #---------------------------------------------------------------------------- |
|
1373 | #---------------------------------------------------------------------------- | |
1374 | def flatten(seq): |
|
1374 | def flatten(seq): | |
1375 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1375 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" | |
1376 |
|
1376 | |||
1377 | # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in). |
|
1377 | # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in). | |
1378 |
|
1378 | |||
1379 | # if the x=0 isn't made, a *global* variable x is left over after calling |
|
1379 | # if the x=0 isn't made, a *global* variable x is left over after calling | |
1380 | # this function, with the value of the last element in the return |
|
1380 | # this function, with the value of the last element in the return | |
1381 | # list. This does seem like a bug big time to me. |
|
1381 | # list. This does seem like a bug big time to me. | |
1382 |
|
1382 | |||
1383 | # the problem is fixed with the x=0, which seems to force the creation of |
|
1383 | # the problem is fixed with the x=0, which seems to force the creation of | |
1384 | # a local name |
|
1384 | # a local name | |
1385 |
|
1385 | |||
1386 | x = 0 |
|
1386 | x = 0 | |
1387 | return [x for subseq in seq for x in subseq] |
|
1387 | return [x for subseq in seq for x in subseq] | |
1388 |
|
1388 | |||
1389 | #---------------------------------------------------------------------------- |
|
1389 | #---------------------------------------------------------------------------- | |
1390 | def get_slice(seq,start=0,stop=None,step=1): |
|
1390 | def get_slice(seq,start=0,stop=None,step=1): | |
1391 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1391 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" | |
1392 | if stop == None: |
|
1392 | if stop == None: | |
1393 | stop = len(seq) |
|
1393 | stop = len(seq) | |
1394 | item = lambda i: seq[i] |
|
1394 | item = lambda i: seq[i] | |
1395 | return map(item,xrange(start,stop,step)) |
|
1395 | return map(item,xrange(start,stop,step)) | |
1396 |
|
1396 | |||
1397 | #---------------------------------------------------------------------------- |
|
1397 | #---------------------------------------------------------------------------- | |
1398 | def chop(seq,size): |
|
1398 | def chop(seq,size): | |
1399 | """Chop a sequence into chunks of the given size.""" |
|
1399 | """Chop a sequence into chunks of the given size.""" | |
1400 | chunk = lambda i: seq[i:i+size] |
|
1400 | chunk = lambda i: seq[i:i+size] | |
1401 | return map(chunk,xrange(0,len(seq),size)) |
|
1401 | return map(chunk,xrange(0,len(seq),size)) | |
1402 |
|
1402 | |||
1403 | #---------------------------------------------------------------------------- |
|
1403 | #---------------------------------------------------------------------------- | |
1404 | def with(object, **args): |
|
1404 | def with(object, **args): | |
1405 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1405 | """Set multiple attributes for an object, similar to Pascal's with. | |
1406 |
|
1406 | |||
1407 | Example: |
|
1407 | Example: | |
1408 | with(jim, |
|
1408 | with(jim, | |
1409 | born = 1960, |
|
1409 | born = 1960, | |
1410 | haircolour = 'Brown', |
|
1410 | haircolour = 'Brown', | |
1411 | eyecolour = 'Green') |
|
1411 | eyecolour = 'Green') | |
1412 |
|
1412 | |||
1413 | Credit: Greg Ewing, in |
|
1413 | Credit: Greg Ewing, in | |
1414 | http://mail.python.org/pipermail/python-list/2001-May/040703.html""" |
|
1414 | http://mail.python.org/pipermail/python-list/2001-May/040703.html""" | |
1415 |
|
1415 | |||
1416 | object.__dict__.update(args) |
|
1416 | object.__dict__.update(args) | |
1417 |
|
1417 | |||
1418 | #---------------------------------------------------------------------------- |
|
1418 | #---------------------------------------------------------------------------- | |
1419 | def setattr_list(obj,alist,nspace = None): |
|
1419 | def setattr_list(obj,alist,nspace = None): | |
1420 | """Set a list of attributes for an object taken from a namespace. |
|
1420 | """Set a list of attributes for an object taken from a namespace. | |
1421 |
|
1421 | |||
1422 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1422 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in | |
1423 | alist with their values taken from nspace, which must be a dict (something |
|
1423 | alist with their values taken from nspace, which must be a dict (something | |
1424 | like locals() will often do) If nspace isn't given, locals() of the |
|
1424 | like locals() will often do) If nspace isn't given, locals() of the | |
1425 | *caller* is used, so in most cases you can omit it. |
|
1425 | *caller* is used, so in most cases you can omit it. | |
1426 |
|
1426 | |||
1427 | Note that alist can be given as a string, which will be automatically |
|
1427 | Note that alist can be given as a string, which will be automatically | |
1428 | split into a list on whitespace. If given as a list, it must be a list of |
|
1428 | split into a list on whitespace. If given as a list, it must be a list of | |
1429 | *strings* (the variable names themselves), not of variables.""" |
|
1429 | *strings* (the variable names themselves), not of variables.""" | |
1430 |
|
1430 | |||
1431 | # this grabs the local variables from the *previous* call frame -- that is |
|
1431 | # this grabs the local variables from the *previous* call frame -- that is | |
1432 | # the locals from the function that called setattr_list(). |
|
1432 | # the locals from the function that called setattr_list(). | |
1433 | # - snipped from weave.inline() |
|
1433 | # - snipped from weave.inline() | |
1434 | if nspace is None: |
|
1434 | if nspace is None: | |
1435 | call_frame = sys._getframe().f_back |
|
1435 | call_frame = sys._getframe().f_back | |
1436 | nspace = call_frame.f_locals |
|
1436 | nspace = call_frame.f_locals | |
1437 |
|
1437 | |||
1438 | if type(alist) in StringTypes: |
|
1438 | if type(alist) in StringTypes: | |
1439 | alist = alist.split() |
|
1439 | alist = alist.split() | |
1440 | for attr in alist: |
|
1440 | for attr in alist: | |
1441 | val = eval(attr,nspace) |
|
1441 | val = eval(attr,nspace) | |
1442 | setattr(obj,attr,val) |
|
1442 | setattr(obj,attr,val) | |
1443 |
|
1443 | |||
1444 | #---------------------------------------------------------------------------- |
|
1444 | #---------------------------------------------------------------------------- | |
1445 | def getattr_list(obj,alist,*args): |
|
1445 | def getattr_list(obj,alist,*args): | |
1446 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1446 | """getattr_list(obj,alist[, default]) -> attribute list. | |
1447 |
|
1447 | |||
1448 | Get a list of named attributes for an object. When a default argument is |
|
1448 | Get a list of named attributes for an object. When a default argument is | |
1449 | given, it is returned when the attribute doesn't exist; without it, an |
|
1449 | given, it is returned when the attribute doesn't exist; without it, an | |
1450 | exception is raised in that case. |
|
1450 | exception is raised in that case. | |
1451 |
|
1451 | |||
1452 | Note that alist can be given as a string, which will be automatically |
|
1452 | Note that alist can be given as a string, which will be automatically | |
1453 | split into a list on whitespace. If given as a list, it must be a list of |
|
1453 | split into a list on whitespace. If given as a list, it must be a list of | |
1454 | *strings* (the variable names themselves), not of variables.""" |
|
1454 | *strings* (the variable names themselves), not of variables.""" | |
1455 |
|
1455 | |||
1456 | if type(alist) in StringTypes: |
|
1456 | if type(alist) in StringTypes: | |
1457 | alist = alist.split() |
|
1457 | alist = alist.split() | |
1458 | if args: |
|
1458 | if args: | |
1459 | if len(args)==1: |
|
1459 | if len(args)==1: | |
1460 | default = args[0] |
|
1460 | default = args[0] | |
1461 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1461 | return map(lambda attr: getattr(obj,attr,default),alist) | |
1462 | else: |
|
1462 | else: | |
1463 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1463 | raise ValueError,'getattr_list() takes only one optional argument' | |
1464 | else: |
|
1464 | else: | |
1465 | return map(lambda attr: getattr(obj,attr),alist) |
|
1465 | return map(lambda attr: getattr(obj,attr),alist) | |
1466 |
|
1466 | |||
1467 | #---------------------------------------------------------------------------- |
|
1467 | #---------------------------------------------------------------------------- | |
1468 | def map_method(method,object_list,*argseq,**kw): |
|
1468 | def map_method(method,object_list,*argseq,**kw): | |
1469 | """map_method(method,object_list,*args,**kw) -> list |
|
1469 | """map_method(method,object_list,*args,**kw) -> list | |
1470 |
|
1470 | |||
1471 | Return a list of the results of applying the methods to the items of the |
|
1471 | Return a list of the results of applying the methods to the items of the | |
1472 | argument sequence(s). If more than one sequence is given, the method is |
|
1472 | argument sequence(s). If more than one sequence is given, the method is | |
1473 | called with an argument list consisting of the corresponding item of each |
|
1473 | called with an argument list consisting of the corresponding item of each | |
1474 | sequence. All sequences must be of the same length. |
|
1474 | sequence. All sequences must be of the same length. | |
1475 |
|
1475 | |||
1476 | Keyword arguments are passed verbatim to all objects called. |
|
1476 | Keyword arguments are passed verbatim to all objects called. | |
1477 |
|
1477 | |||
1478 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1478 | This is Python code, so it's not nearly as fast as the builtin map().""" | |
1479 |
|
1479 | |||
1480 | out_list = [] |
|
1480 | out_list = [] | |
1481 | idx = 0 |
|
1481 | idx = 0 | |
1482 | for object in object_list: |
|
1482 | for object in object_list: | |
1483 | try: |
|
1483 | try: | |
1484 | handler = getattr(object, method) |
|
1484 | handler = getattr(object, method) | |
1485 | except AttributeError: |
|
1485 | except AttributeError: | |
1486 | out_list.append(None) |
|
1486 | out_list.append(None) | |
1487 | else: |
|
1487 | else: | |
1488 | if argseq: |
|
1488 | if argseq: | |
1489 | args = map(lambda lst:lst[idx],argseq) |
|
1489 | args = map(lambda lst:lst[idx],argseq) | |
1490 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1490 | #print 'ob',object,'hand',handler,'ar',args # dbg | |
1491 | out_list.append(handler(args,**kw)) |
|
1491 | out_list.append(handler(args,**kw)) | |
1492 | else: |
|
1492 | else: | |
1493 | out_list.append(handler(**kw)) |
|
1493 | out_list.append(handler(**kw)) | |
1494 | idx += 1 |
|
1494 | idx += 1 | |
1495 | return out_list |
|
1495 | return out_list | |
1496 |
|
1496 | |||
1497 | #---------------------------------------------------------------------------- |
|
1497 | #---------------------------------------------------------------------------- | |
1498 | # Proposed popitem() extension, written as a method |
|
1498 | # Proposed popitem() extension, written as a method | |
1499 |
|
1499 | |||
1500 | class NotGiven: pass |
|
1500 | class NotGiven: pass | |
1501 |
|
1501 | |||
1502 | def popkey(dct,key,default=NotGiven): |
|
1502 | def popkey(dct,key,default=NotGiven): | |
1503 | """Return dct[key] and delete dct[key]. |
|
1503 | """Return dct[key] and delete dct[key]. | |
1504 |
|
1504 | |||
1505 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
1505 | If default is given, return it if dct[key] doesn't exist, otherwise raise | |
1506 | KeyError. """ |
|
1506 | KeyError. """ | |
1507 |
|
1507 | |||
1508 | try: |
|
1508 | try: | |
1509 | val = dct[key] |
|
1509 | val = dct[key] | |
1510 | except KeyError: |
|
1510 | except KeyError: | |
1511 | if default is NotGiven: |
|
1511 | if default is NotGiven: | |
1512 | raise |
|
1512 | raise | |
1513 | else: |
|
1513 | else: | |
1514 | return default |
|
1514 | return default | |
1515 | else: |
|
1515 | else: | |
1516 | del dct[key] |
|
1516 | del dct[key] | |
1517 | return val |
|
1517 | return val | |
1518 | #*************************** end of file <genutils.py> ********************** |
|
1518 | #*************************** end of file <genutils.py> ********************** | |
1519 |
|
1519 |
General Comments 0
You need to be logged in to leave comments.
Login now