##// END OF EJS Templates
Changes for demos and access to raw history in %macro, %save and %edit....
fperez -
Show More

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

@@ -1,2765 +1,2804 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 1121 2006-02-01 21:12:20Z vivainio $"""
4 $Id: Magic.py 1126 2006-02-06 02:31:40Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 import textwrap
35 35 from cStringIO import StringIO
36 36 from getopt import getopt,GetoptError
37 37 from pprint import pprint, pformat
38 38
39 39 # profile isn't bundled by default in Debian for license reasons
40 40 try:
41 41 import profile,pstats
42 42 except ImportError:
43 43 profile = pstats = None
44 44
45 45 # Homebrewed
46 46 from IPython import Debugger, OInspect, wildcard
47 47 from IPython.FakeModule import FakeModule
48 48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 49 from IPython.PyColorize import Parser
50 50 from IPython.ipstruct import Struct
51 51 from IPython.macro import Macro
52 52 from IPython.genutils import *
53 53 from IPython import platutils
54 54
55 55 #***************************************************************************
56 56 # Utility functions
57 57 def on_off(tag):
58 58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 59 return ['OFF','ON'][tag]
60 60
61 61 class Bunch: pass
62 62
63 63 #***************************************************************************
64 64 # Main class implementing Magic functionality
65 65 class Magic:
66 66 """Magic functions for InteractiveShell.
67 67
68 68 Shell functions which can be reached as %function_name. All magic
69 69 functions should accept a string, which they can parse for their own
70 70 needs. This can make some functions easier to type, eg `%cd ../`
71 71 vs. `%cd("../")`
72 72
73 73 ALL definitions MUST begin with the prefix magic_. The user won't need it
74 74 at the command line, but it is is needed in the definition. """
75 75
76 76 # class globals
77 77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
78 78 'Automagic is ON, % prefix NOT needed for magic functions.']
79 79
80 80 #......................................................................
81 81 # some utility functions
82 82
83 83 def __init__(self,shell):
84 84
85 85 self.options_table = {}
86 86 if profile is None:
87 87 self.magic_prun = self.profile_missing_notice
88 88 self.shell = shell
89 89
90 90 # namespace for holding state we may need
91 91 self._magic_state = Bunch()
92 92
93 93 def profile_missing_notice(self, *args, **kwargs):
94 94 error("""\
95 95 The profile module could not be found. If you are a Debian user,
96 96 it has been removed from the standard Debian package because of its non-free
97 97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
98 98
99 99 def default_option(self,fn,optstr):
100 100 """Make an entry in the options_table for fn, with value optstr"""
101
101
102 102 if fn not in self.lsmagic():
103 103 error("%s is not a magic function" % fn)
104 104 self.options_table[fn] = optstr
105 105
106 106 def lsmagic(self):
107 107 """Return a list of currently available magic functions.
108 108
109 109 Gives a list of the bare names after mangling (['ls','cd', ...], not
110 110 ['magic_ls','magic_cd',...]"""
111 111
112 112 # FIXME. This needs a cleanup, in the way the magics list is built.
113 113
114 114 # magics in class definition
115 115 class_magic = lambda fn: fn.startswith('magic_') and \
116 116 callable(Magic.__dict__[fn])
117 117 # in instance namespace (run-time user additions)
118 118 inst_magic = lambda fn: fn.startswith('magic_') and \
119 119 callable(self.__dict__[fn])
120 120 # and bound magics by user (so they can access self):
121 121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
122 122 callable(self.__class__.__dict__[fn])
123 123 magics = filter(class_magic,Magic.__dict__.keys()) + \
124 124 filter(inst_magic,self.__dict__.keys()) + \
125 125 filter(inst_bound_magic,self.__class__.__dict__.keys())
126 126 out = []
127 127 for fn in magics:
128 128 out.append(fn.replace('magic_','',1))
129 129 out.sort()
130 130 return out
131 131
132 def extract_input_slices(self,slices):
132 def extract_input_slices(self,slices,raw=False):
133 133 """Return as a string a set of input history slices.
134 134
135 The set of slices is given as a list of strings (like ['1','4:8','9'],
136 since this function is for use by magic functions which get their
137 arguments as strings.
135 Inputs:
136
137 - slices: the set of slices is given as a list of strings (like
138 ['1','4:8','9'], since this function is for use by magic functions
139 which get their arguments as strings.
140
141 Optional inputs:
142
143 - raw(False): by default, the processed input is used. If this is
144 true, the raw input history is used instead.
138 145
139 146 Note that slices can be called with two notations:
140 147
141 148 N:M -> standard python form, means including items N...(M-1).
142 149
143 150 N-M -> include items N..M (closed endpoint)."""
144 151
152 if raw:
153 hist = self.shell.input_hist_raw
154 else:
155 hist = self.shell.input_hist
156
145 157 cmds = []
146 158 for chunk in slices:
147 159 if ':' in chunk:
148 160 ini,fin = map(int,chunk.split(':'))
149 161 elif '-' in chunk:
150 162 ini,fin = map(int,chunk.split('-'))
151 163 fin += 1
152 164 else:
153 165 ini = int(chunk)
154 166 fin = ini+1
155 cmds.append(self.shell.input_hist[ini:fin])
167 cmds.append(hist[ini:fin])
156 168 return cmds
157 169
158 170 def _ofind(self,oname):
159 171 """Find an object in the available namespaces.
160 172
161 173 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
162 174
163 175 Has special code to detect magic functions.
164 176 """
165 177
166 178 oname = oname.strip()
167 179
168 180 # Namespaces to search in:
169 181 user_ns = self.shell.user_ns
170 182 internal_ns = self.shell.internal_ns
171 183 builtin_ns = __builtin__.__dict__
172 184 alias_ns = self.shell.alias_table
173 185
174 186 # Put them in a list. The order is important so that we find things in
175 187 # the same order that Python finds them.
176 188 namespaces = [ ('Interactive',user_ns),
177 189 ('IPython internal',internal_ns),
178 190 ('Python builtin',builtin_ns),
179 191 ('Alias',alias_ns),
180 192 ]
181 193
182 194 # initialize results to 'null'
183 195 found = 0; obj = None; ospace = None; ds = None;
184 196 ismagic = 0; isalias = 0
185 197
186 198 # Look for the given name by splitting it in parts. If the head is
187 199 # found, then we look for all the remaining parts as members, and only
188 200 # declare success if we can find them all.
189 201 oname_parts = oname.split('.')
190 202 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
191 203 for nsname,ns in namespaces:
192 204 try:
193 205 obj = ns[oname_head]
194 206 except KeyError:
195 207 continue
196 208 else:
197 209 for part in oname_rest:
198 210 try:
199 211 obj = getattr(obj,part)
200 212 except:
201 213 # Blanket except b/c some badly implemented objects
202 214 # allow __getattr__ to raise exceptions other than
203 215 # AttributeError, which then crashes IPython.
204 216 break
205 217 else:
206 218 # If we finish the for loop (no break), we got all members
207 219 found = 1
208 220 ospace = nsname
209 221 if ns == alias_ns:
210 222 isalias = 1
211 223 break # namespace loop
212 224
213 225 # Try to see if it's magic
214 226 if not found:
215 227 if oname.startswith(self.shell.ESC_MAGIC):
216 228 oname = oname[1:]
217 229 obj = getattr(self,'magic_'+oname,None)
218 230 if obj is not None:
219 231 found = 1
220 232 ospace = 'IPython internal'
221 233 ismagic = 1
222 234
223 235 # Last try: special-case some literals like '', [], {}, etc:
224 236 if not found and oname_head in ["''",'""','[]','{}','()']:
225 237 obj = eval(oname_head)
226 238 found = 1
227 239 ospace = 'Interactive'
228 240
229 241 return {'found':found, 'obj':obj, 'namespace':ospace,
230 242 'ismagic':ismagic, 'isalias':isalias}
231 243
232 244 def arg_err(self,func):
233 245 """Print docstring if incorrect arguments were passed"""
234 246 print 'Error in arguments:'
235 247 print OInspect.getdoc(func)
236 248
237 249 def format_latex(self,strng):
238 250 """Format a string for latex inclusion."""
239 251
240 252 # Characters that need to be escaped for latex:
241 253 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
242 254 # Magic command names as headers:
243 255 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
244 256 re.MULTILINE)
245 257 # Magic commands
246 258 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
247 259 re.MULTILINE)
248 260 # Paragraph continue
249 261 par_re = re.compile(r'\\$',re.MULTILINE)
250 262
251 263 # The "\n" symbol
252 264 newline_re = re.compile(r'\\n')
253 265
254 266 # Now build the string for output:
255 267 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
256 268 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
257 269 strng)
258 270 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
259 271 strng = par_re.sub(r'\\\\',strng)
260 272 strng = escape_re.sub(r'\\\1',strng)
261 273 strng = newline_re.sub(r'\\textbackslash{}n',strng)
262 274 return strng
263 275
264 276 def format_screen(self,strng):
265 277 """Format a string for screen printing.
266 278
267 279 This removes some latex-type format codes."""
268 280 # Paragraph continue
269 281 par_re = re.compile(r'\\$',re.MULTILINE)
270 282 strng = par_re.sub('',strng)
271 283 return strng
272 284
273 285 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
274 286 """Parse options passed to an argument string.
275 287
276 288 The interface is similar to that of getopt(), but it returns back a
277 289 Struct with the options as keys and the stripped argument string still
278 290 as a string.
279 291
280 292 arg_str is quoted as a true sys.argv vector by using shlex.split.
281 293 This allows us to easily expand variables, glob files, quote
282 294 arguments, etc.
283 295
284 296 Options:
285 297 -mode: default 'string'. If given as 'list', the argument string is
286 298 returned as a list (split on whitespace) instead of a string.
287 299
288 300 -list_all: put all option values in lists. Normally only options
289 301 appearing more than once are put in a list."""
290 302
291 303 # inject default options at the beginning of the input line
292 304 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
293 305 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
294 306
295 307 mode = kw.get('mode','string')
296 308 if mode not in ['string','list']:
297 309 raise ValueError,'incorrect mode given: %s' % mode
298 310 # Get options
299 311 list_all = kw.get('list_all',0)
300 312
301 313 # Check if we have more than one argument to warrant extra processing:
302 314 odict = {} # Dictionary with options
303 315 args = arg_str.split()
304 316 if len(args) >= 1:
305 317 # If the list of inputs only has 0 or 1 thing in it, there's no
306 318 # need to look for options
307 319 argv = shlex_split(arg_str)
308 320 # Do regular option processing
309 321 try:
310 322 opts,args = getopt(argv,opt_str,*long_opts)
311 323 except GetoptError,e:
312 324 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
313 325 " ".join(long_opts)))
314 326 for o,a in opts:
315 327 if o.startswith('--'):
316 328 o = o[2:]
317 329 else:
318 330 o = o[1:]
319 331 try:
320 332 odict[o].append(a)
321 333 except AttributeError:
322 334 odict[o] = [odict[o],a]
323 335 except KeyError:
324 336 if list_all:
325 337 odict[o] = [a]
326 338 else:
327 339 odict[o] = a
328 340
329 341 # Prepare opts,args for return
330 342 opts = Struct(odict)
331 343 if mode == 'string':
332 344 args = ' '.join(args)
333 345
334 346 return opts,args
335 347
336 348 #......................................................................
337 349 # And now the actual magic functions
338 350
339 351 # Functions for IPython shell work (vars,funcs, config, etc)
340 352 def magic_lsmagic(self, parameter_s = ''):
341 353 """List currently available magic functions."""
342 354 mesc = self.shell.ESC_MAGIC
343 355 print 'Available magic functions:\n'+mesc+\
344 356 (' '+mesc).join(self.lsmagic())
345 357 print '\n' + Magic.auto_status[self.shell.rc.automagic]
346 358 return None
347 359
348 360 def magic_magic(self, parameter_s = ''):
349 361 """Print information about the magic function system."""
350 362
351 363 mode = ''
352 364 try:
353 365 if parameter_s.split()[0] == '-latex':
354 366 mode = 'latex'
355 367 except:
356 368 pass
357 369
358 370 magic_docs = []
359 371 for fname in self.lsmagic():
360 372 mname = 'magic_' + fname
361 373 for space in (Magic,self,self.__class__):
362 374 try:
363 375 fn = space.__dict__[mname]
364 376 except KeyError:
365 377 pass
366 378 else:
367 379 break
368 380 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
369 381 fname,fn.__doc__))
370 382 magic_docs = ''.join(magic_docs)
371 383
372 384 if mode == 'latex':
373 385 print self.format_latex(magic_docs)
374 386 return
375 387 else:
376 388 magic_docs = self.format_screen(magic_docs)
377 389
378 390 outmsg = """
379 391 IPython's 'magic' functions
380 392 ===========================
381 393
382 394 The magic function system provides a series of functions which allow you to
383 395 control the behavior of IPython itself, plus a lot of system-type
384 396 features. All these functions are prefixed with a % character, but parameters
385 397 are given without parentheses or quotes.
386 398
387 399 NOTE: If you have 'automagic' enabled (via the command line option or with the
388 400 %automagic function), you don't need to type in the % explicitly. By default,
389 401 IPython ships with automagic on, so you should only rarely need the % escape.
390 402
391 403 Example: typing '%cd mydir' (without the quotes) changes you working directory
392 404 to 'mydir', if it exists.
393 405
394 406 You can define your own magic functions to extend the system. See the supplied
395 407 ipythonrc and example-magic.py files for details (in your ipython
396 408 configuration directory, typically $HOME/.ipython/).
397 409
398 410 You can also define your own aliased names for magic functions. In your
399 411 ipythonrc file, placing a line like:
400 412
401 413 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
402 414
403 415 will define %pf as a new name for %profile.
404 416
405 417 You can also call magics in code using the ipmagic() function, which IPython
406 418 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
407 419
408 420 For a list of the available magic functions, use %lsmagic. For a description
409 421 of any of them, type %magic_name?, e.g. '%cd?'.
410 422
411 423 Currently the magic system has the following functions:\n"""
412 424
413 425 mesc = self.shell.ESC_MAGIC
414 426 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
415 427 "\n\n%s%s\n\n%s" % (outmsg,
416 428 magic_docs,mesc,mesc,
417 429 (' '+mesc).join(self.lsmagic()),
418 430 Magic.auto_status[self.shell.rc.automagic] ) )
419 431
420 432 page(outmsg,screen_lines=self.shell.rc.screen_length)
421 433
422 434 def magic_automagic(self, parameter_s = ''):
423 435 """Make magic functions callable without having to type the initial %.
424 436
425 437 Toggles on/off (when off, you must call it as %automagic, of
426 438 course). Note that magic functions have lowest priority, so if there's
427 439 a variable whose name collides with that of a magic fn, automagic
428 440 won't work for that function (you get the variable instead). However,
429 441 if you delete the variable (del var), the previously shadowed magic
430 442 function becomes visible to automagic again."""
431 443
432 444 rc = self.shell.rc
433 445 rc.automagic = not rc.automagic
434 446 print '\n' + Magic.auto_status[rc.automagic]
435 447
436 448 def magic_autocall(self, parameter_s = ''):
437 449 """Make functions callable without having to type parentheses.
438 450
439 451 Usage:
440 452
441 453 %autocall [mode]
442 454
443 455 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
444 456 value is toggled on and off (remembering the previous state)."""
445 457
446 458 rc = self.shell.rc
447 459
448 460 if parameter_s:
449 461 arg = int(parameter_s)
450 462 else:
451 463 arg = 'toggle'
452 464
453 465 if not arg in (0,1,2,'toggle'):
454 466 error('Valid modes: (0->Off, 1->Smart, 2->Full')
455 467 return
456 468
457 469 if arg in (0,1,2):
458 470 rc.autocall = arg
459 471 else: # toggle
460 472 if rc.autocall:
461 473 self._magic_state.autocall_save = rc.autocall
462 474 rc.autocall = 0
463 475 else:
464 476 try:
465 477 rc.autocall = self._magic_state.autocall_save
466 478 except AttributeError:
467 479 rc.autocall = self._magic_state.autocall_save = 1
468 480
469 481 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
470 482
471 483 def magic_autoindent(self, parameter_s = ''):
472 484 """Toggle autoindent on/off (if available)."""
473 485
474 486 self.shell.set_autoindent()
475 487 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
476 488
477 489 def magic_system_verbose(self, parameter_s = ''):
478 490 """Toggle verbose printing of system calls on/off."""
479 491
480 492 self.shell.rc_set_toggle('system_verbose')
481 493 print "System verbose printing is:",\
482 494 ['OFF','ON'][self.shell.rc.system_verbose]
483 495
484 496 def magic_history(self, parameter_s = ''):
485 497 """Print input history (_i<n> variables), with most recent last.
486 498
487 499 %history -> print at most 40 inputs (some may be multi-line)\\
488 500 %history n -> print at most n inputs\\
489 501 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
490 502
491 503 Each input's number <n> is shown, and is accessible as the
492 504 automatically generated variable _i<n>. Multi-line statements are
493 505 printed starting at a new line for easy copy/paste.
494 506
495 507
496 508 Options:
497 509
498 510 -n: do NOT print line numbers. This is useful if you want to get a
499 511 printout of many lines which can be directly pasted into a text
500 512 editor.
501 513
502 514 This feature is only available if numbered prompts are in use.
503 515
504 516 -r: print the 'raw' history. IPython filters your input and
505 517 converts it all into valid Python source before executing it (things
506 518 like magics or aliases are turned into function calls, for
507 519 example). With this option, you'll see the unfiltered history
508 520 instead of the filtered version: '%cd /' will be seen as '%cd /'
509 521 instead of '_ip.magic("%cd /")'.
510 522 """
511 523
512 524 shell = self.shell
513 525 if not shell.outputcache.do_full_cache:
514 526 print 'This feature is only available if numbered prompts are in use.'
515 527 return
516 528 opts,args = self.parse_options(parameter_s,'nr',mode='list')
517 529
518 530 if opts.has_key('r'):
519 531 input_hist = shell.input_hist_raw
520 532 else:
521 533 input_hist = shell.input_hist
522 534
523 535 default_length = 40
524 536 if len(args) == 0:
525 537 final = len(input_hist)
526 538 init = max(1,final-default_length)
527 539 elif len(args) == 1:
528 540 final = len(input_hist)
529 541 init = max(1,final-int(args[0]))
530 542 elif len(args) == 2:
531 543 init,final = map(int,args)
532 544 else:
533 545 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
534 546 print self.magic_hist.__doc__
535 547 return
536 548 width = len(str(final))
537 549 line_sep = ['','\n']
538 550 print_nums = not opts.has_key('n')
539 551 for in_num in range(init,final):
540 552 inline = input_hist[in_num]
541 553 multiline = int(inline.count('\n') > 1)
542 554 if print_nums:
543 555 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
544 556 print inline,
545 557
546 558 def magic_hist(self, parameter_s=''):
547 559 """Alternate name for %history."""
548 560 return self.magic_history(parameter_s)
549 561
550 562 def magic_p(self, parameter_s=''):
551 563 """Just a short alias for Python's 'print'."""
552 564 exec 'print ' + parameter_s in self.shell.user_ns
553 565
554 566 def magic_r(self, parameter_s=''):
555 567 """Repeat previous input.
556 568
557 569 If given an argument, repeats the previous command which starts with
558 570 the same string, otherwise it just repeats the previous input.
559 571
560 572 Shell escaped commands (with ! as first character) are not recognized
561 573 by this system, only pure python code and magic commands.
562 574 """
563 575
564 576 start = parameter_s.strip()
565 577 esc_magic = self.shell.ESC_MAGIC
566 578 # Identify magic commands even if automagic is on (which means
567 579 # the in-memory version is different from that typed by the user).
568 580 if self.shell.rc.automagic:
569 581 start_magic = esc_magic+start
570 582 else:
571 583 start_magic = start
572 584 # Look through the input history in reverse
573 585 for n in range(len(self.shell.input_hist)-2,0,-1):
574 586 input = self.shell.input_hist[n]
575 587 # skip plain 'r' lines so we don't recurse to infinity
576 588 if input != '_ip.magic("r")\n' and \
577 589 (input.startswith(start) or input.startswith(start_magic)):
578 590 #print 'match',`input` # dbg
579 591 print 'Executing:',input,
580 592 self.shell.runlines(input)
581 593 return
582 594 print 'No previous input matching `%s` found.' % start
583 595
584 596 def magic_page(self, parameter_s=''):
585 597 """Pretty print the object and display it through a pager.
586 598
587 599 If no parameter is given, use _ (last output)."""
588 600 # After a function contributed by Olivier Aubert, slightly modified.
589 601
590 602 oname = parameter_s and parameter_s or '_'
591 603 info = self._ofind(oname)
592 604 if info['found']:
593 605 page(pformat(info['obj']))
594 606 else:
595 607 print 'Object `%s` not found' % oname
596 608
597 609 def magic_profile(self, parameter_s=''):
598 610 """Print your currently active IPyhton profile."""
599 611 if self.shell.rc.profile:
600 612 printpl('Current IPython profile: $self.shell.rc.profile.')
601 613 else:
602 614 print 'No profile active.'
603 615
604 616 def _inspect(self,meth,oname,**kw):
605 617 """Generic interface to the inspector system.
606 618
607 619 This function is meant to be called by pdef, pdoc & friends."""
608 620
609 621 oname = oname.strip()
610 622 info = Struct(self._ofind(oname))
611 623 if info.found:
612 624 pmethod = getattr(self.shell.inspector,meth)
613 625 formatter = info.ismagic and self.format_screen or None
614 626 if meth == 'pdoc':
615 627 pmethod(info.obj,oname,formatter)
616 628 elif meth == 'pinfo':
617 629 pmethod(info.obj,oname,formatter,info,**kw)
618 630 else:
619 631 pmethod(info.obj,oname)
620 632 else:
621 633 print 'Object `%s` not found.' % oname
622 634 return 'not found' # so callers can take other action
623 635
624 636 def magic_pdef(self, parameter_s=''):
625 637 """Print the definition header for any callable object.
626 638
627 639 If the object is a class, print the constructor information."""
628 640 self._inspect('pdef',parameter_s)
629 641
630 642 def magic_pdoc(self, parameter_s=''):
631 643 """Print the docstring for an object.
632 644
633 645 If the given object is a class, it will print both the class and the
634 646 constructor docstrings."""
635 647 self._inspect('pdoc',parameter_s)
636 648
637 649 def magic_psource(self, parameter_s=''):
638 650 """Print (or run through pager) the source code for an object."""
639 651 self._inspect('psource',parameter_s)
640 652
641 653 def magic_pfile(self, parameter_s=''):
642 654 """Print (or run through pager) the file where an object is defined.
643 655
644 656 The file opens at the line where the object definition begins. IPython
645 657 will honor the environment variable PAGER if set, and otherwise will
646 658 do its best to print the file in a convenient form.
647 659
648 660 If the given argument is not an object currently defined, IPython will
649 661 try to interpret it as a filename (automatically adding a .py extension
650 662 if needed). You can thus use %pfile as a syntax highlighting code
651 663 viewer."""
652 664
653 665 # first interpret argument as an object name
654 666 out = self._inspect('pfile',parameter_s)
655 667 # if not, try the input as a filename
656 668 if out == 'not found':
657 669 try:
658 670 filename = get_py_filename(parameter_s)
659 671 except IOError,msg:
660 672 print msg
661 673 return
662 674 page(self.shell.inspector.format(file(filename).read()))
663 675
664 676 def magic_pinfo(self, parameter_s=''):
665 677 """Provide detailed information about an object.
666 678
667 679 '%pinfo object' is just a synonym for object? or ?object."""
668 680
669 681 #print 'pinfo par: <%s>' % parameter_s # dbg
670 682
671 683 # detail_level: 0 -> obj? , 1 -> obj??
672 684 detail_level = 0
673 685 # We need to detect if we got called as 'pinfo pinfo foo', which can
674 686 # happen if the user types 'pinfo foo?' at the cmd line.
675 687 pinfo,qmark1,oname,qmark2 = \
676 688 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
677 689 if pinfo or qmark1 or qmark2:
678 690 detail_level = 1
679 691 if "*" in oname:
680 692 self.magic_psearch(oname)
681 693 else:
682 694 self._inspect('pinfo',oname,detail_level=detail_level)
683 695
684 696 def magic_psearch(self, parameter_s=''):
685 697 """Search for object in namespaces by wildcard.
686 698
687 699 %psearch [options] PATTERN [OBJECT TYPE]
688 700
689 701 Note: ? can be used as a synonym for %psearch, at the beginning or at
690 702 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
691 703 rest of the command line must be unchanged (options come first), so
692 704 for example the following forms are equivalent
693 705
694 706 %psearch -i a* function
695 707 -i a* function?
696 708 ?-i a* function
697 709
698 710 Arguments:
699 711
700 712 PATTERN
701 713
702 714 where PATTERN is a string containing * as a wildcard similar to its
703 715 use in a shell. The pattern is matched in all namespaces on the
704 716 search path. By default objects starting with a single _ are not
705 717 matched, many IPython generated objects have a single
706 718 underscore. The default is case insensitive matching. Matching is
707 719 also done on the attributes of objects and not only on the objects
708 720 in a module.
709 721
710 722 [OBJECT TYPE]
711 723
712 724 Is the name of a python type from the types module. The name is
713 725 given in lowercase without the ending type, ex. StringType is
714 726 written string. By adding a type here only objects matching the
715 727 given type are matched. Using all here makes the pattern match all
716 728 types (this is the default).
717 729
718 730 Options:
719 731
720 732 -a: makes the pattern match even objects whose names start with a
721 733 single underscore. These names are normally ommitted from the
722 734 search.
723 735
724 736 -i/-c: make the pattern case insensitive/sensitive. If neither of
725 737 these options is given, the default is read from your ipythonrc
726 738 file. The option name which sets this value is
727 739 'wildcards_case_sensitive'. If this option is not specified in your
728 740 ipythonrc file, IPython's internal default is to do a case sensitive
729 741 search.
730 742
731 743 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
732 744 specifiy can be searched in any of the following namespaces:
733 745 'builtin', 'user', 'user_global','internal', 'alias', where
734 746 'builtin' and 'user' are the search defaults. Note that you should
735 747 not use quotes when specifying namespaces.
736 748
737 749 'Builtin' contains the python module builtin, 'user' contains all
738 750 user data, 'alias' only contain the shell aliases and no python
739 751 objects, 'internal' contains objects used by IPython. The
740 752 'user_global' namespace is only used by embedded IPython instances,
741 753 and it contains module-level globals. You can add namespaces to the
742 754 search with -s or exclude them with -e (these options can be given
743 755 more than once).
744 756
745 757 Examples:
746 758
747 759 %psearch a* -> objects beginning with an a
748 760 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
749 761 %psearch a* function -> all functions beginning with an a
750 762 %psearch re.e* -> objects beginning with an e in module re
751 763 %psearch r*.e* -> objects that start with e in modules starting in r
752 764 %psearch r*.* string -> all strings in modules beginning with r
753 765
754 766 Case sensitve search:
755 767
756 768 %psearch -c a* list all object beginning with lower case a
757 769
758 770 Show objects beginning with a single _:
759 771
760 772 %psearch -a _* list objects beginning with a single underscore"""
761 773
762 774 # default namespaces to be searched
763 775 def_search = ['user','builtin']
764 776
765 777 # Process options/args
766 778 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
767 779 opt = opts.get
768 780 shell = self.shell
769 781 psearch = shell.inspector.psearch
770 782
771 783 # select case options
772 784 if opts.has_key('i'):
773 785 ignore_case = True
774 786 elif opts.has_key('c'):
775 787 ignore_case = False
776 788 else:
777 789 ignore_case = not shell.rc.wildcards_case_sensitive
778 790
779 791 # Build list of namespaces to search from user options
780 792 def_search.extend(opt('s',[]))
781 793 ns_exclude = ns_exclude=opt('e',[])
782 794 ns_search = [nm for nm in def_search if nm not in ns_exclude]
783 795
784 796 # Call the actual search
785 797 try:
786 798 psearch(args,shell.ns_table,ns_search,
787 799 show_all=opt('a'),ignore_case=ignore_case)
788 800 except:
789 801 shell.showtraceback()
790 802
791 803 def magic_who_ls(self, parameter_s=''):
792 804 """Return a sorted list of all interactive variables.
793 805
794 806 If arguments are given, only variables of types matching these
795 807 arguments are returned."""
796 808
797 809 user_ns = self.shell.user_ns
798 810 internal_ns = self.shell.internal_ns
799 811 user_config_ns = self.shell.user_config_ns
800 812 out = []
801 813 typelist = parameter_s.split()
802 814
803 815 for i in user_ns:
804 816 if not (i.startswith('_') or i.startswith('_i')) \
805 817 and not (i in internal_ns or i in user_config_ns):
806 818 if typelist:
807 819 if type(user_ns[i]).__name__ in typelist:
808 820 out.append(i)
809 821 else:
810 822 out.append(i)
811 823 out.sort()
812 824 return out
813 825
814 826 def magic_who(self, parameter_s=''):
815 827 """Print all interactive variables, with some minimal formatting.
816 828
817 829 If any arguments are given, only variables whose type matches one of
818 830 these are printed. For example:
819 831
820 832 %who function str
821 833
822 834 will only list functions and strings, excluding all other types of
823 835 variables. To find the proper type names, simply use type(var) at a
824 836 command line to see how python prints type names. For example:
825 837
826 838 In [1]: type('hello')\\
827 839 Out[1]: <type 'str'>
828 840
829 841 indicates that the type name for strings is 'str'.
830 842
831 843 %who always excludes executed names loaded through your configuration
832 844 file and things which are internal to IPython.
833 845
834 846 This is deliberate, as typically you may load many modules and the
835 847 purpose of %who is to show you only what you've manually defined."""
836 848
837 849 varlist = self.magic_who_ls(parameter_s)
838 850 if not varlist:
839 851 print 'Interactive namespace is empty.'
840 852 return
841 853
842 854 # if we have variables, move on...
843 855
844 856 # stupid flushing problem: when prompts have no separators, stdout is
845 857 # getting lost. I'm starting to think this is a python bug. I'm having
846 858 # to force a flush with a print because even a sys.stdout.flush
847 859 # doesn't seem to do anything!
848 860
849 861 count = 0
850 862 for i in varlist:
851 863 print i+'\t',
852 864 count += 1
853 865 if count > 8:
854 866 count = 0
855 867 print
856 868 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
857 869
858 870 print # well, this does force a flush at the expense of an extra \n
859 871
860 872 def magic_whos(self, parameter_s=''):
861 873 """Like %who, but gives some extra information about each variable.
862 874
863 875 The same type filtering of %who can be applied here.
864 876
865 877 For all variables, the type is printed. Additionally it prints:
866 878
867 879 - For {},[],(): their length.
868 880
869 881 - For Numeric arrays, a summary with shape, number of elements,
870 882 typecode and size in memory.
871 883
872 884 - Everything else: a string representation, snipping their middle if
873 885 too long."""
874 886
875 887 varnames = self.magic_who_ls(parameter_s)
876 888 if not varnames:
877 889 print 'Interactive namespace is empty.'
878 890 return
879 891
880 892 # if we have variables, move on...
881 893
882 894 # for these types, show len() instead of data:
883 895 seq_types = [types.DictType,types.ListType,types.TupleType]
884 896
885 897 # for Numeric arrays, display summary info
886 898 try:
887 899 import Numeric
888 900 except ImportError:
889 901 array_type = None
890 902 else:
891 903 array_type = Numeric.ArrayType.__name__
892 904
893 905 # Find all variable names and types so we can figure out column sizes
894 906 get_vars = lambda i: self.shell.user_ns[i]
895 907 type_name = lambda v: type(v).__name__
896 908 varlist = map(get_vars,varnames)
897 909
898 910 typelist = []
899 911 for vv in varlist:
900 912 tt = type_name(vv)
901 913 if tt=='instance':
902 914 typelist.append(str(vv.__class__))
903 915 else:
904 916 typelist.append(tt)
905 917
906 918 # column labels and # of spaces as separator
907 919 varlabel = 'Variable'
908 920 typelabel = 'Type'
909 921 datalabel = 'Data/Info'
910 922 colsep = 3
911 923 # variable format strings
912 924 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
913 925 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
914 926 aformat = "%s: %s elems, type `%s`, %s bytes"
915 927 # find the size of the columns to format the output nicely
916 928 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
917 929 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
918 930 # table header
919 931 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
920 932 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
921 933 # and the table itself
922 934 kb = 1024
923 935 Mb = 1048576 # kb**2
924 936 for vname,var,vtype in zip(varnames,varlist,typelist):
925 937 print itpl(vformat),
926 938 if vtype in seq_types:
927 939 print len(var)
928 940 elif vtype==array_type:
929 941 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
930 942 vsize = Numeric.size(var)
931 943 vbytes = vsize*var.itemsize()
932 944 if vbytes < 100000:
933 945 print aformat % (vshape,vsize,var.typecode(),vbytes)
934 946 else:
935 947 print aformat % (vshape,vsize,var.typecode(),vbytes),
936 948 if vbytes < Mb:
937 949 print '(%s kb)' % (vbytes/kb,)
938 950 else:
939 951 print '(%s Mb)' % (vbytes/Mb,)
940 952 else:
941 953 vstr = str(var).replace('\n','\\n')
942 954 if len(vstr) < 50:
943 955 print vstr
944 956 else:
945 957 printpl(vfmt_short)
946 958
947 959 def magic_reset(self, parameter_s=''):
948 960 """Resets the namespace by removing all names defined by the user.
949 961
950 962 Input/Output history are left around in case you need them."""
951 963
952 964 ans = raw_input(
953 965 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
954 966 if not ans.lower() == 'y':
955 967 print 'Nothing done.'
956 968 return
957 969 user_ns = self.shell.user_ns
958 970 for i in self.magic_who_ls():
959 971 del(user_ns[i])
960 972
961 973 def magic_config(self,parameter_s=''):
962 974 """Show IPython's internal configuration."""
963 975
964 976 page('Current configuration structure:\n'+
965 977 pformat(self.shell.rc.dict()))
966 978
967 979 def magic_logstart(self,parameter_s=''):
968 980 """Start logging anywhere in a session.
969 981
970 982 %logstart [-o|-t] [log_name [log_mode]]
971 983
972 984 If no name is given, it defaults to a file named 'ipython_log.py' in your
973 985 current directory, in 'rotate' mode (see below).
974 986
975 987 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
976 988 history up to that point and then continues logging.
977 989
978 990 %logstart takes a second optional parameter: logging mode. This can be one
979 991 of (note that the modes are given unquoted):\\
980 992 append: well, that says it.\\
981 993 backup: rename (if exists) to name~ and start name.\\
982 994 global: single logfile in your home dir, appended to.\\
983 995 over : overwrite existing log.\\
984 996 rotate: create rotating logs name.1~, name.2~, etc.
985 997
986 998 Options:
987 999
988 1000 -o: log also IPython's output. In this mode, all commands which
989 1001 generate an Out[NN] prompt are recorded to the logfile, right after
990 1002 their corresponding input line. The output lines are always
991 1003 prepended with a '#[Out]# ' marker, so that the log remains valid
992 1004 Python code.
993 1005
994 1006 Since this marker is always the same, filtering only the output from
995 1007 a log is very easy, using for example a simple awk call:
996 1008
997 1009 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
998 1010
999 1011 -t: put timestamps before each input line logged (these are put in
1000 1012 comments)."""
1001 1013
1002 1014 opts,par = self.parse_options(parameter_s,'ot')
1003 1015 log_output = 'o' in opts
1004 1016 timestamp = 't' in opts
1005 1017
1006 1018 rc = self.shell.rc
1007 1019 logger = self.shell.logger
1008 1020
1009 1021 # if no args are given, the defaults set in the logger constructor by
1010 1022 # ipytohn remain valid
1011 1023 if par:
1012 1024 try:
1013 1025 logfname,logmode = par.split()
1014 1026 except:
1015 1027 logfname = par
1016 1028 logmode = 'backup'
1017 1029 else:
1018 1030 logfname = logger.logfname
1019 1031 logmode = logger.logmode
1020 1032 # put logfname into rc struct as if it had been called on the command
1021 1033 # line, so it ends up saved in the log header Save it in case we need
1022 1034 # to restore it...
1023 1035 old_logfile = rc.opts.get('logfile','')
1024 1036 if logfname:
1025 1037 logfname = os.path.expanduser(logfname)
1026 1038 rc.opts.logfile = logfname
1027 1039 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1028 1040 try:
1029 1041 started = logger.logstart(logfname,loghead,logmode,
1030 1042 log_output,timestamp)
1031 1043 except:
1032 1044 rc.opts.logfile = old_logfile
1033 1045 warn("Couldn't start log: %s" % sys.exc_info()[1])
1034 1046 else:
1035 1047 # log input history up to this point, optionally interleaving
1036 1048 # output if requested
1037 1049
1038 1050 if timestamp:
1039 1051 # disable timestamping for the previous history, since we've
1040 1052 # lost those already (no time machine here).
1041 1053 logger.timestamp = False
1042 1054 if log_output:
1043 1055 log_write = logger.log_write
1044 1056 input_hist = self.shell.input_hist
1045 1057 output_hist = self.shell.output_hist
1046 1058 for n in range(1,len(input_hist)-1):
1047 1059 log_write(input_hist[n].rstrip())
1048 1060 if n in output_hist:
1049 1061 log_write(repr(output_hist[n]),'output')
1050 1062 else:
1051 1063 logger.log_write(self.shell.input_hist[1:])
1052 1064 if timestamp:
1053 1065 # re-enable timestamping
1054 1066 logger.timestamp = True
1055 1067
1056 1068 print ('Activating auto-logging. '
1057 1069 'Current session state plus future input saved.')
1058 1070 logger.logstate()
1059 1071
1060 1072 def magic_logoff(self,parameter_s=''):
1061 1073 """Temporarily stop logging.
1062 1074
1063 1075 You must have previously started logging."""
1064 1076 self.shell.logger.switch_log(0)
1065 1077
1066 1078 def magic_logon(self,parameter_s=''):
1067 1079 """Restart logging.
1068 1080
1069 1081 This function is for restarting logging which you've temporarily
1070 1082 stopped with %logoff. For starting logging for the first time, you
1071 1083 must use the %logstart function, which allows you to specify an
1072 1084 optional log filename."""
1073 1085
1074 1086 self.shell.logger.switch_log(1)
1075 1087
1076 1088 def magic_logstate(self,parameter_s=''):
1077 1089 """Print the status of the logging system."""
1078 1090
1079 1091 self.shell.logger.logstate()
1080 1092
1081 1093 def magic_pdb(self, parameter_s=''):
1082 1094 """Control the calling of the pdb interactive debugger.
1083 1095
1084 1096 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1085 1097 argument it works as a toggle.
1086 1098
1087 1099 When an exception is triggered, IPython can optionally call the
1088 1100 interactive pdb debugger after the traceback printout. %pdb toggles
1089 1101 this feature on and off."""
1090 1102
1091 1103 par = parameter_s.strip().lower()
1092 1104
1093 1105 if par:
1094 1106 try:
1095 1107 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1096 1108 except KeyError:
1097 1109 print ('Incorrect argument. Use on/1, off/0, '
1098 1110 'or nothing for a toggle.')
1099 1111 return
1100 1112 else:
1101 1113 # toggle
1102 1114 new_pdb = not self.shell.InteractiveTB.call_pdb
1103 1115
1104 1116 # set on the shell
1105 1117 self.shell.call_pdb = new_pdb
1106 1118 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1107 1119
1108 1120 def magic_prun(self, parameter_s ='',user_mode=1,
1109 1121 opts=None,arg_lst=None,prog_ns=None):
1110 1122
1111 1123 """Run a statement through the python code profiler.
1112 1124
1113 1125 Usage:\\
1114 1126 %prun [options] statement
1115 1127
1116 1128 The given statement (which doesn't require quote marks) is run via the
1117 1129 python profiler in a manner similar to the profile.run() function.
1118 1130 Namespaces are internally managed to work correctly; profile.run
1119 1131 cannot be used in IPython because it makes certain assumptions about
1120 1132 namespaces which do not hold under IPython.
1121 1133
1122 1134 Options:
1123 1135
1124 1136 -l <limit>: you can place restrictions on what or how much of the
1125 1137 profile gets printed. The limit value can be:
1126 1138
1127 1139 * A string: only information for function names containing this string
1128 1140 is printed.
1129 1141
1130 1142 * An integer: only these many lines are printed.
1131 1143
1132 1144 * A float (between 0 and 1): this fraction of the report is printed
1133 1145 (for example, use a limit of 0.4 to see the topmost 40% only).
1134 1146
1135 1147 You can combine several limits with repeated use of the option. For
1136 1148 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1137 1149 information about class constructors.
1138 1150
1139 1151 -r: return the pstats.Stats object generated by the profiling. This
1140 1152 object has all the information about the profile in it, and you can
1141 1153 later use it for further analysis or in other functions.
1142 1154
1143 1155 Since magic functions have a particular form of calling which prevents
1144 1156 you from writing something like:\\
1145 1157 In [1]: p = %prun -r print 4 # invalid!\\
1146 1158 you must instead use IPython's automatic variables to assign this:\\
1147 1159 In [1]: %prun -r print 4 \\
1148 1160 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1149 1161 In [2]: stats = _
1150 1162
1151 1163 If you really need to assign this value via an explicit function call,
1152 1164 you can always tap directly into the true name of the magic function
1153 1165 by using the _ip.magic function:\\
1154 1166 In [3]: stats = _ip.magic('prun','-r print 4')
1155 1167
1156 1168 You can type _ip.magic? for more details.
1157 1169
1158 1170 -s <key>: sort profile by given key. You can provide more than one key
1159 1171 by using the option several times: '-s key1 -s key2 -s key3...'. The
1160 1172 default sorting key is 'time'.
1161 1173
1162 1174 The following is copied verbatim from the profile documentation
1163 1175 referenced below:
1164 1176
1165 1177 When more than one key is provided, additional keys are used as
1166 1178 secondary criteria when the there is equality in all keys selected
1167 1179 before them.
1168 1180
1169 1181 Abbreviations can be used for any key names, as long as the
1170 1182 abbreviation is unambiguous. The following are the keys currently
1171 1183 defined:
1172 1184
1173 1185 Valid Arg Meaning\\
1174 1186 "calls" call count\\
1175 1187 "cumulative" cumulative time\\
1176 1188 "file" file name\\
1177 1189 "module" file name\\
1178 1190 "pcalls" primitive call count\\
1179 1191 "line" line number\\
1180 1192 "name" function name\\
1181 1193 "nfl" name/file/line\\
1182 1194 "stdname" standard name\\
1183 1195 "time" internal time
1184 1196
1185 1197 Note that all sorts on statistics are in descending order (placing
1186 1198 most time consuming items first), where as name, file, and line number
1187 1199 searches are in ascending order (i.e., alphabetical). The subtle
1188 1200 distinction between "nfl" and "stdname" is that the standard name is a
1189 1201 sort of the name as printed, which means that the embedded line
1190 1202 numbers get compared in an odd way. For example, lines 3, 20, and 40
1191 1203 would (if the file names were the same) appear in the string order
1192 1204 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1193 1205 line numbers. In fact, sort_stats("nfl") is the same as
1194 1206 sort_stats("name", "file", "line").
1195 1207
1196 1208 -T <filename>: save profile results as shown on screen to a text
1197 1209 file. The profile is still shown on screen.
1198 1210
1199 1211 -D <filename>: save (via dump_stats) profile statistics to given
1200 1212 filename. This data is in a format understod by the pstats module, and
1201 1213 is generated by a call to the dump_stats() method of profile
1202 1214 objects. The profile is still shown on screen.
1203 1215
1204 1216 If you want to run complete programs under the profiler's control, use
1205 1217 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1206 1218 contains profiler specific options as described here.
1207 1219
1208 1220 You can read the complete documentation for the profile module with:\\
1209 1221 In [1]: import profile; profile.help() """
1210 1222
1211 1223 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1212 1224 # protect user quote marks
1213 1225 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1214 1226
1215 1227 if user_mode: # regular user call
1216 1228 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1217 1229 list_all=1)
1218 1230 namespace = self.shell.user_ns
1219 1231 else: # called to run a program by %run -p
1220 1232 try:
1221 1233 filename = get_py_filename(arg_lst[0])
1222 1234 except IOError,msg:
1223 1235 error(msg)
1224 1236 return
1225 1237
1226 1238 arg_str = 'execfile(filename,prog_ns)'
1227 1239 namespace = locals()
1228 1240
1229 1241 opts.merge(opts_def)
1230 1242
1231 1243 prof = profile.Profile()
1232 1244 try:
1233 1245 prof = prof.runctx(arg_str,namespace,namespace)
1234 1246 sys_exit = ''
1235 1247 except SystemExit:
1236 1248 sys_exit = """*** SystemExit exception caught in code being profiled."""
1237 1249
1238 1250 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1239 1251
1240 1252 lims = opts.l
1241 1253 if lims:
1242 1254 lims = [] # rebuild lims with ints/floats/strings
1243 1255 for lim in opts.l:
1244 1256 try:
1245 1257 lims.append(int(lim))
1246 1258 except ValueError:
1247 1259 try:
1248 1260 lims.append(float(lim))
1249 1261 except ValueError:
1250 1262 lims.append(lim)
1251 1263
1252 1264 # trap output
1253 1265 sys_stdout = sys.stdout
1254 1266 stdout_trap = StringIO()
1255 1267 try:
1256 1268 sys.stdout = stdout_trap
1257 1269 stats.print_stats(*lims)
1258 1270 finally:
1259 1271 sys.stdout = sys_stdout
1260 1272 output = stdout_trap.getvalue()
1261 1273 output = output.rstrip()
1262 1274
1263 1275 page(output,screen_lines=self.shell.rc.screen_length)
1264 1276 print sys_exit,
1265 1277
1266 1278 dump_file = opts.D[0]
1267 1279 text_file = opts.T[0]
1268 1280 if dump_file:
1269 1281 prof.dump_stats(dump_file)
1270 1282 print '\n*** Profile stats marshalled to file',\
1271 1283 `dump_file`+'.',sys_exit
1272 1284 if text_file:
1273 1285 file(text_file,'w').write(output)
1274 1286 print '\n*** Profile printout saved to text file',\
1275 1287 `text_file`+'.',sys_exit
1276 1288
1277 1289 if opts.has_key('r'):
1278 1290 return stats
1279 1291 else:
1280 1292 return None
1281 1293
1282 1294 def magic_run(self, parameter_s ='',runner=None):
1283 1295 """Run the named file inside IPython as a program.
1284 1296
1285 1297 Usage:\\
1286 1298 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1287 1299
1288 1300 Parameters after the filename are passed as command-line arguments to
1289 1301 the program (put in sys.argv). Then, control returns to IPython's
1290 1302 prompt.
1291 1303
1292 1304 This is similar to running at a system prompt:\\
1293 1305 $ python file args\\
1294 1306 but with the advantage of giving you IPython's tracebacks, and of
1295 1307 loading all variables into your interactive namespace for further use
1296 1308 (unless -p is used, see below).
1297 1309
1298 1310 The file is executed in a namespace initially consisting only of
1299 1311 __name__=='__main__' and sys.argv constructed as indicated. It thus
1300 1312 sees its environment as if it were being run as a stand-alone
1301 1313 program. But after execution, the IPython interactive namespace gets
1302 1314 updated with all variables defined in the program (except for __name__
1303 1315 and sys.argv). This allows for very convenient loading of code for
1304 1316 interactive work, while giving each program a 'clean sheet' to run in.
1305 1317
1306 1318 Options:
1307 1319
1308 1320 -n: __name__ is NOT set to '__main__', but to the running file's name
1309 1321 without extension (as python does under import). This allows running
1310 1322 scripts and reloading the definitions in them without calling code
1311 1323 protected by an ' if __name__ == "__main__" ' clause.
1312 1324
1313 1325 -i: run the file in IPython's namespace instead of an empty one. This
1314 1326 is useful if you are experimenting with code written in a text editor
1315 1327 which depends on variables defined interactively.
1316 1328
1317 1329 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1318 1330 being run. This is particularly useful if IPython is being used to
1319 1331 run unittests, which always exit with a sys.exit() call. In such
1320 1332 cases you are interested in the output of the test results, not in
1321 1333 seeing a traceback of the unittest module.
1322 1334
1323 1335 -t: print timing information at the end of the run. IPython will give
1324 1336 you an estimated CPU time consumption for your script, which under
1325 1337 Unix uses the resource module to avoid the wraparound problems of
1326 1338 time.clock(). Under Unix, an estimate of time spent on system tasks
1327 1339 is also given (for Windows platforms this is reported as 0.0).
1328 1340
1329 1341 If -t is given, an additional -N<N> option can be given, where <N>
1330 1342 must be an integer indicating how many times you want the script to
1331 1343 run. The final timing report will include total and per run results.
1332 1344
1333 1345 For example (testing the script uniq_stable.py):
1334 1346
1335 1347 In [1]: run -t uniq_stable
1336 1348
1337 1349 IPython CPU timings (estimated):\\
1338 1350 User : 0.19597 s.\\
1339 1351 System: 0.0 s.\\
1340 1352
1341 1353 In [2]: run -t -N5 uniq_stable
1342 1354
1343 1355 IPython CPU timings (estimated):\\
1344 1356 Total runs performed: 5\\
1345 1357 Times : Total Per run\\
1346 1358 User : 0.910862 s, 0.1821724 s.\\
1347 1359 System: 0.0 s, 0.0 s.
1348 1360
1349 1361 -d: run your program under the control of pdb, the Python debugger.
1350 1362 This allows you to execute your program step by step, watch variables,
1351 1363 etc. Internally, what IPython does is similar to calling:
1352 1364
1353 1365 pdb.run('execfile("YOURFILENAME")')
1354 1366
1355 1367 with a breakpoint set on line 1 of your file. You can change the line
1356 1368 number for this automatic breakpoint to be <N> by using the -bN option
1357 1369 (where N must be an integer). For example:
1358 1370
1359 1371 %run -d -b40 myscript
1360 1372
1361 1373 will set the first breakpoint at line 40 in myscript.py. Note that
1362 1374 the first breakpoint must be set on a line which actually does
1363 1375 something (not a comment or docstring) for it to stop execution.
1364 1376
1365 1377 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1366 1378 first enter 'c' (without qoutes) to start execution up to the first
1367 1379 breakpoint.
1368 1380
1369 1381 Entering 'help' gives information about the use of the debugger. You
1370 1382 can easily see pdb's full documentation with "import pdb;pdb.help()"
1371 1383 at a prompt.
1372 1384
1373 1385 -p: run program under the control of the Python profiler module (which
1374 1386 prints a detailed report of execution times, function calls, etc).
1375 1387
1376 1388 You can pass other options after -p which affect the behavior of the
1377 1389 profiler itself. See the docs for %prun for details.
1378 1390
1379 1391 In this mode, the program's variables do NOT propagate back to the
1380 1392 IPython interactive namespace (because they remain in the namespace
1381 1393 where the profiler executes them).
1382 1394
1383 1395 Internally this triggers a call to %prun, see its documentation for
1384 1396 details on the options available specifically for profiling."""
1385 1397
1386 1398 # get arguments and set sys.argv for program to be run.
1387 1399 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1388 1400 mode='list',list_all=1)
1389 1401
1390 1402 try:
1391 1403 filename = get_py_filename(arg_lst[0])
1392 1404 except IndexError:
1393 1405 warn('you must provide at least a filename.')
1394 1406 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1395 1407 return
1396 1408 except IOError,msg:
1397 1409 error(msg)
1398 1410 return
1399 1411
1400 1412 # Control the response to exit() calls made by the script being run
1401 1413 exit_ignore = opts.has_key('e')
1402 1414
1403 1415 # Make sure that the running script gets a proper sys.argv as if it
1404 1416 # were run from a system shell.
1405 1417 save_argv = sys.argv # save it for later restoring
1406 1418 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1407 1419
1408 1420 if opts.has_key('i'):
1409 1421 prog_ns = self.shell.user_ns
1410 1422 __name__save = self.shell.user_ns['__name__']
1411 1423 prog_ns['__name__'] = '__main__'
1412 1424 else:
1413 1425 if opts.has_key('n'):
1414 1426 name = os.path.splitext(os.path.basename(filename))[0]
1415 1427 else:
1416 1428 name = '__main__'
1417 1429 prog_ns = {'__name__':name}
1418 1430
1419 1431 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1420 1432 # set the __file__ global in the script's namespace
1421 1433 prog_ns['__file__'] = filename
1422 1434
1423 1435 # pickle fix. See iplib for an explanation. But we need to make sure
1424 1436 # that, if we overwrite __main__, we replace it at the end
1425 1437 if prog_ns['__name__'] == '__main__':
1426 1438 restore_main = sys.modules['__main__']
1427 1439 else:
1428 1440 restore_main = False
1429 1441
1430 1442 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1431 1443
1432 1444 stats = None
1433 1445 try:
1434 1446 if opts.has_key('p'):
1435 1447 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1436 1448 else:
1437 1449 if opts.has_key('d'):
1438 1450 deb = Debugger.Pdb(self.shell.rc.colors)
1439 1451 # reset Breakpoint state, which is moronically kept
1440 1452 # in a class
1441 1453 bdb.Breakpoint.next = 1
1442 1454 bdb.Breakpoint.bplist = {}
1443 1455 bdb.Breakpoint.bpbynumber = [None]
1444 1456 # Set an initial breakpoint to stop execution
1445 1457 maxtries = 10
1446 1458 bp = int(opts.get('b',[1])[0])
1447 1459 checkline = deb.checkline(filename,bp)
1448 1460 if not checkline:
1449 1461 for bp in range(bp+1,bp+maxtries+1):
1450 1462 if deb.checkline(filename,bp):
1451 1463 break
1452 1464 else:
1453 1465 msg = ("\nI failed to find a valid line to set "
1454 1466 "a breakpoint\n"
1455 1467 "after trying up to line: %s.\n"
1456 1468 "Please set a valid breakpoint manually "
1457 1469 "with the -b option." % bp)
1458 1470 error(msg)
1459 1471 return
1460 1472 # if we find a good linenumber, set the breakpoint
1461 1473 deb.do_break('%s:%s' % (filename,bp))
1462 1474 # Start file run
1463 1475 print "NOTE: Enter 'c' at the",
1464 1476 print "ipdb> prompt to start your script."
1465 1477 try:
1466 1478 deb.run('execfile("%s")' % filename,prog_ns)
1467 1479 except:
1468 1480 etype, value, tb = sys.exc_info()
1469 1481 # Skip three frames in the traceback: the %run one,
1470 1482 # one inside bdb.py, and the command-line typed by the
1471 1483 # user (run by exec in pdb itself).
1472 1484 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1473 1485 else:
1474 1486 if runner is None:
1475 1487 runner = self.shell.safe_execfile
1476 1488 if opts.has_key('t'):
1477 1489 try:
1478 1490 nruns = int(opts['N'][0])
1479 1491 if nruns < 1:
1480 1492 error('Number of runs must be >=1')
1481 1493 return
1482 1494 except (KeyError):
1483 1495 nruns = 1
1484 1496 if nruns == 1:
1485 1497 t0 = clock2()
1486 1498 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1487 1499 t1 = clock2()
1488 1500 t_usr = t1[0]-t0[0]
1489 1501 t_sys = t1[1]-t1[1]
1490 1502 print "\nIPython CPU timings (estimated):"
1491 1503 print " User : %10s s." % t_usr
1492 1504 print " System: %10s s." % t_sys
1493 1505 else:
1494 1506 runs = range(nruns)
1495 1507 t0 = clock2()
1496 1508 for nr in runs:
1497 1509 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1498 1510 t1 = clock2()
1499 1511 t_usr = t1[0]-t0[0]
1500 1512 t_sys = t1[1]-t1[1]
1501 1513 print "\nIPython CPU timings (estimated):"
1502 1514 print "Total runs performed:",nruns
1503 1515 print " Times : %10s %10s" % ('Total','Per run')
1504 1516 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1505 1517 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1506 1518
1507 1519 else:
1508 1520 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1509 1521 if opts.has_key('i'):
1510 1522 self.shell.user_ns['__name__'] = __name__save
1511 1523 else:
1512 1524 # update IPython interactive namespace
1513 1525 del prog_ns['__name__']
1514 1526 self.shell.user_ns.update(prog_ns)
1515 1527 finally:
1516 1528 sys.argv = save_argv
1517 1529 if restore_main:
1518 1530 sys.modules['__main__'] = restore_main
1519 1531 return stats
1520 1532
1521 1533 def magic_runlog(self, parameter_s =''):
1522 1534 """Run files as logs.
1523 1535
1524 1536 Usage:\\
1525 1537 %runlog file1 file2 ...
1526 1538
1527 1539 Run the named files (treating them as log files) in sequence inside
1528 1540 the interpreter, and return to the prompt. This is much slower than
1529 1541 %run because each line is executed in a try/except block, but it
1530 1542 allows running files with syntax errors in them.
1531 1543
1532 1544 Normally IPython will guess when a file is one of its own logfiles, so
1533 1545 you can typically use %run even for logs. This shorthand allows you to
1534 1546 force any file to be treated as a log file."""
1535 1547
1536 1548 for f in parameter_s.split():
1537 1549 self.shell.safe_execfile(f,self.shell.user_ns,
1538 1550 self.shell.user_ns,islog=1)
1539 1551
1540 1552 def magic_time(self,parameter_s = ''):
1541 1553 """Time execution of a Python statement or expression.
1542 1554
1543 1555 The CPU and wall clock times are printed, and the value of the
1544 1556 expression (if any) is returned. Note that under Win32, system time
1545 1557 is always reported as 0, since it can not be measured.
1546 1558
1547 1559 This function provides very basic timing functionality. In Python
1548 1560 2.3, the timeit module offers more control and sophistication, but for
1549 1561 now IPython supports Python 2.2, so we can not rely on timeit being
1550 1562 present.
1551 1563
1552 1564 Some examples:
1553 1565
1554 1566 In [1]: time 2**128
1555 1567 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1556 1568 Wall time: 0.00
1557 1569 Out[1]: 340282366920938463463374607431768211456L
1558 1570
1559 1571 In [2]: n = 1000000
1560 1572
1561 1573 In [3]: time sum(range(n))
1562 1574 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1563 1575 Wall time: 1.37
1564 1576 Out[3]: 499999500000L
1565 1577
1566 1578 In [4]: time print 'hello world'
1567 1579 hello world
1568 1580 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1569 1581 Wall time: 0.00
1570 1582 """
1571 1583
1572 1584 # fail immediately if the given expression can't be compiled
1573 1585 try:
1574 1586 mode = 'eval'
1575 1587 code = compile(parameter_s,'<timed eval>',mode)
1576 1588 except SyntaxError:
1577 1589 mode = 'exec'
1578 1590 code = compile(parameter_s,'<timed exec>',mode)
1579 1591 # skew measurement as little as possible
1580 1592 glob = self.shell.user_ns
1581 1593 clk = clock2
1582 1594 wtime = time.time
1583 1595 # time execution
1584 1596 wall_st = wtime()
1585 1597 if mode=='eval':
1586 1598 st = clk()
1587 1599 out = eval(code,glob)
1588 1600 end = clk()
1589 1601 else:
1590 1602 st = clk()
1591 1603 exec code in glob
1592 1604 end = clk()
1593 1605 out = None
1594 1606 wall_end = wtime()
1595 1607 # Compute actual times and report
1596 1608 wall_time = wall_end-wall_st
1597 1609 cpu_user = end[0]-st[0]
1598 1610 cpu_sys = end[1]-st[1]
1599 1611 cpu_tot = cpu_user+cpu_sys
1600 1612 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1601 1613 (cpu_user,cpu_sys,cpu_tot)
1602 1614 print "Wall time: %.2f" % wall_time
1603 1615 return out
1604 1616
1605 1617 def magic_macro(self,parameter_s = ''):
1606 1618 """Define a set of input lines as a macro for future re-execution.
1607 1619
1608 1620 Usage:\\
1609 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1621 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1622
1623 Options:
1624
1625 -r: use 'raw' input. By default, the 'processed' history is used,
1626 so that magics are loaded in their transformed version to valid
1627 Python. If this option is given, the raw input as typed as the
1628 command line is used instead.
1610 1629
1611 1630 This will define a global variable called `name` which is a string
1612 1631 made of joining the slices and lines you specify (n1,n2,... numbers
1613 1632 above) from your input history into a single string. This variable
1614 1633 acts like an automatic function which re-executes those lines as if
1615 1634 you had typed them. You just type 'name' at the prompt and the code
1616 1635 executes.
1617 1636
1618 1637 The notation for indicating number ranges is: n1-n2 means 'use line
1619 1638 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1620 1639 using the lines numbered 5,6 and 7.
1621 1640
1622 1641 Note: as a 'hidden' feature, you can also use traditional python slice
1623 1642 notation, where N:M means numbers N through M-1.
1624 1643
1625 1644 For example, if your history contains (%hist prints it):
1626 1645
1627 1646 44: x=1\\
1628 1647 45: y=3\\
1629 1648 46: z=x+y\\
1630 1649 47: print x\\
1631 1650 48: a=5\\
1632 1651 49: print 'x',x,'y',y\\
1633 1652
1634 1653 you can create a macro with lines 44 through 47 (included) and line 49
1635 1654 called my_macro with:
1636 1655
1637 1656 In [51]: %macro my_macro 44-47 49
1638 1657
1639 1658 Now, typing `my_macro` (without quotes) will re-execute all this code
1640 1659 in one pass.
1641 1660
1642 1661 You don't need to give the line-numbers in order, and any given line
1643 1662 number can appear multiple times. You can assemble macros with any
1644 1663 lines from your input history in any order.
1645 1664
1646 1665 The macro is a simple object which holds its value in an attribute,
1647 1666 but IPython's display system checks for macros and executes them as
1648 1667 code instead of printing them when you type their name.
1649 1668
1650 1669 You can view a macro's contents by explicitly printing it with:
1651 1670
1652 1671 'print macro_name'.
1653 1672
1654 1673 For one-off cases which DON'T contain magic function calls in them you
1655 1674 can obtain similar results by explicitly executing slices from your
1656 1675 input history with:
1657 1676
1658 1677 In [60]: exec In[44:48]+In[49]"""
1659 1678
1660 args = parameter_s.split()
1679 opts,args = self.parse_options(parameter_s,'r')
1661 1680 name,ranges = args[0], args[1:]
1662 1681 #print 'rng',ranges # dbg
1663 lines = self.extract_input_slices(ranges)
1682 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1664 1683 macro = Macro(lines)
1665 1684 self.shell.user_ns.update({name:macro})
1666 1685 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1667 1686 print 'Macro contents:'
1668 1687 print macro,
1669 1688
1670 1689 def magic_save(self,parameter_s = ''):
1671 1690 """Save a set of lines to a given filename.
1672 1691
1673 1692 Usage:\\
1674 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1693 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1694
1695 Options:
1696
1697 -r: use 'raw' input. By default, the 'processed' history is used,
1698 so that magics are loaded in their transformed version to valid
1699 Python. If this option is given, the raw input as typed as the
1700 command line is used instead.
1675 1701
1676 1702 This function uses the same syntax as %macro for line extraction, but
1677 1703 instead of creating a macro it saves the resulting string to the
1678 1704 filename you specify.
1679 1705
1680 1706 It adds a '.py' extension to the file if you don't do so yourself, and
1681 1707 it asks for confirmation before overwriting existing files."""
1682 1708
1683 args = parameter_s.split()
1709 opts,args = self.parse_options(parameter_s,'r')
1684 1710 fname,ranges = args[0], args[1:]
1685 1711 if not fname.endswith('.py'):
1686 1712 fname += '.py'
1687 1713 if os.path.isfile(fname):
1688 1714 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1689 1715 if ans.lower() not in ['y','yes']:
1690 1716 print 'Operation cancelled.'
1691 1717 return
1692 cmds = ''.join(self.extract_input_slices(ranges))
1718 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1693 1719 f = file(fname,'w')
1694 1720 f.write(cmds)
1695 1721 f.close()
1696 1722 print 'The following commands were written to file `%s`:' % fname
1697 1723 print cmds
1698 1724
1699 1725 def _edit_macro(self,mname,macro):
1700 1726 """open an editor with the macro data in a file"""
1701 1727 filename = self.shell.mktempfile(macro.value)
1702 1728 self.shell.hooks.editor(filename)
1703 1729
1704 1730 # and make a new macro object, to replace the old one
1705 1731 mfile = open(filename)
1706 1732 mvalue = mfile.read()
1707 1733 mfile.close()
1708 1734 self.shell.user_ns[mname] = Macro(mvalue)
1709 1735
1710 1736 def magic_ed(self,parameter_s=''):
1711 1737 """Alias to %edit."""
1712 1738 return self.magic_edit(parameter_s)
1713 1739
1714 1740 def magic_edit(self,parameter_s='',last_call=['','']):
1715 1741 """Bring up an editor and execute the resulting code.
1716 1742
1717 1743 Usage:
1718 1744 %edit [options] [args]
1719 1745
1720 1746 %edit runs IPython's editor hook. The default version of this hook is
1721 1747 set to call the __IPYTHON__.rc.editor command. This is read from your
1722 1748 environment variable $EDITOR. If this isn't found, it will default to
1723 1749 vi under Linux/Unix and to notepad under Windows. See the end of this
1724 1750 docstring for how to change the editor hook.
1725 1751
1726 1752 You can also set the value of this editor via the command line option
1727 1753 '-editor' or in your ipythonrc file. This is useful if you wish to use
1728 1754 specifically for IPython an editor different from your typical default
1729 1755 (and for Windows users who typically don't set environment variables).
1730 1756
1731 1757 This command allows you to conveniently edit multi-line code right in
1732 1758 your IPython session.
1733 1759
1734 1760 If called without arguments, %edit opens up an empty editor with a
1735 1761 temporary file and will execute the contents of this file when you
1736 1762 close it (don't forget to save it!).
1737 1763
1738 1764
1739 1765 Options:
1740 1766
1741 1767 -p: this will call the editor with the same data as the previous time
1742 1768 it was used, regardless of how long ago (in your current session) it
1743 1769 was.
1744 1770
1771 -r: use 'raw' input. This option only applies to input taken from the
1772 user's history. By default, the 'processed' history is used, so that
1773 magics are loaded in their transformed version to valid Python. If
1774 this option is given, the raw input as typed as the command line is
1775 used instead. When you exit the editor, it will be executed by
1776 IPython's own processor.
1777
1745 1778 -x: do not execute the edited code immediately upon exit. This is
1746 1779 mainly useful if you are editing programs which need to be called with
1747 1780 command line arguments, which you can then do using %run.
1748 1781
1749 1782
1750 1783 Arguments:
1751 1784
1752 1785 If arguments are given, the following possibilites exist:
1753 1786
1754 1787 - The arguments are numbers or pairs of colon-separated numbers (like
1755 1788 1 4:8 9). These are interpreted as lines of previous input to be
1756 1789 loaded into the editor. The syntax is the same of the %macro command.
1757 1790
1758 1791 - If the argument doesn't start with a number, it is evaluated as a
1759 1792 variable and its contents loaded into the editor. You can thus edit
1760 1793 any string which contains python code (including the result of
1761 1794 previous edits).
1762 1795
1763 1796 - If the argument is the name of an object (other than a string),
1764 1797 IPython will try to locate the file where it was defined and open the
1765 1798 editor at the point where it is defined. You can use `%edit function`
1766 1799 to load an editor exactly at the point where 'function' is defined,
1767 1800 edit it and have the file be executed automatically.
1768 1801
1769 1802 If the object is a macro (see %macro for details), this opens up your
1770 1803 specified editor with a temporary file containing the macro's data.
1771 1804 Upon exit, the macro is reloaded with the contents of the file.
1772 1805
1773 1806 Note: opening at an exact line is only supported under Unix, and some
1774 1807 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1775 1808 '+NUMBER' parameter necessary for this feature. Good editors like
1776 1809 (X)Emacs, vi, jed, pico and joe all do.
1777 1810
1778 1811 - If the argument is not found as a variable, IPython will look for a
1779 1812 file with that name (adding .py if necessary) and load it into the
1780 1813 editor. It will execute its contents with execfile() when you exit,
1781 1814 loading any code in the file into your interactive namespace.
1782 1815
1783 1816 After executing your code, %edit will return as output the code you
1784 1817 typed in the editor (except when it was an existing file). This way
1785 1818 you can reload the code in further invocations of %edit as a variable,
1786 1819 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1787 1820 the output.
1788 1821
1789 1822 Note that %edit is also available through the alias %ed.
1790 1823
1791 1824 This is an example of creating a simple function inside the editor and
1792 1825 then modifying it. First, start up the editor:
1793 1826
1794 1827 In [1]: ed\\
1795 1828 Editing... done. Executing edited code...\\
1796 1829 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1797 1830
1798 1831 We can then call the function foo():
1799 1832
1800 1833 In [2]: foo()\\
1801 1834 foo() was defined in an editing session
1802 1835
1803 1836 Now we edit foo. IPython automatically loads the editor with the
1804 1837 (temporary) file where foo() was previously defined:
1805 1838
1806 1839 In [3]: ed foo\\
1807 1840 Editing... done. Executing edited code...
1808 1841
1809 1842 And if we call foo() again we get the modified version:
1810 1843
1811 1844 In [4]: foo()\\
1812 1845 foo() has now been changed!
1813 1846
1814 1847 Here is an example of how to edit a code snippet successive
1815 1848 times. First we call the editor:
1816 1849
1817 1850 In [8]: ed\\
1818 1851 Editing... done. Executing edited code...\\
1819 1852 hello\\
1820 1853 Out[8]: "print 'hello'\\n"
1821 1854
1822 1855 Now we call it again with the previous output (stored in _):
1823 1856
1824 1857 In [9]: ed _\\
1825 1858 Editing... done. Executing edited code...\\
1826 1859 hello world\\
1827 1860 Out[9]: "print 'hello world'\\n"
1828 1861
1829 1862 Now we call it with the output #8 (stored in _8, also as Out[8]):
1830 1863
1831 1864 In [10]: ed _8\\
1832 1865 Editing... done. Executing edited code...\\
1833 1866 hello again\\
1834 1867 Out[10]: "print 'hello again'\\n"
1835 1868
1836 1869
1837 1870 Changing the default editor hook:
1838 1871
1839 1872 If you wish to write your own editor hook, you can put it in a
1840 1873 configuration file which you load at startup time. The default hook
1841 1874 is defined in the IPython.hooks module, and you can use that as a
1842 1875 starting example for further modifications. That file also has
1843 1876 general instructions on how to set a new hook for use once you've
1844 1877 defined it."""
1845 1878
1846 1879 # FIXME: This function has become a convoluted mess. It needs a
1847 1880 # ground-up rewrite with clean, simple logic.
1848 1881
1849 1882 def make_filename(arg):
1850 1883 "Make a filename from the given args"
1851 1884 try:
1852 1885 filename = get_py_filename(arg)
1853 1886 except IOError:
1854 1887 if args.endswith('.py'):
1855 1888 filename = arg
1856 1889 else:
1857 1890 filename = None
1858 1891 return filename
1859 1892
1860 1893 # custom exceptions
1861 1894 class DataIsObject(Exception): pass
1862 1895
1863 opts,args = self.parse_options(parameter_s,'px')
1896 opts,args = self.parse_options(parameter_s,'prx')
1897 # Set a few locals from the options for convenience:
1898 opts_p = opts.has_key('p')
1899 opts_r = opts.has_key('r')
1864 1900
1865 1901 # Default line number value
1866 1902 lineno = None
1867 if opts.has_key('p'):
1903 if opts_p:
1868 1904 args = '_%s' % last_call[0]
1869 1905 if not self.shell.user_ns.has_key(args):
1870 1906 args = last_call[1]
1871 1907
1872 1908 # use last_call to remember the state of the previous call, but don't
1873 1909 # let it be clobbered by successive '-p' calls.
1874 1910 try:
1875 1911 last_call[0] = self.shell.outputcache.prompt_count
1876 if not opts.has_key('p'):
1912 if not opts_p:
1877 1913 last_call[1] = parameter_s
1878 1914 except:
1879 1915 pass
1880 1916
1881 1917 # by default this is done with temp files, except when the given
1882 1918 # arg is a filename
1883 1919 use_temp = 1
1884 1920
1885 1921 if re.match(r'\d',args):
1886 1922 # Mode where user specifies ranges of lines, like in %macro.
1887 1923 # This means that you can't edit files whose names begin with
1888 1924 # numbers this way. Tough.
1889 1925 ranges = args.split()
1890 data = ''.join(self.extract_input_slices(ranges))
1926 data = ''.join(self.extract_input_slices(ranges,opts_r))
1891 1927 elif args.endswith('.py'):
1892 1928 filename = make_filename(args)
1893 1929 data = ''
1894 1930 use_temp = 0
1895 1931 elif args:
1896 1932 try:
1897 1933 # Load the parameter given as a variable. If not a string,
1898 1934 # process it as an object instead (below)
1899 1935
1900 1936 #print '*** args',args,'type',type(args) # dbg
1901 1937 data = eval(args,self.shell.user_ns)
1902 1938 if not type(data) in StringTypes:
1903 1939 raise DataIsObject
1904 1940
1905 1941 except (NameError,SyntaxError):
1906 1942 # given argument is not a variable, try as a filename
1907 1943 filename = make_filename(args)
1908 1944 if filename is None:
1909 1945 warn("Argument given (%s) can't be found as a variable "
1910 1946 "or as a filename." % args)
1911 1947 return
1912 1948
1913 1949 data = ''
1914 1950 use_temp = 0
1915 1951 except DataIsObject:
1916 1952
1917 1953 # macros have a special edit function
1918 1954 if isinstance(data,Macro):
1919 1955 self._edit_macro(args,data)
1920 1956 return
1921 1957
1922 1958 # For objects, try to edit the file where they are defined
1923 1959 try:
1924 1960 filename = inspect.getabsfile(data)
1925 1961 datafile = 1
1926 1962 except TypeError:
1927 1963 filename = make_filename(args)
1928 1964 datafile = 1
1929 1965 warn('Could not find file where `%s` is defined.\n'
1930 1966 'Opening a file named `%s`' % (args,filename))
1931 1967 # Now, make sure we can actually read the source (if it was in
1932 1968 # a temp file it's gone by now).
1933 1969 if datafile:
1934 1970 try:
1935 1971 lineno = inspect.getsourcelines(data)[1]
1936 1972 except IOError:
1937 1973 filename = make_filename(args)
1938 1974 if filename is None:
1939 1975 warn('The file `%s` where `%s` was defined cannot '
1940 1976 'be read.' % (filename,data))
1941 1977 return
1942 1978 use_temp = 0
1943 1979 else:
1944 1980 data = ''
1945 1981
1946 1982 if use_temp:
1947 1983 filename = self.shell.mktempfile(data)
1948 1984 print 'IPython will make a temporary file named:',filename
1949 1985
1950 1986 # do actual editing here
1951 1987 print 'Editing...',
1952 1988 sys.stdout.flush()
1953 1989 self.shell.hooks.editor(filename,lineno)
1954 1990 if opts.has_key('x'): # -x prevents actual execution
1955 1991 print
1956 1992 else:
1957 1993 print 'done. Executing edited code...'
1958 self.shell.safe_execfile(filename,self.shell.user_ns)
1994 if opts_r:
1995 self.shell.runlines(file_read(filename))
1996 else:
1997 self.shell.safe_execfile(filename,self.shell.user_ns)
1959 1998 if use_temp:
1960 1999 try:
1961 2000 return open(filename).read()
1962 2001 except IOError,msg:
1963 2002 if msg.filename == filename:
1964 2003 warn('File not found. Did you forget to save?')
1965 2004 return
1966 2005 else:
1967 2006 self.shell.showtraceback()
1968 2007
1969 2008 def magic_xmode(self,parameter_s = ''):
1970 2009 """Switch modes for the exception handlers.
1971 2010
1972 2011 Valid modes: Plain, Context and Verbose.
1973 2012
1974 2013 If called without arguments, acts as a toggle."""
1975 2014
1976 2015 def xmode_switch_err(name):
1977 2016 warn('Error changing %s exception modes.\n%s' %
1978 2017 (name,sys.exc_info()[1]))
1979 2018
1980 2019 shell = self.shell
1981 2020 new_mode = parameter_s.strip().capitalize()
1982 2021 try:
1983 2022 shell.InteractiveTB.set_mode(mode=new_mode)
1984 2023 print 'Exception reporting mode:',shell.InteractiveTB.mode
1985 2024 except:
1986 2025 xmode_switch_err('user')
1987 2026
1988 2027 # threaded shells use a special handler in sys.excepthook
1989 2028 if shell.isthreaded:
1990 2029 try:
1991 2030 shell.sys_excepthook.set_mode(mode=new_mode)
1992 2031 except:
1993 2032 xmode_switch_err('threaded')
1994 2033
1995 2034 def magic_colors(self,parameter_s = ''):
1996 2035 """Switch color scheme for prompts, info system and exception handlers.
1997 2036
1998 2037 Currently implemented schemes: NoColor, Linux, LightBG.
1999 2038
2000 2039 Color scheme names are not case-sensitive."""
2001 2040
2002 2041 def color_switch_err(name):
2003 2042 warn('Error changing %s color schemes.\n%s' %
2004 2043 (name,sys.exc_info()[1]))
2005 2044
2006 2045
2007 2046 new_scheme = parameter_s.strip()
2008 2047 if not new_scheme:
2009 2048 print 'You must specify a color scheme.'
2010 2049 return
2011 2050 import IPython.rlineimpl as readline
2012 2051 if not readline.have_readline:
2013 2052 msg = """\
2014 2053 Proper color support under MS Windows requires Gary Bishop's readline library.
2015 2054 You can find it at:
2016 2055 http://sourceforge.net/projects/uncpythontools
2017 2056 Gary's readline needs the ctypes module, from:
2018 2057 http://starship.python.net/crew/theller/ctypes
2019 2058
2020 2059 Defaulting color scheme to 'NoColor'"""
2021 2060 new_scheme = 'NoColor'
2022 2061 warn(msg)
2023 2062 # local shortcut
2024 2063 shell = self.shell
2025 2064
2026 2065 # Set prompt colors
2027 2066 try:
2028 2067 shell.outputcache.set_colors(new_scheme)
2029 2068 except:
2030 2069 color_switch_err('prompt')
2031 2070 else:
2032 2071 shell.rc.colors = \
2033 2072 shell.outputcache.color_table.active_scheme_name
2034 2073 # Set exception colors
2035 2074 try:
2036 2075 shell.InteractiveTB.set_colors(scheme = new_scheme)
2037 2076 shell.SyntaxTB.set_colors(scheme = new_scheme)
2038 2077 except:
2039 2078 color_switch_err('exception')
2040 2079
2041 2080 # threaded shells use a verbose traceback in sys.excepthook
2042 2081 if shell.isthreaded:
2043 2082 try:
2044 2083 shell.sys_excepthook.set_colors(scheme=new_scheme)
2045 2084 except:
2046 2085 color_switch_err('system exception handler')
2047 2086
2048 2087 # Set info (for 'object?') colors
2049 2088 if shell.rc.color_info:
2050 2089 try:
2051 2090 shell.inspector.set_active_scheme(new_scheme)
2052 2091 except:
2053 2092 color_switch_err('object inspector')
2054 2093 else:
2055 2094 shell.inspector.set_active_scheme('NoColor')
2056 2095
2057 2096 def magic_color_info(self,parameter_s = ''):
2058 2097 """Toggle color_info.
2059 2098
2060 2099 The color_info configuration parameter controls whether colors are
2061 2100 used for displaying object details (by things like %psource, %pfile or
2062 2101 the '?' system). This function toggles this value with each call.
2063 2102
2064 2103 Note that unless you have a fairly recent pager (less works better
2065 2104 than more) in your system, using colored object information displays
2066 2105 will not work properly. Test it and see."""
2067 2106
2068 2107 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2069 2108 self.magic_colors(self.shell.rc.colors)
2070 2109 print 'Object introspection functions have now coloring:',
2071 2110 print ['OFF','ON'][self.shell.rc.color_info]
2072 2111
2073 2112 def magic_Pprint(self, parameter_s=''):
2074 2113 """Toggle pretty printing on/off."""
2075 2114
2076 2115 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2077 2116 print 'Pretty printing has been turned', \
2078 2117 ['OFF','ON'][self.shell.outputcache.Pprint]
2079 2118
2080 2119 def magic_exit(self, parameter_s=''):
2081 2120 """Exit IPython, confirming if configured to do so.
2082 2121
2083 2122 You can configure whether IPython asks for confirmation upon exit by
2084 2123 setting the confirm_exit flag in the ipythonrc file."""
2085 2124
2086 2125 self.shell.exit()
2087 2126
2088 2127 def magic_quit(self, parameter_s=''):
2089 2128 """Exit IPython, confirming if configured to do so (like %exit)"""
2090 2129
2091 2130 self.shell.exit()
2092 2131
2093 2132 def magic_Exit(self, parameter_s=''):
2094 2133 """Exit IPython without confirmation."""
2095 2134
2096 2135 self.shell.exit_now = True
2097 2136
2098 2137 def magic_Quit(self, parameter_s=''):
2099 2138 """Exit IPython without confirmation (like %Exit)."""
2100 2139
2101 2140 self.shell.exit_now = True
2102 2141
2103 2142 #......................................................................
2104 2143 # Functions to implement unix shell-type things
2105 2144
2106 2145 def magic_alias(self, parameter_s = ''):
2107 2146 """Define an alias for a system command.
2108 2147
2109 2148 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2110 2149
2111 2150 Then, typing 'alias_name params' will execute the system command 'cmd
2112 2151 params' (from your underlying operating system).
2113 2152
2114 2153 Aliases have lower precedence than magic functions and Python normal
2115 2154 variables, so if 'foo' is both a Python variable and an alias, the
2116 2155 alias can not be executed until 'del foo' removes the Python variable.
2117 2156
2118 2157 You can use the %l specifier in an alias definition to represent the
2119 2158 whole line when the alias is called. For example:
2120 2159
2121 2160 In [2]: alias all echo "Input in brackets: <%l>"\\
2122 2161 In [3]: all hello world\\
2123 2162 Input in brackets: <hello world>
2124 2163
2125 2164 You can also define aliases with parameters using %s specifiers (one
2126 2165 per parameter):
2127 2166
2128 2167 In [1]: alias parts echo first %s second %s\\
2129 2168 In [2]: %parts A B\\
2130 2169 first A second B\\
2131 2170 In [3]: %parts A\\
2132 2171 Incorrect number of arguments: 2 expected.\\
2133 2172 parts is an alias to: 'echo first %s second %s'
2134 2173
2135 2174 Note that %l and %s are mutually exclusive. You can only use one or
2136 2175 the other in your aliases.
2137 2176
2138 2177 Aliases expand Python variables just like system calls using ! or !!
2139 2178 do: all expressions prefixed with '$' get expanded. For details of
2140 2179 the semantic rules, see PEP-215:
2141 2180 http://www.python.org/peps/pep-0215.html. This is the library used by
2142 2181 IPython for variable expansion. If you want to access a true shell
2143 2182 variable, an extra $ is necessary to prevent its expansion by IPython:
2144 2183
2145 2184 In [6]: alias show echo\\
2146 2185 In [7]: PATH='A Python string'\\
2147 2186 In [8]: show $PATH\\
2148 2187 A Python string\\
2149 2188 In [9]: show $$PATH\\
2150 2189 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2151 2190
2152 2191 You can use the alias facility to acess all of $PATH. See the %rehash
2153 2192 and %rehashx functions, which automatically create aliases for the
2154 2193 contents of your $PATH.
2155 2194
2156 2195 If called with no parameters, %alias prints the current alias table."""
2157 2196
2158 2197 par = parameter_s.strip()
2159 2198 if not par:
2160 2199 if self.shell.rc.automagic:
2161 2200 prechar = ''
2162 2201 else:
2163 2202 prechar = self.shell.ESC_MAGIC
2164 2203 #print 'Alias\t\tSystem Command\n'+'-'*30
2165 2204 atab = self.shell.alias_table
2166 2205 aliases = atab.keys()
2167 2206 aliases.sort()
2168 2207 res = []
2169 2208 for alias in aliases:
2170 2209 res.append((alias, atab[alias][1]))
2171 2210 print "Total number of aliases:",len(aliases)
2172 2211 return res
2173 2212 try:
2174 2213 alias,cmd = par.split(None,1)
2175 2214 except:
2176 2215 print OInspect.getdoc(self.magic_alias)
2177 2216 else:
2178 2217 nargs = cmd.count('%s')
2179 2218 if nargs>0 and cmd.find('%l')>=0:
2180 2219 error('The %s and %l specifiers are mutually exclusive '
2181 2220 'in alias definitions.')
2182 2221 else: # all looks OK
2183 2222 self.shell.alias_table[alias] = (nargs,cmd)
2184 2223 self.shell.alias_table_validate(verbose=1)
2185 2224 # end magic_alias
2186 2225
2187 2226 def magic_unalias(self, parameter_s = ''):
2188 2227 """Remove an alias"""
2189 2228
2190 2229 aname = parameter_s.strip()
2191 2230 if aname in self.shell.alias_table:
2192 2231 del self.shell.alias_table[aname]
2193 2232
2194 2233 def magic_rehash(self, parameter_s = ''):
2195 2234 """Update the alias table with all entries in $PATH.
2196 2235
2197 2236 This version does no checks on execute permissions or whether the
2198 2237 contents of $PATH are truly files (instead of directories or something
2199 2238 else). For such a safer (but slower) version, use %rehashx."""
2200 2239
2201 2240 # This function (and rehashx) manipulate the alias_table directly
2202 2241 # rather than calling magic_alias, for speed reasons. A rehash on a
2203 2242 # typical Linux box involves several thousand entries, so efficiency
2204 2243 # here is a top concern.
2205 2244
2206 2245 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2207 2246 alias_table = self.shell.alias_table
2208 2247 for pdir in path:
2209 2248 for ff in os.listdir(pdir):
2210 2249 # each entry in the alias table must be (N,name), where
2211 2250 # N is the number of positional arguments of the alias.
2212 2251 alias_table[ff] = (0,ff)
2213 2252 # Make sure the alias table doesn't contain keywords or builtins
2214 2253 self.shell.alias_table_validate()
2215 2254 # Call again init_auto_alias() so we get 'rm -i' and other modified
2216 2255 # aliases since %rehash will probably clobber them
2217 2256 self.shell.init_auto_alias()
2218 2257
2219 2258 def magic_rehashx(self, parameter_s = ''):
2220 2259 """Update the alias table with all executable files in $PATH.
2221 2260
2222 2261 This version explicitly checks that every entry in $PATH is a file
2223 2262 with execute access (os.X_OK), so it is much slower than %rehash.
2224 2263
2225 2264 Under Windows, it checks executability as a match agains a
2226 2265 '|'-separated string of extensions, stored in the IPython config
2227 2266 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2228 2267
2229 2268 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2230 2269 alias_table = self.shell.alias_table
2231 2270
2232 2271 if os.name == 'posix':
2233 2272 isexec = lambda fname:os.path.isfile(fname) and \
2234 2273 os.access(fname,os.X_OK)
2235 2274 else:
2236 2275
2237 2276 try:
2238 2277 winext = os.environ['pathext'].replace(';','|').replace('.','')
2239 2278 except KeyError:
2240 2279 winext = 'exe|com|bat'
2241 2280
2242 2281 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2243 2282 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2244 2283 savedir = os.getcwd()
2245 2284 try:
2246 2285 # write the whole loop for posix/Windows so we don't have an if in
2247 2286 # the innermost part
2248 2287 if os.name == 'posix':
2249 2288 for pdir in path:
2250 2289 os.chdir(pdir)
2251 2290 for ff in os.listdir(pdir):
2252 2291 if isexec(ff):
2253 2292 # each entry in the alias table must be (N,name),
2254 2293 # where N is the number of positional arguments of the
2255 2294 # alias.
2256 2295 alias_table[ff] = (0,ff)
2257 2296 else:
2258 2297 for pdir in path:
2259 2298 os.chdir(pdir)
2260 2299 for ff in os.listdir(pdir):
2261 2300 if isexec(ff):
2262 2301 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2263 2302 # Make sure the alias table doesn't contain keywords or builtins
2264 2303 self.shell.alias_table_validate()
2265 2304 # Call again init_auto_alias() so we get 'rm -i' and other
2266 2305 # modified aliases since %rehashx will probably clobber them
2267 2306 self.shell.init_auto_alias()
2268 2307 finally:
2269 2308 os.chdir(savedir)
2270 2309
2271 2310 def magic_pwd(self, parameter_s = ''):
2272 2311 """Return the current working directory path."""
2273 2312 return os.getcwd()
2274 2313
2275 2314 def magic_cd(self, parameter_s=''):
2276 2315 """Change the current working directory.
2277 2316
2278 2317 This command automatically maintains an internal list of directories
2279 2318 you visit during your IPython session, in the variable _dh. The
2280 2319 command %dhist shows this history nicely formatted.
2281 2320
2282 2321 Usage:
2283 2322
2284 2323 cd 'dir': changes to directory 'dir'.
2285 2324
2286 2325 cd -: changes to the last visited directory.
2287 2326
2288 2327 cd -<n>: changes to the n-th directory in the directory history.
2289 2328
2290 2329 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2291 2330 (note: cd <bookmark_name> is enough if there is no
2292 2331 directory <bookmark_name>, but a bookmark with the name exists.)
2293 2332
2294 2333 Options:
2295 2334
2296 2335 -q: quiet. Do not print the working directory after the cd command is
2297 2336 executed. By default IPython's cd command does print this directory,
2298 2337 since the default prompts do not display path information.
2299 2338
2300 2339 Note that !cd doesn't work for this purpose because the shell where
2301 2340 !command runs is immediately discarded after executing 'command'."""
2302 2341
2303 2342 parameter_s = parameter_s.strip()
2304 2343 #bkms = self.shell.persist.get("bookmarks",{})
2305 2344
2306 2345 numcd = re.match(r'(-)(\d+)$',parameter_s)
2307 2346 # jump in directory history by number
2308 2347 if numcd:
2309 2348 nn = int(numcd.group(2))
2310 2349 try:
2311 2350 ps = self.shell.user_ns['_dh'][nn]
2312 2351 except IndexError:
2313 2352 print 'The requested directory does not exist in history.'
2314 2353 return
2315 2354 else:
2316 2355 opts = {}
2317 2356 else:
2318 2357 #turn all non-space-escaping backslashes to slashes,
2319 2358 # for c:\windows\directory\names\
2320 2359 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2321 2360 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2322 2361 # jump to previous
2323 2362 if ps == '-':
2324 2363 try:
2325 2364 ps = self.shell.user_ns['_dh'][-2]
2326 2365 except IndexError:
2327 2366 print 'No previous directory to change to.'
2328 2367 return
2329 2368 # jump to bookmark if needed
2330 2369 else:
2331 2370 if not os.path.isdir(ps) or opts.has_key('b'):
2332 2371 bkms = self.db.get('bookmarks', {})
2333 2372
2334 2373 if bkms.has_key(ps):
2335 2374 target = bkms[ps]
2336 2375 print '(bookmark:%s) -> %s' % (ps,target)
2337 2376 ps = target
2338 2377 else:
2339 2378 if opts.has_key('b'):
2340 2379 error("Bookmark '%s' not found. "
2341 2380 "Use '%%bookmark -l' to see your bookmarks." % ps)
2342 2381 return
2343 2382
2344 2383 # at this point ps should point to the target dir
2345 2384 if ps:
2346 2385 try:
2347 2386 os.chdir(os.path.expanduser(ps))
2348 2387 ttitle = ("IPy:" + (
2349 2388 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2350 2389 platutils.set_term_title(ttitle)
2351 2390 except OSError:
2352 2391 print sys.exc_info()[1]
2353 2392 else:
2354 2393 self.shell.user_ns['_dh'].append(os.getcwd())
2355 2394 else:
2356 2395 os.chdir(self.shell.home_dir)
2357 2396 platutils.set_term_title("IPy:~")
2358 2397 self.shell.user_ns['_dh'].append(os.getcwd())
2359 2398 if not 'q' in opts:
2360 2399 print self.shell.user_ns['_dh'][-1]
2361 2400
2362 2401 def magic_dhist(self, parameter_s=''):
2363 2402 """Print your history of visited directories.
2364 2403
2365 2404 %dhist -> print full history\\
2366 2405 %dhist n -> print last n entries only\\
2367 2406 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2368 2407
2369 2408 This history is automatically maintained by the %cd command, and
2370 2409 always available as the global list variable _dh. You can use %cd -<n>
2371 2410 to go to directory number <n>."""
2372 2411
2373 2412 dh = self.shell.user_ns['_dh']
2374 2413 if parameter_s:
2375 2414 try:
2376 2415 args = map(int,parameter_s.split())
2377 2416 except:
2378 2417 self.arg_err(Magic.magic_dhist)
2379 2418 return
2380 2419 if len(args) == 1:
2381 2420 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2382 2421 elif len(args) == 2:
2383 2422 ini,fin = args
2384 2423 else:
2385 2424 self.arg_err(Magic.magic_dhist)
2386 2425 return
2387 2426 else:
2388 2427 ini,fin = 0,len(dh)
2389 2428 nlprint(dh,
2390 2429 header = 'Directory history (kept in _dh)',
2391 2430 start=ini,stop=fin)
2392 2431
2393 2432 def magic_env(self, parameter_s=''):
2394 2433 """List environment variables."""
2395 2434
2396 2435 return os.environ.data
2397 2436
2398 2437 def magic_pushd(self, parameter_s=''):
2399 2438 """Place the current dir on stack and change directory.
2400 2439
2401 2440 Usage:\\
2402 2441 %pushd ['dirname']
2403 2442
2404 2443 %pushd with no arguments does a %pushd to your home directory.
2405 2444 """
2406 2445 if parameter_s == '': parameter_s = '~'
2407 2446 dir_s = self.shell.dir_stack
2408 2447 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2409 2448 os.path.expanduser(self.shell.dir_stack[0]):
2410 2449 try:
2411 2450 self.magic_cd(parameter_s)
2412 2451 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2413 2452 self.magic_dirs()
2414 2453 except:
2415 2454 print 'Invalid directory'
2416 2455 else:
2417 2456 print 'You are already there!'
2418 2457
2419 2458 def magic_popd(self, parameter_s=''):
2420 2459 """Change to directory popped off the top of the stack.
2421 2460 """
2422 2461 if len (self.shell.dir_stack) > 1:
2423 2462 self.shell.dir_stack.pop(0)
2424 2463 self.magic_cd(self.shell.dir_stack[0])
2425 2464 print self.shell.dir_stack[0]
2426 2465 else:
2427 2466 print "You can't remove the starting directory from the stack:",\
2428 2467 self.shell.dir_stack
2429 2468
2430 2469 def magic_dirs(self, parameter_s=''):
2431 2470 """Return the current directory stack."""
2432 2471
2433 2472 return self.shell.dir_stack[:]
2434 2473
2435 2474 def magic_sc(self, parameter_s=''):
2436 2475 """Shell capture - execute a shell command and capture its output.
2437 2476
2438 2477 DEPRECATED. Suboptimal, retained for backwards compatibility.
2439 2478
2440 2479 You should use the form 'var = !command' instead. Example:
2441 2480
2442 2481 "%sc -l myfiles = ls ~" should now be written as
2443 2482
2444 2483 "myfiles = !ls ~"
2445 2484
2446 2485 myfiles.s, myfiles.l and myfiles.n still apply as documented
2447 2486 below.
2448 2487
2449 2488 --
2450 2489 %sc [options] varname=command
2451 2490
2452 2491 IPython will run the given command using commands.getoutput(), and
2453 2492 will then update the user's interactive namespace with a variable
2454 2493 called varname, containing the value of the call. Your command can
2455 2494 contain shell wildcards, pipes, etc.
2456 2495
2457 2496 The '=' sign in the syntax is mandatory, and the variable name you
2458 2497 supply must follow Python's standard conventions for valid names.
2459 2498
2460 2499 (A special format without variable name exists for internal use)
2461 2500
2462 2501 Options:
2463 2502
2464 2503 -l: list output. Split the output on newlines into a list before
2465 2504 assigning it to the given variable. By default the output is stored
2466 2505 as a single string.
2467 2506
2468 2507 -v: verbose. Print the contents of the variable.
2469 2508
2470 2509 In most cases you should not need to split as a list, because the
2471 2510 returned value is a special type of string which can automatically
2472 2511 provide its contents either as a list (split on newlines) or as a
2473 2512 space-separated string. These are convenient, respectively, either
2474 2513 for sequential processing or to be passed to a shell command.
2475 2514
2476 2515 For example:
2477 2516
2478 2517 # Capture into variable a
2479 2518 In [9]: sc a=ls *py
2480 2519
2481 2520 # a is a string with embedded newlines
2482 2521 In [10]: a
2483 2522 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2484 2523
2485 2524 # which can be seen as a list:
2486 2525 In [11]: a.l
2487 2526 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2488 2527
2489 2528 # or as a whitespace-separated string:
2490 2529 In [12]: a.s
2491 2530 Out[12]: 'setup.py win32_manual_post_install.py'
2492 2531
2493 2532 # a.s is useful to pass as a single command line:
2494 2533 In [13]: !wc -l $a.s
2495 2534 146 setup.py
2496 2535 130 win32_manual_post_install.py
2497 2536 276 total
2498 2537
2499 2538 # while the list form is useful to loop over:
2500 2539 In [14]: for f in a.l:
2501 2540 ....: !wc -l $f
2502 2541 ....:
2503 2542 146 setup.py
2504 2543 130 win32_manual_post_install.py
2505 2544
2506 2545 Similiarly, the lists returned by the -l option are also special, in
2507 2546 the sense that you can equally invoke the .s attribute on them to
2508 2547 automatically get a whitespace-separated string from their contents:
2509 2548
2510 2549 In [1]: sc -l b=ls *py
2511 2550
2512 2551 In [2]: b
2513 2552 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2514 2553
2515 2554 In [3]: b.s
2516 2555 Out[3]: 'setup.py win32_manual_post_install.py'
2517 2556
2518 2557 In summary, both the lists and strings used for ouptut capture have
2519 2558 the following special attributes:
2520 2559
2521 2560 .l (or .list) : value as list.
2522 2561 .n (or .nlstr): value as newline-separated string.
2523 2562 .s (or .spstr): value as space-separated string.
2524 2563 """
2525 2564
2526 2565 opts,args = self.parse_options(parameter_s,'lv')
2527 2566 # Try to get a variable name and command to run
2528 2567 try:
2529 2568 # the variable name must be obtained from the parse_options
2530 2569 # output, which uses shlex.split to strip options out.
2531 2570 var,_ = args.split('=',1)
2532 2571 var = var.strip()
2533 2572 # But the the command has to be extracted from the original input
2534 2573 # parameter_s, not on what parse_options returns, to avoid the
2535 2574 # quote stripping which shlex.split performs on it.
2536 2575 _,cmd = parameter_s.split('=',1)
2537 2576 except ValueError:
2538 2577 var,cmd = '',''
2539 2578 # If all looks ok, proceed
2540 2579 out,err = self.shell.getoutputerror(cmd)
2541 2580 if err:
2542 2581 print >> Term.cerr,err
2543 2582 if opts.has_key('l'):
2544 2583 out = SList(out.split('\n'))
2545 2584 else:
2546 2585 out = LSString(out)
2547 2586 if opts.has_key('v'):
2548 2587 print '%s ==\n%s' % (var,pformat(out))
2549 2588 if var:
2550 2589 self.shell.user_ns.update({var:out})
2551 2590 else:
2552 2591 return out
2553 2592
2554 2593 def magic_sx(self, parameter_s=''):
2555 2594 """Shell execute - run a shell command and capture its output.
2556 2595
2557 2596 %sx command
2558 2597
2559 2598 IPython will run the given command using commands.getoutput(), and
2560 2599 return the result formatted as a list (split on '\\n'). Since the
2561 2600 output is _returned_, it will be stored in ipython's regular output
2562 2601 cache Out[N] and in the '_N' automatic variables.
2563 2602
2564 2603 Notes:
2565 2604
2566 2605 1) If an input line begins with '!!', then %sx is automatically
2567 2606 invoked. That is, while:
2568 2607 !ls
2569 2608 causes ipython to simply issue system('ls'), typing
2570 2609 !!ls
2571 2610 is a shorthand equivalent to:
2572 2611 %sx ls
2573 2612
2574 2613 2) %sx differs from %sc in that %sx automatically splits into a list,
2575 2614 like '%sc -l'. The reason for this is to make it as easy as possible
2576 2615 to process line-oriented shell output via further python commands.
2577 2616 %sc is meant to provide much finer control, but requires more
2578 2617 typing.
2579 2618
2580 2619 3) Just like %sc -l, this is a list with special attributes:
2581 2620
2582 2621 .l (or .list) : value as list.
2583 2622 .n (or .nlstr): value as newline-separated string.
2584 2623 .s (or .spstr): value as whitespace-separated string.
2585 2624
2586 2625 This is very useful when trying to use such lists as arguments to
2587 2626 system commands."""
2588 2627
2589 2628 if parameter_s:
2590 2629 out,err = self.shell.getoutputerror(parameter_s)
2591 2630 if err:
2592 2631 print >> Term.cerr,err
2593 2632 return SList(out.split('\n'))
2594 2633
2595 2634 def magic_bg(self, parameter_s=''):
2596 2635 """Run a job in the background, in a separate thread.
2597 2636
2598 2637 For example,
2599 2638
2600 2639 %bg myfunc(x,y,z=1)
2601 2640
2602 2641 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2603 2642 execution starts, a message will be printed indicating the job
2604 2643 number. If your job number is 5, you can use
2605 2644
2606 2645 myvar = jobs.result(5) or myvar = jobs[5].result
2607 2646
2608 2647 to assign this result to variable 'myvar'.
2609 2648
2610 2649 IPython has a job manager, accessible via the 'jobs' object. You can
2611 2650 type jobs? to get more information about it, and use jobs.<TAB> to see
2612 2651 its attributes. All attributes not starting with an underscore are
2613 2652 meant for public use.
2614 2653
2615 2654 In particular, look at the jobs.new() method, which is used to create
2616 2655 new jobs. This magic %bg function is just a convenience wrapper
2617 2656 around jobs.new(), for expression-based jobs. If you want to create a
2618 2657 new job with an explicit function object and arguments, you must call
2619 2658 jobs.new() directly.
2620 2659
2621 2660 The jobs.new docstring also describes in detail several important
2622 2661 caveats associated with a thread-based model for background job
2623 2662 execution. Type jobs.new? for details.
2624 2663
2625 2664 You can check the status of all jobs with jobs.status().
2626 2665
2627 2666 The jobs variable is set by IPython into the Python builtin namespace.
2628 2667 If you ever declare a variable named 'jobs', you will shadow this
2629 2668 name. You can either delete your global jobs variable to regain
2630 2669 access to the job manager, or make a new name and assign it manually
2631 2670 to the manager (stored in IPython's namespace). For example, to
2632 2671 assign the job manager to the Jobs name, use:
2633 2672
2634 2673 Jobs = __builtins__.jobs"""
2635 2674
2636 2675 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2637 2676
2638 2677
2639 2678 def magic_bookmark(self, parameter_s=''):
2640 2679 """Manage IPython's bookmark system.
2641 2680
2642 2681 %bookmark <name> - set bookmark to current dir
2643 2682 %bookmark <name> <dir> - set bookmark to <dir>
2644 2683 %bookmark -l - list all bookmarks
2645 2684 %bookmark -d <name> - remove bookmark
2646 2685 %bookmark -r - remove all bookmarks
2647 2686
2648 2687 You can later on access a bookmarked folder with:
2649 2688 %cd -b <name>
2650 2689 or simply '%cd <name>' if there is no directory called <name> AND
2651 2690 there is such a bookmark defined.
2652 2691
2653 2692 Your bookmarks persist through IPython sessions, but they are
2654 2693 associated with each profile."""
2655 2694
2656 2695 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2657 2696 if len(args) > 2:
2658 2697 error('You can only give at most two arguments')
2659 2698 return
2660 2699
2661 2700 bkms = self.db.get('bookmarks',{})
2662 2701
2663 2702 if opts.has_key('d'):
2664 2703 try:
2665 2704 todel = args[0]
2666 2705 except IndexError:
2667 2706 error('You must provide a bookmark to delete')
2668 2707 else:
2669 2708 try:
2670 2709 del bkms[todel]
2671 2710 except:
2672 2711 error("Can't delete bookmark '%s'" % todel)
2673 2712 elif opts.has_key('r'):
2674 2713 bkms = {}
2675 2714 elif opts.has_key('l'):
2676 2715 bks = bkms.keys()
2677 2716 bks.sort()
2678 2717 if bks:
2679 2718 size = max(map(len,bks))
2680 2719 else:
2681 2720 size = 0
2682 2721 fmt = '%-'+str(size)+'s -> %s'
2683 2722 print 'Current bookmarks:'
2684 2723 for bk in bks:
2685 2724 print fmt % (bk,bkms[bk])
2686 2725 else:
2687 2726 if not args:
2688 2727 error("You must specify the bookmark name")
2689 2728 elif len(args)==1:
2690 2729 bkms[args[0]] = os.getcwd()
2691 2730 elif len(args)==2:
2692 2731 bkms[args[0]] = args[1]
2693 2732 self.db['bookmarks'] = bkms
2694 2733
2695 2734 def magic_pycat(self, parameter_s=''):
2696 2735 """Show a syntax-highlighted file through a pager.
2697 2736
2698 2737 This magic is similar to the cat utility, but it will assume the file
2699 2738 to be Python source and will show it with syntax highlighting. """
2700 2739
2701 2740 try:
2702 2741 filename = get_py_filename(parameter_s)
2703 2742 cont = file_read(filename)
2704 2743 except IOError:
2705 2744 try:
2706 2745 cont = eval(parameter_s,self.user_ns)
2707 2746 except NameError:
2708 2747 cont = None
2709 2748 if cont is None:
2710 2749 print "Error: no such file or variable"
2711 2750 return
2712 2751
2713 2752 page(self.shell.pycolorize(cont),
2714 2753 screen_lines=self.shell.rc.screen_length)
2715 2754
2716 2755 def magic_cpaste(self, parameter_s=''):
2717 2756 """Allows you to paste & execute a pre-formatted code block from
2718 2757 clipboard.
2719 2758
2720 2759 You must terminate the block with '--' (two minus-signs) alone on the
2721 2760 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2722 2761 is the new sentinel for this operation)
2723 2762
2724 2763 The block is dedented prior to execution to enable execution of
2725 2764 method definitions. The executed block is also assigned to variable
2726 2765 named 'pasted_block' for later editing with '%edit pasted_block'.
2727 2766
2728 2767 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2729 2768 This assigns the pasted block to variable 'foo' as string, without
2730 2769 dedenting or executing it.
2731 2770
2732 2771 Do not be alarmed by garbled output on Windows (it's a readline bug).
2733 2772 Just press enter and type -- (and press enter again) and the block
2734 2773 will be what was just pasted.
2735 2774
2736 2775 IPython statements (magics, shell escapes) are not supported (yet).
2737 2776 """
2738 2777 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2739 2778 par = args.strip()
2740 2779 sentinel = opts.get('s','--')
2741 2780
2742 2781 from IPython import iplib
2743 2782 lines = []
2744 2783 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2745 2784 while 1:
2746 2785 l = iplib.raw_input_original(':')
2747 2786 if l ==sentinel:
2748 2787 break
2749 2788 lines.append(l)
2750 2789 block = "\n".join(lines) + '\n'
2751 2790 #print "block:\n",block
2752 2791 if not par:
2753 2792 b = textwrap.dedent(block)
2754 2793 exec b in self.user_ns
2755 2794 self.user_ns['pasted_block'] = b
2756 2795 else:
2757 2796 self.user_ns[par] = block
2758 2797 print "Block assigned to '%s'" % par
2759 2798 def magic_quickref(self,arg):
2760 2799 import IPython.usage
2761 2800 page(IPython.usage.quick_reference)
2762 2801 del IPython.usage
2763 2802
2764 2803
2765 2804 # end Magic
@@ -1,311 +1,418 b''
1 1 """Module for interactive demos using IPython.
2 2
3 This module implements a single class, Demo, for running Python scripts
4 interactively in IPython for demonstrations. With very simple markup (a few
5 tags in comments), you can control points where the script stops executing and
6 returns control to IPython.
3 This module implements a few classes for running Python scripts interactively
4 in IPython for demonstrations. With very simple markup (a few tags in
5 comments), you can control points where the script stops executing and returns
6 control to IPython.
7
8 The classes are (see their docstrings for further details):
9
10 - Demo: pure python demos
11
12 - IPythonDemo: demos with input to be processed by IPython as if it had been
13 typed interactively (so magics work, as well as any other special syntax you
14 may have added via input prefilters).
15
16 - LineDemo: single-line version of the Demo class. These demos are executed
17 one line at a time, and require no markup.
18
19 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
20 executed a line at a time, but processed via IPython).
21
7 22
8 23 The file is run in its own empty namespace (though you can pass it a string of
9 24 arguments as if in a command line environment, and it will see those as
10 25 sys.argv). But at each stop, the global IPython namespace is updated with the
11 26 current internal demo namespace, so you can work interactively with the data
12 27 accumulated so far.
13 28
14 29 By default, each block of code is printed (with syntax highlighting) before
15 30 executing it and you have to confirm execution. This is intended to show the
16 31 code to an audience first so you can discuss it, and only proceed with
17 32 execution once you agree. There are a few tags which allow you to modify this
18 33 behavior.
19 34
20 35 The supported tags are:
21 36
22 37 # <demo> --- stop ---
23 38
24 39 Defines block boundaries, the points where IPython stops execution of the
25 40 file and returns to the interactive prompt.
26 41
27 42 # <demo> silent
28 43
29 44 Make a block execute silently (and hence automatically). Typically used in
30 45 cases where you have some boilerplate or initialization code which you need
31 46 executed but do not want to be seen in the demo.
32 47
33 48 # <demo> auto
34 49
35 50 Make a block execute automatically, but still being printed. Useful for
36 51 simple code which does not warrant discussion, since it avoids the extra
37 52 manual confirmation.
38 53
39 54 # <demo> auto_all
40 55
41 56 This tag can _only_ be in the first block, and if given it overrides the
42 57 individual auto tags to make the whole demo fully automatic (no block asks
43 58 for confirmation). It can also be given at creation time (or the attribute
44 59 set later) to override what's in the file.
45 60
46 61 While _any_ python file can be run as a Demo instance, if there are no stop
47 62 tags the whole file will run in a single block (no different that calling
48 63 first %pycat and then %run). The minimal markup to make this useful is to
49 64 place a set of stop tags; the other tags are only there to let you fine-tune
50 65 the execution.
51 66
52 67 This is probably best explained with the simple example file below. You can
53 68 copy this into a file named ex_demo.py, and try running it via:
54 69
55 70 from IPython.demo import Demo
56 71 d = Demo('ex_demo.py')
57 d() <--- Call the d object (omit the parens if you have autocall on).
72 d() <--- Call the d object (omit the parens if you have autocall set to 2).
58 73
59 74 Each time you call the demo object, it runs the next block. The demo object
60 has a few useful methods for navigation, like again(), jump(), seek() and
61 back(). It can be reset for a new run via reset() or reloaded from disk (in
62 case you've edited the source) via reload(). See their docstrings below.
75 has a few useful methods for navigation, like again(), edit(), jump(), seek()
76 and back(). It can be reset for a new run via reset() or reloaded from disk
77 (in case you've edited the source) via reload(). See their docstrings below.
63 78
64 79 #################### EXAMPLE DEMO <ex_demo.py> ###############################
65 80 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
66 81
67 82 print 'Hello, welcome to an interactive IPython demo.'
68 83
69 84 # The mark below defines a block boundary, which is a point where IPython will
70 85 # stop execution and return to the interactive prompt.
71 86 # Note that in actual interactive execution,
72 87 # <demo> --- stop ---
73 88
74 89 x = 1
75 90 y = 2
76 91
77 92 # <demo> --- stop ---
78 93
79 94 # the mark below makes this block as silent
80 95 # <demo> silent
81 96
82 97 print 'This is a silent block, which gets executed but not printed.'
83 98
84 99 # <demo> --- stop ---
85 100 # <demo> auto
86 101 print 'This is an automatic block.'
87 102 print 'It is executed without asking for confirmation, but printed.'
88 103 z = x+y
89 104
90 105 print 'z=',x
91 106
92 107 # <demo> --- stop ---
93 108 # This is just another normal block.
94 109 print 'z is now:', z
95 110
96 111 print 'bye!'
97 112 ################### END EXAMPLE DEMO <ex_demo.py> ############################
98
99 WARNING: this module uses Python 2.3 features, so it won't work in 2.2
100 environments.
101 113 """
102 114 #*****************************************************************************
103 115 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
104 116 #
105 117 # Distributed under the terms of the BSD License. The full license is in
106 118 # the file COPYING, distributed as part of this software.
107 119 #
108 120 #*****************************************************************************
109 121
110 122 import exceptions
123 import os
111 124 import re
112 125 import sys
113 126
114 127 from IPython.PyColorize import Parser
115 from IPython.genutils import marquee, shlex_split, file_read
128 from IPython.genutils import marquee, shlex_split, file_read, file_readlines
116 129
117 __all__ = ['Demo','DemoError']
130 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
118 131
119 132 class DemoError(exceptions.Exception): pass
120 133
121 134 def re_mark(mark):
122 135 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
123 136
124 137 class Demo:
125 138
126 139 re_stop = re_mark('---\s?stop\s?---')
127 140 re_silent = re_mark('silent')
128 141 re_auto = re_mark('auto')
129 142 re_auto_all = re_mark('auto_all')
130 143
131 144 def __init__(self,fname,arg_str='',auto_all=None):
132 145 """Make a new demo object. To run the demo, simply call the object.
133 146
134 147 See the module docstring for full details and an example (you can use
135 148 IPython.Demo? in IPython to see it).
136 149
137 150 Inputs:
138 151
139 152 - fname = filename.
140 153
141 154 Optional inputs:
142 155
143 156 - arg_str(''): a string of arguments, internally converted to a list
144 157 just like sys.argv, so the demo script can see a similar
145 158 environment.
146 159
147 160 - auto_all(None): global flag to run all blocks automatically without
148 161 confirmation. This attribute overrides the block-level tags and
149 162 applies to the whole demo. It is an attribute of the object, and
150 163 can be changed at runtime simply by reassigning it to a boolean
151 164 value.
152 165 """
153
166
154 167 self.fname = fname
155 168 self.sys_argv = [fname] + shlex_split(arg_str)
156 169 self.auto_all = auto_all
157 170
158 171 # get a few things from ipython. While it's a bit ugly design-wise,
159 172 # it ensures that things like color scheme and the like are always in
160 173 # sync with the ipython mode being used. This class is only meant to
161 174 # be used inside ipython anyways, so it's OK.
162 self.ip_showtb = __IPYTHON__.showtraceback
163 175 self.ip_ns = __IPYTHON__.user_ns
164 176 self.ip_colorize = __IPYTHON__.pycolorize
177 self.ip_showtb = __IPYTHON__.showtraceback
178 self.ip_runlines = __IPYTHON__.runlines
179 self.shell = __IPYTHON__
165 180
166 181 # load user data and initialize data structures
167 182 self.reload()
168 183
169 184 def reload(self):
170 185 """Reload source from disk and initialize state."""
171 186 # read data and parse into blocks
172 187 self.src = file_read(self.fname)
173 188 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
174 189 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
175 190 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
176 191
177 192 # if auto_all is not given (def. None), we read it from the file
178 193 if self.auto_all is None:
179 194 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
180 195 else:
181 196 self.auto_all = bool(self.auto_all)
182 197
183 198 # Clean the sources from all markup so it doesn't get displayed when
184 199 # running the demo
185 200 src_blocks = []
186 201 auto_strip = lambda s: self.re_auto.sub('',s)
187 202 for i,b in enumerate(src_b):
188 203 if self._auto[i]:
189 204 src_blocks.append(auto_strip(b))
190 205 else:
191 206 src_blocks.append(b)
192 207 # remove the auto_all marker
193 208 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
194 209
195 210 self.nblocks = len(src_blocks)
196 211 self.src_blocks = src_blocks
197 212
198 213 # also build syntax-highlighted source
199 214 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
200 215
201 216 # ensure clean namespace and seek offset
202 217 self.reset()
203 218
204 219 def reset(self):
205 220 """Reset the namespace and seek pointer to restart the demo"""
206 221 self.user_ns = {}
207 222 self.finished = False
208 223 self.block_index = 0
209 224
210 225 def _validate_index(self,index):
211 226 if index<0 or index>=self.nblocks:
212 227 raise ValueError('invalid block index %s' % index)
213 228
229 def _get_index(self,index):
230 """Get the current block index, validating and checking status.
231
232 Returns None if the demo is finished"""
233
234 if index is None:
235 if self.finished:
236 print 'Demo finished. Use reset() if you want to rerun it.'
237 return None
238 index = self.block_index
239 else:
240 self._validate_index(index)
241 return index
242
214 243 def seek(self,index):
215 244 """Move the current seek pointer to the given block"""
216 245 self._validate_index(index)
217 246 self.block_index = index
218 247 self.finished = False
219 248
220 249 def back(self,num=1):
221 250 """Move the seek pointer back num blocks (default is 1)."""
222 251 self.seek(self.block_index-num)
223 252
224 253 def jump(self,num):
225 254 """Jump a given number of blocks relative to the current one."""
226 255 self.seek(self.block_index+num)
227 256
228 257 def again(self):
229 258 """Move the seek pointer back one block and re-execute."""
230 259 self.back(1)
231 260 self()
232 261
262 def edit(self,index=None):
263 """Edit a block.
264
265 If no number is given, use the last block executed.
266
267 This edits the in-memory copy of the demo, it does NOT modify the
268 original source file. If you want to do that, simply open the file in
269 an editor and use reload() when you make changes to the file. This
270 method is meant to let you change a block during a demonstration for
271 explanatory purposes, without damaging your original script."""
272
273 index = self._get_index(index)
274 if index is None:
275 return
276 # decrease the index by one (unless we're at the very beginning), so
277 # that the default demo.edit() call opens up the sblock we've last run
278 if index>0:
279 index -= 1
280
281 filename = self.shell.mktempfile(self.src_blocks[index])
282 self.shell.hooks.editor(filename,1)
283 new_block = file_read(filename)
284 # update the source and colored block
285 self.src_blocks[index] = new_block
286 self.src_blocks_colored[index] = self.ip_colorize(new_block)
287 self.block_index = index
288 # call to run with the newly edited index
289 self()
290
233 291 def show(self,index=None):
234 292 """Show a single block on screen"""
293
294 index = self._get_index(index)
235 295 if index is None:
236 if self.finished:
237 print 'Demo finished. Use reset() if you want to rerun it.'
238 return
239 index = self.block_index
240 else:
241 self._validate_index(index)
296 return
297
242 298 print marquee('<%s> block # %s (%s remaining)' %
243 299 (self.fname,index,self.nblocks-index-1))
244 300 print self.src_blocks_colored[index],
245 301 sys.stdout.flush()
246 302
247 303 def show_all(self):
248 304 """Show entire demo on screen, block by block"""
249 305
250 306 fname = self.fname
251 307 nblocks = self.nblocks
252 308 silent = self._silent
253 309 for index,block in enumerate(self.src_blocks_colored):
254 310 if silent[index]:
255 311 print marquee('<%s> SILENT block # %s (%s remaining)' %
256 312 (fname,index,nblocks-index-1))
257 313 else:
258 314 print marquee('<%s> block # %s (%s remaining)' %
259 315 (fname,index,nblocks-index-1))
260 316 print block,
261 317 sys.stdout.flush()
262
318
319 def runlines(self,source):
320 """Execute a string with one or more lines of code"""
321
322 exec source in self.user_ns
323
263 324 def __call__(self,index=None):
264 325 """run a block of the demo.
265 326
266 327 If index is given, it should be an integer >=1 and <= nblocks. This
267 328 means that the calling convention is one off from typical Python
268 329 lists. The reason for the inconsistency is that the demo always
269 330 prints 'Block n/N, and N is the total, so it would be very odd to use
270 331 zero-indexing here."""
271 332
272 if index is None and self.finished:
273 print 'Demo finished. Use reset() if you want to rerun it.'
274 return
333 index = self._get_index(index)
275 334 if index is None:
276 index = self.block_index
277 self._validate_index(index)
335 return
278 336 try:
279 337 next_block = self.src_blocks[index]
280 338 self.block_index += 1
281 339 if self._silent[index]:
282 340 print marquee('Executing silent block # %s (%s remaining)' %
283 341 (index,self.nblocks-index-1))
284 342 else:
285 343 self.show(index)
286 344 if self.auto_all or self._auto[index]:
287 345 print marquee('output')
288 346 else:
289 347 print marquee('Press <q> to quit, <Enter> to execute...'),
290 348 ans = raw_input().strip()
291 349 if ans:
292 350 print marquee('Block NOT executed')
293 351 return
294 352 try:
295 353 save_argv = sys.argv
296 354 sys.argv = self.sys_argv
297 exec next_block in self.user_ns
355 self.runlines(next_block)
298 356 finally:
299 357 sys.argv = save_argv
300 358
301 359 except:
302 360 self.ip_showtb(filename=self.fname)
303 361 else:
304 362 self.ip_ns.update(self.user_ns)
305 363
306 364 if self.block_index == self.nblocks:
307 365 print
308 366 print marquee(' END OF DEMO ')
309 367 print marquee('Use reset() if you want to rerun it.')
310 368 self.finished = True
311 369
370 class IPythonDemo(Demo):
371 """Class for interactive demos with IPython's input processing applied.
372
373 This subclasses Demo, but instead of executing each block by the Python
374 interpreter (via exec), it actually calls IPython on it, so that any input
375 filters which may be in place are applied to the input block.
376
377 If you have an interactive environment which exposes special input
378 processing, you can use this class instead to write demo scripts which
379 operate exactly as if you had typed them interactively. The default Demo
380 class requires the input to be valid, pure Python code.
381 """
382
383 def runlines(self,source):
384 """Execute a string with one or more lines of code"""
385
386 self.runlines(source)
387
388 class LineDemo(Demo):
389 """Demo where each line is executed as a separate block.
390
391 The input script should be valid Python code.
392
393 This class doesn't require any markup at all, and it's meant for simple
394 scripts (with no nesting or any kind of indentation) which consist of
395 multiple lines of input to be executed, one at a time, as if they had been
396 typed in the interactive prompt."""
397
398 def reload(self):
399 """Reload source from disk and initialize state."""
400 # read data and parse into blocks
401 src_b = [l for l in file_readlines(self.fname) if l.strip()]
402 nblocks = len(src_b)
403 self.src = os.linesep.join(file_readlines(self.fname))
404 self._silent = [False]*nblocks
405 self._auto = [True]*nblocks
406 self.auto_all = True
407 self.nblocks = nblocks
408 self.src_blocks = src_b
409
410 # also build syntax-highlighted source
411 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
412
413 # ensure clean namespace and seek offset
414 self.reset()
415
416 class IPythonLineDemo(IPythonDemo,LineDemo):
417 """Variant of the LineDemo class whose input is processed by IPython."""
418 pass
@@ -1,1761 +1,1768 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 1110 2006-01-30 20:43:30Z vivainio $"""
8 $Id: genutils.py 1126 2006-02-06 02:31:40Z fperez $"""
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 from __future__ import generators # 2.2 compatibility
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 21 __license__ = Release.license
22 22
23 23 #****************************************************************************
24 24 # required modules from the Python standard library
25 25 import __main__
26 26 import commands
27 27 import os
28 28 import re
29 29 import shlex
30 30 import shutil
31 31 import sys
32 32 import tempfile
33 33 import time
34 34 import types
35 35
36 36 # Other IPython utilities
37 37 from IPython.Itpl import Itpl,itpl,printpl
38 38 from IPython import DPyGetOpt
39 39 from path import path
40 40 if os.name == "nt":
41 41 from IPython.winconsole import get_console_size
42 42
43 43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 44 # 2.2-friendly
45 45 try:
46 46 basestring
47 47 except NameError:
48 48 import types
49 49 basestring = (types.StringType, types.UnicodeType)
50 50 True = 1==1
51 51 False = 1==0
52 52
53 53 def enumerate(obj):
54 54 i = -1
55 55 for item in obj:
56 56 i += 1
57 57 yield i, item
58 58
59 59 # add these to the builtin namespace, so that all modules find them
60 60 import __builtin__
61 61 __builtin__.basestring = basestring
62 62 __builtin__.True = True
63 63 __builtin__.False = False
64 64 __builtin__.enumerate = enumerate
65 65
66 66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 68 try:
69 69 shlex_split = shlex.split
70 70 except AttributeError:
71 71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 75 'À�ÂÃÄÅÆÇÈÉÊËÌ�Î��ÑÒÓÔÕÖØÙÚÛÜ�Þ%s'
76 76 % os.sep)
77 77
78 78 def shlex_split(s):
79 79 """Simplified backport to Python 2.2 of shlex.split().
80 80
81 81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 82 several of the features needed to really match the functionality of
83 83 shlex.split() in 2.3."""
84 84
85 85 lex = shlex.shlex(StringIO(s))
86 86 # Try to get options, extensions and path separators as characters
87 87 lex.wordchars = _wordchars
88 88 lex.commenters = ''
89 89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 90 # iterator.
91 91 lout = []
92 92 while 1:
93 93 token = lex.get_token()
94 94 if token == '':
95 95 break
96 96 # Try to handle quoted tokens correctly
97 97 quotes = _quotesre.match(token)
98 98 if quotes:
99 99 token = quotes.group(1)
100 100 lout.append(token)
101 101 return lout
102 102
103 103 #****************************************************************************
104 104 # Exceptions
105 105 class Error(Exception):
106 106 """Base class for exceptions in this module."""
107 107 pass
108 108
109 109 #----------------------------------------------------------------------------
110 110 class IOStream:
111 111 def __init__(self,stream,fallback):
112 112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 113 stream = fallback
114 114 self.stream = stream
115 115 self._swrite = stream.write
116 116 self.flush = stream.flush
117 117
118 118 def write(self,data):
119 119 try:
120 120 self._swrite(data)
121 121 except:
122 122 try:
123 123 # print handles some unicode issues which may trip a plain
124 124 # write() call. Attempt to emulate write() by using a
125 125 # trailing comma
126 126 print >> self.stream, data,
127 127 except:
128 128 # if we get here, something is seriously broken.
129 129 print >> sys.stderr, \
130 130 'ERROR - failed to write data to stream:', stream
131 131
132 132 class IOTerm:
133 133 """ Term holds the file or file-like objects for handling I/O operations.
134 134
135 135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 136 Windows they can can replaced to allow editing the strings before they are
137 137 displayed."""
138 138
139 139 # In the future, having IPython channel all its I/O operations through
140 140 # this class will make it easier to embed it into other environments which
141 141 # are not a normal terminal (such as a GUI-based shell)
142 142 def __init__(self,cin=None,cout=None,cerr=None):
143 143 self.cin = IOStream(cin,sys.stdin)
144 144 self.cout = IOStream(cout,sys.stdout)
145 145 self.cerr = IOStream(cerr,sys.stderr)
146 146
147 147 # Global variable to be used for all I/O
148 148 Term = IOTerm()
149 149
150 150 import IPython.rlineimpl as readline
151 151 # Remake Term to use the readline i/o facilities
152 152 if sys.platform == 'win32' and readline.have_readline:
153 153
154 154 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
155 155
156 156
157 157 #****************************************************************************
158 158 # Generic warning/error printer, used by everything else
159 159 def warn(msg,level=2,exit_val=1):
160 160 """Standard warning printer. Gives formatting consistency.
161 161
162 162 Output is sent to Term.cerr (sys.stderr by default).
163 163
164 164 Options:
165 165
166 166 -level(2): allows finer control:
167 167 0 -> Do nothing, dummy function.
168 168 1 -> Print message.
169 169 2 -> Print 'WARNING:' + message. (Default level).
170 170 3 -> Print 'ERROR:' + message.
171 171 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
172 172
173 173 -exit_val (1): exit value returned by sys.exit() for a level 4
174 174 warning. Ignored for all other levels."""
175 175
176 176 if level>0:
177 177 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
178 178 print >> Term.cerr, '%s%s' % (header[level],msg)
179 179 if level == 4:
180 180 print >> Term.cerr,'Exiting.\n'
181 181 sys.exit(exit_val)
182 182
183 183 def info(msg):
184 184 """Equivalent to warn(msg,level=1)."""
185 185
186 186 warn(msg,level=1)
187 187
188 188 def error(msg):
189 189 """Equivalent to warn(msg,level=3)."""
190 190
191 191 warn(msg,level=3)
192 192
193 193 def fatal(msg,exit_val=1):
194 194 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
195 195
196 196 warn(msg,exit_val=exit_val,level=4)
197 197
198 198 #---------------------------------------------------------------------------
199 199 # Debugging routines
200 200 #
201 201 def debugx(expr,pre_msg=''):
202 202 """Print the value of an expression from the caller's frame.
203 203
204 204 Takes an expression, evaluates it in the caller's frame and prints both
205 205 the given expression and the resulting value (as well as a debug mark
206 206 indicating the name of the calling function. The input must be of a form
207 207 suitable for eval().
208 208
209 209 An optional message can be passed, which will be prepended to the printed
210 210 expr->value pair."""
211 211
212 212 cf = sys._getframe(1)
213 213 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
214 214 eval(expr,cf.f_globals,cf.f_locals))
215 215
216 216 # deactivate it by uncommenting the following line, which makes it a no-op
217 217 #def debugx(expr,pre_msg=''): pass
218 218
219 219 #----------------------------------------------------------------------------
220 220 StringTypes = types.StringTypes
221 221
222 222 # Basic timing functionality
223 223
224 224 # If possible (Unix), use the resource module instead of time.clock()
225 225 try:
226 226 import resource
227 227 def clock():
228 228 """clock() -> floating point number
229 229
230 230 Return the CPU time in seconds (user time only, system time is
231 231 ignored) since the start of the process. This is done via a call to
232 232 resource.getrusage, so it avoids the wraparound problems in
233 233 time.clock()."""
234 234
235 235 return resource.getrusage(resource.RUSAGE_SELF)[0]
236 236
237 237 def clock2():
238 238 """clock2() -> (t_user,t_system)
239 239
240 240 Similar to clock(), but return a tuple of user/system times."""
241 241 return resource.getrusage(resource.RUSAGE_SELF)[:2]
242 242
243 243 except ImportError:
244 244 clock = time.clock
245 245 def clock2():
246 246 """Under windows, system CPU time can't be measured.
247 247
248 248 This just returns clock() and zero."""
249 249 return time.clock(),0.0
250 250
251 251 def timings_out(reps,func,*args,**kw):
252 252 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
253 253
254 254 Execute a function reps times, return a tuple with the elapsed total
255 255 CPU time in seconds, the time per call and the function's output.
256 256
257 257 Under Unix, the return value is the sum of user+system time consumed by
258 258 the process, computed via the resource module. This prevents problems
259 259 related to the wraparound effect which the time.clock() function has.
260 260
261 261 Under Windows the return value is in wall clock seconds. See the
262 262 documentation for the time module for more details."""
263 263
264 264 reps = int(reps)
265 265 assert reps >=1, 'reps must be >= 1'
266 266 if reps==1:
267 267 start = clock()
268 268 out = func(*args,**kw)
269 269 tot_time = clock()-start
270 270 else:
271 271 rng = xrange(reps-1) # the last time is executed separately to store output
272 272 start = clock()
273 273 for dummy in rng: func(*args,**kw)
274 274 out = func(*args,**kw) # one last time
275 275 tot_time = clock()-start
276 276 av_time = tot_time / reps
277 277 return tot_time,av_time,out
278 278
279 279 def timings(reps,func,*args,**kw):
280 280 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
281 281
282 282 Execute a function reps times, return a tuple with the elapsed total CPU
283 283 time in seconds and the time per call. These are just the first two values
284 284 in timings_out()."""
285 285
286 286 return timings_out(reps,func,*args,**kw)[0:2]
287 287
288 288 def timing(func,*args,**kw):
289 289 """timing(func,*args,**kw) -> t_total
290 290
291 291 Execute a function once, return the elapsed total CPU time in
292 292 seconds. This is just the first value in timings_out()."""
293 293
294 294 return timings_out(1,func,*args,**kw)[0]
295 295
296 296 #****************************************************************************
297 297 # file and system
298 298
299 299 def system(cmd,verbose=0,debug=0,header=''):
300 300 """Execute a system command, return its exit status.
301 301
302 302 Options:
303 303
304 304 - verbose (0): print the command to be executed.
305 305
306 306 - debug (0): only print, do not actually execute.
307 307
308 308 - header (''): Header to print on screen prior to the executed command (it
309 309 is only prepended to the command, no newlines are added).
310 310
311 311 Note: a stateful version of this function is available through the
312 312 SystemExec class."""
313 313
314 314 stat = 0
315 315 if verbose or debug: print header+cmd
316 316 sys.stdout.flush()
317 317 if not debug: stat = os.system(cmd)
318 318 return stat
319 319
320 320 # This function is used by ipython in a lot of places to make system calls.
321 321 # We need it to be slightly different under win32, due to the vagaries of
322 322 # 'network shares'. A win32 override is below.
323 323
324 324 def shell(cmd,verbose=0,debug=0,header=''):
325 325 """Execute a command in the system shell, always return None.
326 326
327 327 Options:
328 328
329 329 - verbose (0): print the command to be executed.
330 330
331 331 - debug (0): only print, do not actually execute.
332 332
333 333 - header (''): Header to print on screen prior to the executed command (it
334 334 is only prepended to the command, no newlines are added).
335 335
336 336 Note: this is similar to genutils.system(), but it returns None so it can
337 337 be conveniently used in interactive loops without getting the return value
338 338 (typically 0) printed many times."""
339 339
340 340 stat = 0
341 341 if verbose or debug: print header+cmd
342 342 # flush stdout so we don't mangle python's buffering
343 343 sys.stdout.flush()
344 344 if not debug:
345 345 os.system(cmd)
346 346
347 347 # override shell() for win32 to deal with network shares
348 348 if os.name in ('nt','dos'):
349 349
350 350 shell_ori = shell
351 351
352 352 def shell(cmd,verbose=0,debug=0,header=''):
353 353 if os.getcwd().startswith(r"\\"):
354 354 path = os.getcwd()
355 355 # change to c drive (cannot be on UNC-share when issuing os.system,
356 356 # as cmd.exe cannot handle UNC addresses)
357 357 os.chdir("c:")
358 358 # issue pushd to the UNC-share and then run the command
359 359 try:
360 360 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
361 361 finally:
362 362 os.chdir(path)
363 363 else:
364 364 shell_ori(cmd,verbose,debug,header)
365 365
366 366 shell.__doc__ = shell_ori.__doc__
367 367
368 368 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
369 369 """Dummy substitute for perl's backquotes.
370 370
371 371 Executes a command and returns the output.
372 372
373 373 Accepts the same arguments as system(), plus:
374 374
375 375 - split(0): if true, the output is returned as a list split on newlines.
376 376
377 377 Note: a stateful version of this function is available through the
378 378 SystemExec class."""
379 379
380 380 if verbose or debug: print header+cmd
381 381 if not debug:
382 382 output = commands.getoutput(cmd)
383 383 if split:
384 384 return output.split('\n')
385 385 else:
386 386 return output
387 387
388 388 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
389 389 """Return (standard output,standard error) of executing cmd in a shell.
390 390
391 391 Accepts the same arguments as system(), plus:
392 392
393 393 - split(0): if true, each of stdout/err is returned as a list split on
394 394 newlines.
395 395
396 396 Note: a stateful version of this function is available through the
397 397 SystemExec class."""
398 398
399 399 if verbose or debug: print header+cmd
400 400 if not cmd:
401 401 if split:
402 402 return [],[]
403 403 else:
404 404 return '',''
405 405 if not debug:
406 406 pin,pout,perr = os.popen3(cmd)
407 407 tout = pout.read().rstrip()
408 408 terr = perr.read().rstrip()
409 409 pin.close()
410 410 pout.close()
411 411 perr.close()
412 412 if split:
413 413 return tout.split('\n'),terr.split('\n')
414 414 else:
415 415 return tout,terr
416 416
417 417 # for compatibility with older naming conventions
418 418 xsys = system
419 419 bq = getoutput
420 420
421 421 class SystemExec:
422 422 """Access the system and getoutput functions through a stateful interface.
423 423
424 424 Note: here we refer to the system and getoutput functions from this
425 425 library, not the ones from the standard python library.
426 426
427 427 This class offers the system and getoutput functions as methods, but the
428 428 verbose, debug and header parameters can be set for the instance (at
429 429 creation time or later) so that they don't need to be specified on each
430 430 call.
431 431
432 432 For efficiency reasons, there's no way to override the parameters on a
433 433 per-call basis other than by setting instance attributes. If you need
434 434 local overrides, it's best to directly call system() or getoutput().
435 435
436 436 The following names are provided as alternate options:
437 437 - xsys: alias to system
438 438 - bq: alias to getoutput
439 439
440 440 An instance can then be created as:
441 441 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
442 442
443 443 And used as:
444 444 >>> sysexec.xsys('pwd')
445 445 >>> dirlist = sysexec.bq('ls -l')
446 446 """
447 447
448 448 def __init__(self,verbose=0,debug=0,header='',split=0):
449 449 """Specify the instance's values for verbose, debug and header."""
450 450 setattr_list(self,'verbose debug header split')
451 451
452 452 def system(self,cmd):
453 453 """Stateful interface to system(), with the same keyword parameters."""
454 454
455 455 system(cmd,self.verbose,self.debug,self.header)
456 456
457 457 def shell(self,cmd):
458 458 """Stateful interface to shell(), with the same keyword parameters."""
459 459
460 460 shell(cmd,self.verbose,self.debug,self.header)
461 461
462 462 xsys = system # alias
463 463
464 464 def getoutput(self,cmd):
465 465 """Stateful interface to getoutput()."""
466 466
467 467 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
468 468
469 469 def getoutputerror(self,cmd):
470 470 """Stateful interface to getoutputerror()."""
471 471
472 472 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
473 473
474 474 bq = getoutput # alias
475 475
476 476 #-----------------------------------------------------------------------------
477 477 def mutex_opts(dict,ex_op):
478 478 """Check for presence of mutually exclusive keys in a dict.
479 479
480 480 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
481 481 for op1,op2 in ex_op:
482 482 if op1 in dict and op2 in dict:
483 483 raise ValueError,'\n*** ERROR in Arguments *** '\
484 484 'Options '+op1+' and '+op2+' are mutually exclusive.'
485 485
486 486 #-----------------------------------------------------------------------------
487 487 def get_py_filename(name):
488 488 """Return a valid python filename in the current directory.
489 489
490 490 If the given name is not a file, it adds '.py' and searches again.
491 491 Raises IOError with an informative message if the file isn't found."""
492 492
493 493 name = os.path.expanduser(name)
494 494 if not os.path.isfile(name) and not name.endswith('.py'):
495 495 name += '.py'
496 496 if os.path.isfile(name):
497 497 return name
498 498 else:
499 499 raise IOError,'File `%s` not found.' % name
500 500
501 501 #-----------------------------------------------------------------------------
502 502 def filefind(fname,alt_dirs = None):
503 503 """Return the given filename either in the current directory, if it
504 504 exists, or in a specified list of directories.
505 505
506 506 ~ expansion is done on all file and directory names.
507 507
508 508 Upon an unsuccessful search, raise an IOError exception."""
509 509
510 510 if alt_dirs is None:
511 511 try:
512 512 alt_dirs = get_home_dir()
513 513 except HomeDirError:
514 514 alt_dirs = os.getcwd()
515 515 search = [fname] + list_strings(alt_dirs)
516 516 search = map(os.path.expanduser,search)
517 517 #print 'search list for',fname,'list:',search # dbg
518 518 fname = search[0]
519 519 if os.path.isfile(fname):
520 520 return fname
521 521 for direc in search[1:]:
522 522 testname = os.path.join(direc,fname)
523 523 #print 'testname',testname # dbg
524 524 if os.path.isfile(testname):
525 525 return testname
526 526 raise IOError,'File' + `fname` + \
527 527 ' not found in current or supplied directories:' + `alt_dirs`
528 528
529 529 #----------------------------------------------------------------------------
530 530 def file_read(filename):
531 531 """Read a file and close it. Returns the file source."""
532 fobj=open(filename,'r');
532 fobj = open(filename,'r');
533 533 source = fobj.read();
534 534 fobj.close()
535 535 return source
536 536
537 def file_readlines(filename):
538 """Read a file and close it. Returns the file source using readlines()."""
539 fobj = open(filename,'r');
540 lines = fobj.readlines();
541 fobj.close()
542 return lines
543
537 544 #----------------------------------------------------------------------------
538 545 def target_outdated(target,deps):
539 546 """Determine whether a target is out of date.
540 547
541 548 target_outdated(target,deps) -> 1/0
542 549
543 550 deps: list of filenames which MUST exist.
544 551 target: single filename which may or may not exist.
545 552
546 553 If target doesn't exist or is older than any file listed in deps, return
547 554 true, otherwise return false.
548 555 """
549 556 try:
550 557 target_time = os.path.getmtime(target)
551 558 except os.error:
552 559 return 1
553 560 for dep in deps:
554 561 dep_time = os.path.getmtime(dep)
555 562 if dep_time > target_time:
556 563 #print "For target",target,"Dep failed:",dep # dbg
557 564 #print "times (dep,tar):",dep_time,target_time # dbg
558 565 return 1
559 566 return 0
560 567
561 568 #-----------------------------------------------------------------------------
562 569 def target_update(target,deps,cmd):
563 570 """Update a target with a given command given a list of dependencies.
564 571
565 572 target_update(target,deps,cmd) -> runs cmd if target is outdated.
566 573
567 574 This is just a wrapper around target_outdated() which calls the given
568 575 command if target is outdated."""
569 576
570 577 if target_outdated(target,deps):
571 578 xsys(cmd)
572 579
573 580 #----------------------------------------------------------------------------
574 581 def unquote_ends(istr):
575 582 """Remove a single pair of quotes from the endpoints of a string."""
576 583
577 584 if not istr:
578 585 return istr
579 586 if (istr[0]=="'" and istr[-1]=="'") or \
580 587 (istr[0]=='"' and istr[-1]=='"'):
581 588 return istr[1:-1]
582 589 else:
583 590 return istr
584 591
585 592 #----------------------------------------------------------------------------
586 593 def process_cmdline(argv,names=[],defaults={},usage=''):
587 594 """ Process command-line options and arguments.
588 595
589 596 Arguments:
590 597
591 598 - argv: list of arguments, typically sys.argv.
592 599
593 600 - names: list of option names. See DPyGetOpt docs for details on options
594 601 syntax.
595 602
596 603 - defaults: dict of default values.
597 604
598 605 - usage: optional usage notice to print if a wrong argument is passed.
599 606
600 607 Return a dict of options and a list of free arguments."""
601 608
602 609 getopt = DPyGetOpt.DPyGetOpt()
603 610 getopt.setIgnoreCase(0)
604 611 getopt.parseConfiguration(names)
605 612
606 613 try:
607 614 getopt.processArguments(argv)
608 615 except:
609 616 print usage
610 617 warn(`sys.exc_value`,level=4)
611 618
612 619 defaults.update(getopt.optionValues)
613 620 args = getopt.freeValues
614 621
615 622 return defaults,args
616 623
617 624 #----------------------------------------------------------------------------
618 625 def optstr2types(ostr):
619 626 """Convert a string of option names to a dict of type mappings.
620 627
621 628 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
622 629
623 630 This is used to get the types of all the options in a string formatted
624 631 with the conventions of DPyGetOpt. The 'type' None is used for options
625 632 which are strings (they need no further conversion). This function's main
626 633 use is to get a typemap for use with read_dict().
627 634 """
628 635
629 636 typeconv = {None:'',int:'',float:''}
630 637 typemap = {'s':None,'i':int,'f':float}
631 638 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
632 639
633 640 for w in ostr.split():
634 641 oname,alias,otype = opt_re.match(w).groups()
635 642 if otype == '' or alias == '!': # simple switches are integers too
636 643 otype = 'i'
637 644 typeconv[typemap[otype]] += oname + ' '
638 645 return typeconv
639 646
640 647 #----------------------------------------------------------------------------
641 648 def read_dict(filename,type_conv=None,**opt):
642 649
643 650 """Read a dictionary of key=value pairs from an input file, optionally
644 651 performing conversions on the resulting values.
645 652
646 653 read_dict(filename,type_conv,**opt) -> dict
647 654
648 655 Only one value per line is accepted, the format should be
649 656 # optional comments are ignored
650 657 key value\n
651 658
652 659 Args:
653 660
654 661 - type_conv: A dictionary specifying which keys need to be converted to
655 662 which types. By default all keys are read as strings. This dictionary
656 663 should have as its keys valid conversion functions for strings
657 664 (int,long,float,complex, or your own). The value for each key
658 665 (converter) should be a whitespace separated string containing the names
659 666 of all the entries in the file to be converted using that function. For
660 667 keys to be left alone, use None as the conversion function (only needed
661 668 with purge=1, see below).
662 669
663 670 - opt: dictionary with extra options as below (default in parens)
664 671
665 672 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
666 673 of the dictionary to be returned. If purge is going to be used, the
667 674 set of keys to be left as strings also has to be explicitly specified
668 675 using the (non-existent) conversion function None.
669 676
670 677 fs(None): field separator. This is the key/value separator to be used
671 678 when parsing the file. The None default means any whitespace [behavior
672 679 of string.split()].
673 680
674 681 strip(0): if 1, strip string values of leading/trailinig whitespace.
675 682
676 683 warn(1): warning level if requested keys are not found in file.
677 684 - 0: silently ignore.
678 685 - 1: inform but proceed.
679 686 - 2: raise KeyError exception.
680 687
681 688 no_empty(0): if 1, remove keys with whitespace strings as a value.
682 689
683 690 unique([]): list of keys (or space separated string) which can't be
684 691 repeated. If one such key is found in the file, each new instance
685 692 overwrites the previous one. For keys not listed here, the behavior is
686 693 to make a list of all appearances.
687 694
688 695 Example:
689 696 If the input file test.ini has:
690 697 i 3
691 698 x 4.5
692 699 y 5.5
693 700 s hi ho
694 701 Then:
695 702
696 703 >>> type_conv={int:'i',float:'x',None:'s'}
697 704 >>> read_dict('test.ini')
698 705 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
699 706 >>> read_dict('test.ini',type_conv)
700 707 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
701 708 >>> read_dict('test.ini',type_conv,purge=1)
702 709 {'i': 3, 's': 'hi ho', 'x': 4.5}
703 710 """
704 711
705 712 # starting config
706 713 opt.setdefault('purge',0)
707 714 opt.setdefault('fs',None) # field sep defaults to any whitespace
708 715 opt.setdefault('strip',0)
709 716 opt.setdefault('warn',1)
710 717 opt.setdefault('no_empty',0)
711 718 opt.setdefault('unique','')
712 719 if type(opt['unique']) in StringTypes:
713 720 unique_keys = qw(opt['unique'])
714 721 elif type(opt['unique']) in (types.TupleType,types.ListType):
715 722 unique_keys = opt['unique']
716 723 else:
717 724 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
718 725
719 726 dict = {}
720 727 # first read in table of values as strings
721 728 file = open(filename,'r')
722 729 for line in file.readlines():
723 730 line = line.strip()
724 731 if len(line) and line[0]=='#': continue
725 732 if len(line)>0:
726 733 lsplit = line.split(opt['fs'],1)
727 734 try:
728 735 key,val = lsplit
729 736 except ValueError:
730 737 key,val = lsplit[0],''
731 738 key = key.strip()
732 739 if opt['strip']: val = val.strip()
733 740 if val == "''" or val == '""': val = ''
734 741 if opt['no_empty'] and (val=='' or val.isspace()):
735 742 continue
736 743 # if a key is found more than once in the file, build a list
737 744 # unless it's in the 'unique' list. In that case, last found in file
738 745 # takes precedence. User beware.
739 746 try:
740 747 if dict[key] and key in unique_keys:
741 748 dict[key] = val
742 749 elif type(dict[key]) is types.ListType:
743 750 dict[key].append(val)
744 751 else:
745 752 dict[key] = [dict[key],val]
746 753 except KeyError:
747 754 dict[key] = val
748 755 # purge if requested
749 756 if opt['purge']:
750 757 accepted_keys = qwflat(type_conv.values())
751 758 for key in dict.keys():
752 759 if key in accepted_keys: continue
753 760 del(dict[key])
754 761 # now convert if requested
755 762 if type_conv==None: return dict
756 763 conversions = type_conv.keys()
757 764 try: conversions.remove(None)
758 765 except: pass
759 766 for convert in conversions:
760 767 for val in qw(type_conv[convert]):
761 768 try:
762 769 dict[val] = convert(dict[val])
763 770 except KeyError,e:
764 771 if opt['warn'] == 0:
765 772 pass
766 773 elif opt['warn'] == 1:
767 774 print >>sys.stderr, 'Warning: key',val,\
768 775 'not found in file',filename
769 776 elif opt['warn'] == 2:
770 777 raise KeyError,e
771 778 else:
772 779 raise ValueError,'Warning level must be 0,1 or 2'
773 780
774 781 return dict
775 782
776 783 #----------------------------------------------------------------------------
777 784 def flag_calls(func):
778 785 """Wrap a function to detect and flag when it gets called.
779 786
780 787 This is a decorator which takes a function and wraps it in a function with
781 788 a 'called' attribute. wrapper.called is initialized to False.
782 789
783 790 The wrapper.called attribute is set to False right before each call to the
784 791 wrapped function, so if the call fails it remains False. After the call
785 792 completes, wrapper.called is set to True and the output is returned.
786 793
787 794 Testing for truth in wrapper.called allows you to determine if a call to
788 795 func() was attempted and succeeded."""
789 796
790 797 def wrapper(*args,**kw):
791 798 wrapper.called = False
792 799 out = func(*args,**kw)
793 800 wrapper.called = True
794 801 return out
795 802
796 803 wrapper.called = False
797 804 wrapper.__doc__ = func.__doc__
798 805 return wrapper
799 806
800 807 #----------------------------------------------------------------------------
801 808 class HomeDirError(Error):
802 809 pass
803 810
804 811 def get_home_dir():
805 812 """Return the closest possible equivalent to a 'home' directory.
806 813
807 814 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
808 815
809 816 Currently only Posix and NT are implemented, a HomeDirError exception is
810 817 raised for all other OSes. """
811 818
812 819 isdir = os.path.isdir
813 820 env = os.environ
814 821 try:
815 822 homedir = env['HOME']
816 823 if not isdir(homedir):
817 824 # in case a user stuck some string which does NOT resolve to a
818 825 # valid path, it's as good as if we hadn't foud it
819 826 raise KeyError
820 827 return homedir
821 828 except KeyError:
822 829 if os.name == 'posix':
823 830 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
824 831 elif os.name == 'nt':
825 832 # For some strange reason, win9x returns 'nt' for os.name.
826 833 try:
827 834 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
828 835 if not isdir(homedir):
829 836 homedir = os.path.join(env['USERPROFILE'])
830 837 if not isdir(homedir):
831 838 raise HomeDirError
832 839 return homedir
833 840 except:
834 841 try:
835 842 # Use the registry to get the 'My Documents' folder.
836 843 import _winreg as wreg
837 844 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
838 845 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
839 846 homedir = wreg.QueryValueEx(key,'Personal')[0]
840 847 key.Close()
841 848 if not isdir(homedir):
842 849 e = ('Invalid "Personal" folder registry key '
843 850 'typically "My Documents".\n'
844 851 'Value: %s\n'
845 852 'This is not a valid directory on your system.' %
846 853 homedir)
847 854 raise HomeDirError(e)
848 855 return homedir
849 856 except HomeDirError:
850 857 raise
851 858 except:
852 859 return 'C:\\'
853 860 elif os.name == 'dos':
854 861 # Desperate, may do absurd things in classic MacOS. May work under DOS.
855 862 return 'C:\\'
856 863 else:
857 864 raise HomeDirError,'support for your operating system not implemented.'
858 865
859 866 #****************************************************************************
860 867 # strings and text
861 868
862 869 class LSString(str):
863 870 """String derivative with a special access attributes.
864 871
865 872 These are normal strings, but with the special attributes:
866 873
867 874 .l (or .list) : value as list (split on newlines).
868 875 .n (or .nlstr): original value (the string itself).
869 876 .s (or .spstr): value as whitespace-separated string.
870 877
871 878 Any values which require transformations are computed only once and
872 879 cached.
873 880
874 881 Such strings are very useful to efficiently interact with the shell, which
875 882 typically only understands whitespace-separated options for commands."""
876 883
877 884 def get_list(self):
878 885 try:
879 886 return self.__list
880 887 except AttributeError:
881 888 self.__list = self.split('\n')
882 889 return self.__list
883 890
884 891 l = list = property(get_list)
885 892
886 893 def get_spstr(self):
887 894 try:
888 895 return self.__spstr
889 896 except AttributeError:
890 897 self.__spstr = self.replace('\n',' ')
891 898 return self.__spstr
892 899
893 900 s = spstr = property(get_spstr)
894 901
895 902 def get_nlstr(self):
896 903 return self
897 904
898 905 n = nlstr = property(get_nlstr)
899 906
900 907 def get_paths(self):
901 908 try:
902 909 return self.__paths
903 910 except AttributeError:
904 911 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
905 912 return self.__paths
906 913
907 914 p = paths = property(get_paths)
908 915
909 916
910 917 #----------------------------------------------------------------------------
911 918 class SList(list):
912 919 """List derivative with a special access attributes.
913 920
914 921 These are normal lists, but with the special attributes:
915 922
916 923 .l (or .list) : value as list (the list itself).
917 924 .n (or .nlstr): value as a string, joined on newlines.
918 925 .s (or .spstr): value as a string, joined on spaces.
919 926
920 927 Any values which require transformations are computed only once and
921 928 cached."""
922 929
923 930 def get_list(self):
924 931 return self
925 932
926 933 l = list = property(get_list)
927 934
928 935 def get_spstr(self):
929 936 try:
930 937 return self.__spstr
931 938 except AttributeError:
932 939 self.__spstr = ' '.join(self)
933 940 return self.__spstr
934 941
935 942 s = spstr = property(get_spstr)
936 943
937 944 def get_nlstr(self):
938 945 try:
939 946 return self.__nlstr
940 947 except AttributeError:
941 948 self.__nlstr = '\n'.join(self)
942 949 return self.__nlstr
943 950
944 951 n = nlstr = property(get_nlstr)
945 952
946 953 def get_paths(self):
947 954 try:
948 955 return self.__paths
949 956 except AttributeError:
950 957 self.__paths = [path(p) for p in self if os.path.exists(p)]
951 958 return self.__paths
952 959
953 960 p = paths = property(get_paths)
954 961
955 962 #----------------------------------------------------------------------------
956 963 def esc_quotes(strng):
957 964 """Return the input string with single and double quotes escaped out"""
958 965
959 966 return strng.replace('"','\\"').replace("'","\\'")
960 967
961 968 #----------------------------------------------------------------------------
962 969 def make_quoted_expr(s):
963 970 """Return string s in appropriate quotes, using raw string if possible.
964 971
965 972 Effectively this turns string: cd \ao\ao\
966 973 to: r"cd \ao\ao\_"[:-1]
967 974
968 975 Note the use of raw string and padding at the end to allow trailing backslash.
969 976
970 977 """
971 978
972 979 tail = ''
973 980 tailpadding = ''
974 981 raw = ''
975 982 if "\\" in s:
976 983 raw = 'r'
977 984 if s.endswith('\\'):
978 985 tail = '[:-1]'
979 986 tailpadding = '_'
980 987 if '"' not in s:
981 988 quote = '"'
982 989 elif "'" not in s:
983 990 quote = "'"
984 991 elif '"""' not in s and not s.endswith('"'):
985 992 quote = '"""'
986 993 elif "'''" not in s and not s.endswith("'"):
987 994 quote = "'''"
988 995 else:
989 996 # give up, backslash-escaped string will do
990 997 return '"%s"' % esc_quotes(s)
991 998 res = itpl("$raw$quote$s$tailpadding$quote$tail")
992 999 return res
993 1000
994 1001
995 1002 #----------------------------------------------------------------------------
996 1003 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
997 1004 """Take multiple lines of input.
998 1005
999 1006 A list with each line of input as a separate element is returned when a
1000 1007 termination string is entered (defaults to a single '.'). Input can also
1001 1008 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1002 1009
1003 1010 Lines of input which end in \\ are joined into single entries (and a
1004 1011 secondary continuation prompt is issued as long as the user terminates
1005 1012 lines with \\). This allows entering very long strings which are still
1006 1013 meant to be treated as single entities.
1007 1014 """
1008 1015
1009 1016 try:
1010 1017 if header:
1011 1018 header += '\n'
1012 1019 lines = [raw_input(header + ps1)]
1013 1020 except EOFError:
1014 1021 return []
1015 1022 terminate = [terminate_str]
1016 1023 try:
1017 1024 while lines[-1:] != terminate:
1018 1025 new_line = raw_input(ps1)
1019 1026 while new_line.endswith('\\'):
1020 1027 new_line = new_line[:-1] + raw_input(ps2)
1021 1028 lines.append(new_line)
1022 1029
1023 1030 return lines[:-1] # don't return the termination command
1024 1031 except EOFError:
1025 1032 print
1026 1033 return lines
1027 1034
1028 1035 #----------------------------------------------------------------------------
1029 1036 def raw_input_ext(prompt='', ps2='... '):
1030 1037 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1031 1038
1032 1039 line = raw_input(prompt)
1033 1040 while line.endswith('\\'):
1034 1041 line = line[:-1] + raw_input(ps2)
1035 1042 return line
1036 1043
1037 1044 #----------------------------------------------------------------------------
1038 1045 def ask_yes_no(prompt,default=None):
1039 1046 """Asks a question and returns an integer 1/0 (y/n) answer.
1040 1047
1041 1048 If default is given (one of 'y','n'), it is used if the user input is
1042 1049 empty. Otherwise the question is repeated until an answer is given.
1043 1050 If EOF occurs 20 times consecutively, the default answer is assumed,
1044 1051 or if there is no default, an exception is raised to prevent infinite
1045 1052 loops.
1046 1053
1047 1054 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1048 1055
1049 1056 answers = {'y':True,'n':False,'yes':True,'no':False}
1050 1057 ans = None
1051 1058 eofs, max_eofs = 0, 20
1052 1059 while ans not in answers.keys():
1053 1060 try:
1054 1061 ans = raw_input(prompt+' ').lower()
1055 1062 if not ans: # response was an empty string
1056 1063 ans = default
1057 1064 eofs = 0
1058 1065 except (EOFError,KeyboardInterrupt):
1059 1066 eofs = eofs + 1
1060 1067 if eofs >= max_eofs:
1061 1068 if default in answers.keys():
1062 1069 ans = default
1063 1070 else:
1064 1071 raise
1065 1072
1066 1073 return answers[ans]
1067 1074
1068 1075 #----------------------------------------------------------------------------
1069 1076 def marquee(txt='',width=78,mark='*'):
1070 1077 """Return the input string centered in a 'marquee'."""
1071 1078 if not txt:
1072 1079 return (mark*width)[:width]
1073 1080 nmark = (width-len(txt)-2)/len(mark)/2
1074 1081 if nmark < 0: nmark =0
1075 1082 marks = mark*nmark
1076 1083 return '%s %s %s' % (marks,txt,marks)
1077 1084
1078 1085 #----------------------------------------------------------------------------
1079 1086 class EvalDict:
1080 1087 """
1081 1088 Emulate a dict which evaluates its contents in the caller's frame.
1082 1089
1083 1090 Usage:
1084 1091 >>>number = 19
1085 1092 >>>text = "python"
1086 1093 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1087 1094 """
1088 1095
1089 1096 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1090 1097 # modified (shorter) version of:
1091 1098 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1092 1099 # Skip Montanaro (skip@pobox.com).
1093 1100
1094 1101 def __getitem__(self, name):
1095 1102 frame = sys._getframe(1)
1096 1103 return eval(name, frame.f_globals, frame.f_locals)
1097 1104
1098 1105 EvalString = EvalDict # for backwards compatibility
1099 1106 #----------------------------------------------------------------------------
1100 1107 def qw(words,flat=0,sep=None,maxsplit=-1):
1101 1108 """Similar to Perl's qw() operator, but with some more options.
1102 1109
1103 1110 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1104 1111
1105 1112 words can also be a list itself, and with flat=1, the output will be
1106 1113 recursively flattened. Examples:
1107 1114
1108 1115 >>> qw('1 2')
1109 1116 ['1', '2']
1110 1117 >>> qw(['a b','1 2',['m n','p q']])
1111 1118 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1112 1119 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1113 1120 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1114 1121
1115 1122 if type(words) in StringTypes:
1116 1123 return [word.strip() for word in words.split(sep,maxsplit)
1117 1124 if word and not word.isspace() ]
1118 1125 if flat:
1119 1126 return flatten(map(qw,words,[1]*len(words)))
1120 1127 return map(qw,words)
1121 1128
1122 1129 #----------------------------------------------------------------------------
1123 1130 def qwflat(words,sep=None,maxsplit=-1):
1124 1131 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1125 1132 return qw(words,1,sep,maxsplit)
1126 1133
1127 1134 #----------------------------------------------------------------------------
1128 1135 def qw_lol(indata):
1129 1136 """qw_lol('a b') -> [['a','b']],
1130 1137 otherwise it's just a call to qw().
1131 1138
1132 1139 We need this to make sure the modules_some keys *always* end up as a
1133 1140 list of lists."""
1134 1141
1135 1142 if type(indata) in StringTypes:
1136 1143 return [qw(indata)]
1137 1144 else:
1138 1145 return qw(indata)
1139 1146
1140 1147 #-----------------------------------------------------------------------------
1141 1148 def list_strings(arg):
1142 1149 """Always return a list of strings, given a string or list of strings
1143 1150 as input."""
1144 1151
1145 1152 if type(arg) in StringTypes: return [arg]
1146 1153 else: return arg
1147 1154
1148 1155 #----------------------------------------------------------------------------
1149 1156 def grep(pat,list,case=1):
1150 1157 """Simple minded grep-like function.
1151 1158 grep(pat,list) returns occurrences of pat in list, None on failure.
1152 1159
1153 1160 It only does simple string matching, with no support for regexps. Use the
1154 1161 option case=0 for case-insensitive matching."""
1155 1162
1156 1163 # This is pretty crude. At least it should implement copying only references
1157 1164 # to the original data in case it's big. Now it copies the data for output.
1158 1165 out=[]
1159 1166 if case:
1160 1167 for term in list:
1161 1168 if term.find(pat)>-1: out.append(term)
1162 1169 else:
1163 1170 lpat=pat.lower()
1164 1171 for term in list:
1165 1172 if term.lower().find(lpat)>-1: out.append(term)
1166 1173
1167 1174 if len(out): return out
1168 1175 else: return None
1169 1176
1170 1177 #----------------------------------------------------------------------------
1171 1178 def dgrep(pat,*opts):
1172 1179 """Return grep() on dir()+dir(__builtins__).
1173 1180
1174 1181 A very common use of grep() when working interactively."""
1175 1182
1176 1183 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1177 1184
1178 1185 #----------------------------------------------------------------------------
1179 1186 def idgrep(pat):
1180 1187 """Case-insensitive dgrep()"""
1181 1188
1182 1189 return dgrep(pat,0)
1183 1190
1184 1191 #----------------------------------------------------------------------------
1185 1192 def igrep(pat,list):
1186 1193 """Synonym for case-insensitive grep."""
1187 1194
1188 1195 return grep(pat,list,case=0)
1189 1196
1190 1197 #----------------------------------------------------------------------------
1191 1198 def indent(str,nspaces=4,ntabs=0):
1192 1199 """Indent a string a given number of spaces or tabstops.
1193 1200
1194 1201 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1195 1202 """
1196 1203 if str is None:
1197 1204 return
1198 1205 ind = '\t'*ntabs+' '*nspaces
1199 1206 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1200 1207 if outstr.endswith(os.linesep+ind):
1201 1208 return outstr[:-len(ind)]
1202 1209 else:
1203 1210 return outstr
1204 1211
1205 1212 #-----------------------------------------------------------------------------
1206 1213 def native_line_ends(filename,backup=1):
1207 1214 """Convert (in-place) a file to line-ends native to the current OS.
1208 1215
1209 1216 If the optional backup argument is given as false, no backup of the
1210 1217 original file is left. """
1211 1218
1212 1219 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1213 1220
1214 1221 bak_filename = filename + backup_suffixes[os.name]
1215 1222
1216 1223 original = open(filename).read()
1217 1224 shutil.copy2(filename,bak_filename)
1218 1225 try:
1219 1226 new = open(filename,'wb')
1220 1227 new.write(os.linesep.join(original.splitlines()))
1221 1228 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1222 1229 new.close()
1223 1230 except:
1224 1231 os.rename(bak_filename,filename)
1225 1232 if not backup:
1226 1233 try:
1227 1234 os.remove(bak_filename)
1228 1235 except:
1229 1236 pass
1230 1237
1231 1238 #----------------------------------------------------------------------------
1232 1239 def get_pager_cmd(pager_cmd = None):
1233 1240 """Return a pager command.
1234 1241
1235 1242 Makes some attempts at finding an OS-correct one."""
1236 1243
1237 1244 if os.name == 'posix':
1238 1245 default_pager_cmd = 'less -r' # -r for color control sequences
1239 1246 elif os.name in ['nt','dos']:
1240 1247 default_pager_cmd = 'type'
1241 1248
1242 1249 if pager_cmd is None:
1243 1250 try:
1244 1251 pager_cmd = os.environ['PAGER']
1245 1252 except:
1246 1253 pager_cmd = default_pager_cmd
1247 1254 return pager_cmd
1248 1255
1249 1256 #-----------------------------------------------------------------------------
1250 1257 def get_pager_start(pager,start):
1251 1258 """Return the string for paging files with an offset.
1252 1259
1253 1260 This is the '+N' argument which less and more (under Unix) accept.
1254 1261 """
1255 1262
1256 1263 if pager in ['less','more']:
1257 1264 if start:
1258 1265 start_string = '+' + str(start)
1259 1266 else:
1260 1267 start_string = ''
1261 1268 else:
1262 1269 start_string = ''
1263 1270 return start_string
1264 1271
1265 1272 #----------------------------------------------------------------------------
1266 1273 if os.name == "nt":
1267 1274 import msvcrt
1268 1275 def page_more():
1269 1276 """ Smart pausing between pages
1270 1277
1271 1278 @return: True if need print more lines, False if quit
1272 1279 """
1273 1280 Term.cout.write('---Return to continue, q to quit--- ')
1274 1281 ans = msvcrt.getch()
1275 1282 if ans in ("q", "Q"):
1276 1283 result = False
1277 1284 else:
1278 1285 result = True
1279 1286 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1280 1287 return result
1281 1288 else:
1282 1289 def page_more():
1283 1290 ans = raw_input('---Return to continue, q to quit--- ')
1284 1291 if ans.lower().startswith('q'):
1285 1292 return False
1286 1293 else:
1287 1294 return True
1288 1295
1289 1296 esc_re = re.compile(r"(\x1b[^m]+m)")
1290 1297
1291 1298 def page_dumb(strng,start=0,screen_lines=25):
1292 1299 """Very dumb 'pager' in Python, for when nothing else works.
1293 1300
1294 1301 Only moves forward, same interface as page(), except for pager_cmd and
1295 1302 mode."""
1296 1303
1297 1304 out_ln = strng.splitlines()[start:]
1298 1305 screens = chop(out_ln,screen_lines-1)
1299 1306 if len(screens) == 1:
1300 1307 print >>Term.cout, os.linesep.join(screens[0])
1301 1308 else:
1302 1309 last_escape = ""
1303 1310 for scr in screens[0:-1]:
1304 1311 hunk = os.linesep.join(scr)
1305 1312 print >>Term.cout, last_escape + hunk
1306 1313 if not page_more():
1307 1314 return
1308 1315 esc_list = esc_re.findall(hunk)
1309 1316 if len(esc_list) > 0:
1310 1317 last_escape = esc_list[-1]
1311 1318 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1312 1319
1313 1320 #----------------------------------------------------------------------------
1314 1321 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1315 1322 """Print a string, piping through a pager after a certain length.
1316 1323
1317 1324 The screen_lines parameter specifies the number of *usable* lines of your
1318 1325 terminal screen (total lines minus lines you need to reserve to show other
1319 1326 information).
1320 1327
1321 1328 If you set screen_lines to a number <=0, page() will try to auto-determine
1322 1329 your screen size and will only use up to (screen_size+screen_lines) for
1323 1330 printing, paging after that. That is, if you want auto-detection but need
1324 1331 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1325 1332 auto-detection without any lines reserved simply use screen_lines = 0.
1326 1333
1327 1334 If a string won't fit in the allowed lines, it is sent through the
1328 1335 specified pager command. If none given, look for PAGER in the environment,
1329 1336 and ultimately default to less.
1330 1337
1331 1338 If no system pager works, the string is sent through a 'dumb pager'
1332 1339 written in python, very simplistic.
1333 1340 """
1334 1341
1335 1342 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1336 1343 TERM = os.environ.get('TERM','dumb')
1337 1344 if TERM in ['dumb','emacs'] and os.name != 'nt':
1338 1345 print strng
1339 1346 return
1340 1347 # chop off the topmost part of the string we don't want to see
1341 1348 str_lines = strng.split(os.linesep)[start:]
1342 1349 str_toprint = os.linesep.join(str_lines)
1343 1350 num_newlines = len(str_lines)
1344 1351 len_str = len(str_toprint)
1345 1352
1346 1353 # Dumb heuristics to guesstimate number of on-screen lines the string
1347 1354 # takes. Very basic, but good enough for docstrings in reasonable
1348 1355 # terminals. If someone later feels like refining it, it's not hard.
1349 1356 numlines = max(num_newlines,int(len_str/80)+1)
1350 1357
1351 1358 if os.name == "nt":
1352 1359 screen_lines_def = get_console_size(defaulty=25)[1]
1353 1360 else:
1354 1361 screen_lines_def = 25 # default value if we can't auto-determine
1355 1362
1356 1363 # auto-determine screen size
1357 1364 if screen_lines <= 0:
1358 1365 if TERM=='xterm':
1359 1366 try:
1360 1367 import curses
1361 1368 if hasattr(curses,'initscr'):
1362 1369 use_curses = 1
1363 1370 else:
1364 1371 use_curses = 0
1365 1372 except ImportError:
1366 1373 use_curses = 0
1367 1374 else:
1368 1375 # curses causes problems on many terminals other than xterm.
1369 1376 use_curses = 0
1370 1377 if use_curses:
1371 1378 scr = curses.initscr()
1372 1379 screen_lines_real,screen_cols = scr.getmaxyx()
1373 1380 curses.endwin()
1374 1381 screen_lines += screen_lines_real
1375 1382 #print '***Screen size:',screen_lines_real,'lines x',\
1376 1383 #screen_cols,'columns.' # dbg
1377 1384 else:
1378 1385 screen_lines += screen_lines_def
1379 1386
1380 1387 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1381 1388 if numlines <= screen_lines :
1382 1389 #print '*** normal print' # dbg
1383 1390 print >>Term.cout, str_toprint
1384 1391 else:
1385 1392 # Try to open pager and default to internal one if that fails.
1386 1393 # All failure modes are tagged as 'retval=1', to match the return
1387 1394 # value of a failed system command. If any intermediate attempt
1388 1395 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1389 1396 pager_cmd = get_pager_cmd(pager_cmd)
1390 1397 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1391 1398 if os.name == 'nt':
1392 1399 if pager_cmd.startswith('type'):
1393 1400 # The default WinXP 'type' command is failing on complex strings.
1394 1401 retval = 1
1395 1402 else:
1396 1403 tmpname = tempfile.mktemp('.txt')
1397 1404 tmpfile = file(tmpname,'wt')
1398 1405 tmpfile.write(strng)
1399 1406 tmpfile.close()
1400 1407 cmd = "%s < %s" % (pager_cmd,tmpname)
1401 1408 if os.system(cmd):
1402 1409 retval = 1
1403 1410 else:
1404 1411 retval = None
1405 1412 os.remove(tmpname)
1406 1413 else:
1407 1414 try:
1408 1415 retval = None
1409 1416 # if I use popen4, things hang. No idea why.
1410 1417 #pager,shell_out = os.popen4(pager_cmd)
1411 1418 pager = os.popen(pager_cmd,'w')
1412 1419 pager.write(strng)
1413 1420 pager.close()
1414 1421 retval = pager.close() # success returns None
1415 1422 except IOError,msg: # broken pipe when user quits
1416 1423 if msg.args == (32,'Broken pipe'):
1417 1424 retval = None
1418 1425 else:
1419 1426 retval = 1
1420 1427 except OSError:
1421 1428 # Other strange problems, sometimes seen in Win2k/cygwin
1422 1429 retval = 1
1423 1430 if retval is not None:
1424 1431 page_dumb(strng,screen_lines=screen_lines)
1425 1432
1426 1433 #----------------------------------------------------------------------------
1427 1434 def page_file(fname,start = 0, pager_cmd = None):
1428 1435 """Page a file, using an optional pager command and starting line.
1429 1436 """
1430 1437
1431 1438 pager_cmd = get_pager_cmd(pager_cmd)
1432 1439 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1433 1440
1434 1441 try:
1435 1442 if os.environ['TERM'] in ['emacs','dumb']:
1436 1443 raise EnvironmentError
1437 1444 xsys(pager_cmd + ' ' + fname)
1438 1445 except:
1439 1446 try:
1440 1447 if start > 0:
1441 1448 start -= 1
1442 1449 page(open(fname).read(),start)
1443 1450 except:
1444 1451 print 'Unable to show file',`fname`
1445 1452
1446 1453 #----------------------------------------------------------------------------
1447 1454 def snip_print(str,width = 75,print_full = 0,header = ''):
1448 1455 """Print a string snipping the midsection to fit in width.
1449 1456
1450 1457 print_full: mode control:
1451 1458 - 0: only snip long strings
1452 1459 - 1: send to page() directly.
1453 1460 - 2: snip long strings and ask for full length viewing with page()
1454 1461 Return 1 if snipping was necessary, 0 otherwise."""
1455 1462
1456 1463 if print_full == 1:
1457 1464 page(header+str)
1458 1465 return 0
1459 1466
1460 1467 print header,
1461 1468 if len(str) < width:
1462 1469 print str
1463 1470 snip = 0
1464 1471 else:
1465 1472 whalf = int((width -5)/2)
1466 1473 print str[:whalf] + ' <...> ' + str[-whalf:]
1467 1474 snip = 1
1468 1475 if snip and print_full == 2:
1469 1476 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1470 1477 page(str)
1471 1478 return snip
1472 1479
1473 1480 #****************************************************************************
1474 1481 # lists, dicts and structures
1475 1482
1476 1483 def belong(candidates,checklist):
1477 1484 """Check whether a list of items appear in a given list of options.
1478 1485
1479 1486 Returns a list of 1 and 0, one for each candidate given."""
1480 1487
1481 1488 return [x in checklist for x in candidates]
1482 1489
1483 1490 #----------------------------------------------------------------------------
1484 1491 def uniq_stable(elems):
1485 1492 """uniq_stable(elems) -> list
1486 1493
1487 1494 Return from an iterable, a list of all the unique elements in the input,
1488 1495 but maintaining the order in which they first appear.
1489 1496
1490 1497 A naive solution to this problem which just makes a dictionary with the
1491 1498 elements as keys fails to respect the stability condition, since
1492 1499 dictionaries are unsorted by nature.
1493 1500
1494 1501 Note: All elements in the input must be valid dictionary keys for this
1495 1502 routine to work, as it internally uses a dictionary for efficiency
1496 1503 reasons."""
1497 1504
1498 1505 unique = []
1499 1506 unique_dict = {}
1500 1507 for nn in elems:
1501 1508 if nn not in unique_dict:
1502 1509 unique.append(nn)
1503 1510 unique_dict[nn] = None
1504 1511 return unique
1505 1512
1506 1513 #----------------------------------------------------------------------------
1507 1514 class NLprinter:
1508 1515 """Print an arbitrarily nested list, indicating index numbers.
1509 1516
1510 1517 An instance of this class called nlprint is available and callable as a
1511 1518 function.
1512 1519
1513 1520 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1514 1521 and using 'sep' to separate the index from the value. """
1515 1522
1516 1523 def __init__(self):
1517 1524 self.depth = 0
1518 1525
1519 1526 def __call__(self,lst,pos='',**kw):
1520 1527 """Prints the nested list numbering levels."""
1521 1528 kw.setdefault('indent',' ')
1522 1529 kw.setdefault('sep',': ')
1523 1530 kw.setdefault('start',0)
1524 1531 kw.setdefault('stop',len(lst))
1525 1532 # we need to remove start and stop from kw so they don't propagate
1526 1533 # into a recursive call for a nested list.
1527 1534 start = kw['start']; del kw['start']
1528 1535 stop = kw['stop']; del kw['stop']
1529 1536 if self.depth == 0 and 'header' in kw.keys():
1530 1537 print kw['header']
1531 1538
1532 1539 for idx in range(start,stop):
1533 1540 elem = lst[idx]
1534 1541 if type(elem)==type([]):
1535 1542 self.depth += 1
1536 1543 self.__call__(elem,itpl('$pos$idx,'),**kw)
1537 1544 self.depth -= 1
1538 1545 else:
1539 1546 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1540 1547
1541 1548 nlprint = NLprinter()
1542 1549 #----------------------------------------------------------------------------
1543 1550 def all_belong(candidates,checklist):
1544 1551 """Check whether a list of items ALL appear in a given list of options.
1545 1552
1546 1553 Returns a single 1 or 0 value."""
1547 1554
1548 1555 return 1-(0 in [x in checklist for x in candidates])
1549 1556
1550 1557 #----------------------------------------------------------------------------
1551 1558 def sort_compare(lst1,lst2,inplace = 1):
1552 1559 """Sort and compare two lists.
1553 1560
1554 1561 By default it does it in place, thus modifying the lists. Use inplace = 0
1555 1562 to avoid that (at the cost of temporary copy creation)."""
1556 1563 if not inplace:
1557 1564 lst1 = lst1[:]
1558 1565 lst2 = lst2[:]
1559 1566 lst1.sort(); lst2.sort()
1560 1567 return lst1 == lst2
1561 1568
1562 1569 #----------------------------------------------------------------------------
1563 1570 def mkdict(**kwargs):
1564 1571 """Return a dict from a keyword list.
1565 1572
1566 1573 It's just syntactic sugar for making ditcionary creation more convenient:
1567 1574 # the standard way
1568 1575 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1569 1576 # a cleaner way
1570 1577 >>>data = dict(red=1, green=2, blue=3)
1571 1578
1572 1579 If you need more than this, look at the Struct() class."""
1573 1580
1574 1581 return kwargs
1575 1582
1576 1583 #----------------------------------------------------------------------------
1577 1584 def list2dict(lst):
1578 1585 """Takes a list of (key,value) pairs and turns it into a dict."""
1579 1586
1580 1587 dic = {}
1581 1588 for k,v in lst: dic[k] = v
1582 1589 return dic
1583 1590
1584 1591 #----------------------------------------------------------------------------
1585 1592 def list2dict2(lst,default=''):
1586 1593 """Takes a list and turns it into a dict.
1587 1594 Much slower than list2dict, but more versatile. This version can take
1588 1595 lists with sublists of arbitrary length (including sclars)."""
1589 1596
1590 1597 dic = {}
1591 1598 for elem in lst:
1592 1599 if type(elem) in (types.ListType,types.TupleType):
1593 1600 size = len(elem)
1594 1601 if size == 0:
1595 1602 pass
1596 1603 elif size == 1:
1597 1604 dic[elem] = default
1598 1605 else:
1599 1606 k,v = elem[0], elem[1:]
1600 1607 if len(v) == 1: v = v[0]
1601 1608 dic[k] = v
1602 1609 else:
1603 1610 dic[elem] = default
1604 1611 return dic
1605 1612
1606 1613 #----------------------------------------------------------------------------
1607 1614 def flatten(seq):
1608 1615 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1609 1616
1610 1617 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1611 1618
1612 1619 # if the x=0 isn't made, a *global* variable x is left over after calling
1613 1620 # this function, with the value of the last element in the return
1614 1621 # list. This does seem like a bug big time to me.
1615 1622
1616 1623 # the problem is fixed with the x=0, which seems to force the creation of
1617 1624 # a local name
1618 1625
1619 1626 x = 0
1620 1627 return [x for subseq in seq for x in subseq]
1621 1628
1622 1629 #----------------------------------------------------------------------------
1623 1630 def get_slice(seq,start=0,stop=None,step=1):
1624 1631 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1625 1632 if stop == None:
1626 1633 stop = len(seq)
1627 1634 item = lambda i: seq[i]
1628 1635 return map(item,xrange(start,stop,step))
1629 1636
1630 1637 #----------------------------------------------------------------------------
1631 1638 def chop(seq,size):
1632 1639 """Chop a sequence into chunks of the given size."""
1633 1640 chunk = lambda i: seq[i:i+size]
1634 1641 return map(chunk,xrange(0,len(seq),size))
1635 1642
1636 1643 #----------------------------------------------------------------------------
1637 1644 def with(object, **args):
1638 1645 """Set multiple attributes for an object, similar to Pascal's with.
1639 1646
1640 1647 Example:
1641 1648 with(jim,
1642 1649 born = 1960,
1643 1650 haircolour = 'Brown',
1644 1651 eyecolour = 'Green')
1645 1652
1646 1653 Credit: Greg Ewing, in
1647 1654 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1648 1655
1649 1656 object.__dict__.update(args)
1650 1657
1651 1658 #----------------------------------------------------------------------------
1652 1659 def setattr_list(obj,alist,nspace = None):
1653 1660 """Set a list of attributes for an object taken from a namespace.
1654 1661
1655 1662 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1656 1663 alist with their values taken from nspace, which must be a dict (something
1657 1664 like locals() will often do) If nspace isn't given, locals() of the
1658 1665 *caller* is used, so in most cases you can omit it.
1659 1666
1660 1667 Note that alist can be given as a string, which will be automatically
1661 1668 split into a list on whitespace. If given as a list, it must be a list of
1662 1669 *strings* (the variable names themselves), not of variables."""
1663 1670
1664 1671 # this grabs the local variables from the *previous* call frame -- that is
1665 1672 # the locals from the function that called setattr_list().
1666 1673 # - snipped from weave.inline()
1667 1674 if nspace is None:
1668 1675 call_frame = sys._getframe().f_back
1669 1676 nspace = call_frame.f_locals
1670 1677
1671 1678 if type(alist) in StringTypes:
1672 1679 alist = alist.split()
1673 1680 for attr in alist:
1674 1681 val = eval(attr,nspace)
1675 1682 setattr(obj,attr,val)
1676 1683
1677 1684 #----------------------------------------------------------------------------
1678 1685 def getattr_list(obj,alist,*args):
1679 1686 """getattr_list(obj,alist[, default]) -> attribute list.
1680 1687
1681 1688 Get a list of named attributes for an object. When a default argument is
1682 1689 given, it is returned when the attribute doesn't exist; without it, an
1683 1690 exception is raised in that case.
1684 1691
1685 1692 Note that alist can be given as a string, which will be automatically
1686 1693 split into a list on whitespace. If given as a list, it must be a list of
1687 1694 *strings* (the variable names themselves), not of variables."""
1688 1695
1689 1696 if type(alist) in StringTypes:
1690 1697 alist = alist.split()
1691 1698 if args:
1692 1699 if len(args)==1:
1693 1700 default = args[0]
1694 1701 return map(lambda attr: getattr(obj,attr,default),alist)
1695 1702 else:
1696 1703 raise ValueError,'getattr_list() takes only one optional argument'
1697 1704 else:
1698 1705 return map(lambda attr: getattr(obj,attr),alist)
1699 1706
1700 1707 #----------------------------------------------------------------------------
1701 1708 def map_method(method,object_list,*argseq,**kw):
1702 1709 """map_method(method,object_list,*args,**kw) -> list
1703 1710
1704 1711 Return a list of the results of applying the methods to the items of the
1705 1712 argument sequence(s). If more than one sequence is given, the method is
1706 1713 called with an argument list consisting of the corresponding item of each
1707 1714 sequence. All sequences must be of the same length.
1708 1715
1709 1716 Keyword arguments are passed verbatim to all objects called.
1710 1717
1711 1718 This is Python code, so it's not nearly as fast as the builtin map()."""
1712 1719
1713 1720 out_list = []
1714 1721 idx = 0
1715 1722 for object in object_list:
1716 1723 try:
1717 1724 handler = getattr(object, method)
1718 1725 except AttributeError:
1719 1726 out_list.append(None)
1720 1727 else:
1721 1728 if argseq:
1722 1729 args = map(lambda lst:lst[idx],argseq)
1723 1730 #print 'ob',object,'hand',handler,'ar',args # dbg
1724 1731 out_list.append(handler(args,**kw))
1725 1732 else:
1726 1733 out_list.append(handler(**kw))
1727 1734 idx += 1
1728 1735 return out_list
1729 1736
1730 1737 #----------------------------------------------------------------------------
1731 1738 def import_fail_info(mod_name,fns=None):
1732 1739 """Inform load failure for a module."""
1733 1740
1734 1741 if fns == None:
1735 1742 warn("Loading of %s failed.\n" % (mod_name,))
1736 1743 else:
1737 1744 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1738 1745
1739 1746 #----------------------------------------------------------------------------
1740 1747 # Proposed popitem() extension, written as a method
1741 1748
1742 1749 class NotGiven: pass
1743 1750
1744 1751 def popkey(dct,key,default=NotGiven):
1745 1752 """Return dct[key] and delete dct[key].
1746 1753
1747 1754 If default is given, return it if dct[key] doesn't exist, otherwise raise
1748 1755 KeyError. """
1749 1756
1750 1757 try:
1751 1758 val = dct[key]
1752 1759 except KeyError:
1753 1760 if default is NotGiven:
1754 1761 raise
1755 1762 else:
1756 1763 return default
1757 1764 else:
1758 1765 del dct[key]
1759 1766 return val
1760 1767 #*************************** end of file <genutils.py> **********************
1761 1768
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now