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