##// END OF EJS Templates
- More fixes for doctest support....
fperez -
Show More

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

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