##// END OF EJS Templates
prompt and set_term_title now include drive letter and / characters on win32
vivainio -
Show More

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

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