##// END OF EJS Templates
Fix autocall misfiring on print for python 2.6 and newer. Closes Bug #414967...
Fernando Perez -
Show More
@@ -1,3618 +1,3625 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008-2009 The IPython Development Team
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 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import __builtin__
19 import __future__
19 20 import bdb
20 21 import inspect
21 22 import os
22 23 import sys
23 24 import shutil
24 25 import re
25 26 import time
26 27 import textwrap
27 28 import types
28 29 from cStringIO import StringIO
29 30 from getopt import getopt,GetoptError
30 31 from pprint import pformat
31 32
32 33 # cProfile was added in Python2.5
33 34 try:
34 35 import cProfile as profile
35 36 import pstats
36 37 except ImportError:
37 38 # profile isn't bundled by default in Debian for license reasons
38 39 try:
39 40 import profile,pstats
40 41 except ImportError:
41 42 profile = pstats = None
42 43
43 44 import IPython
44 45 from IPython.core import debugger, oinspect
45 46 from IPython.core.error import TryNext
46 47 from IPython.core.error import UsageError
47 48 from IPython.core.fakemodule import FakeModule
48 49 from IPython.core.macro import Macro
49 50 from IPython.core.page import page
50 51 from IPython.core.prefilter import ESC_MAGIC
51 52 from IPython.lib.pylabtools import mpl_runner
52 53 from IPython.lib.inputhook import enable_gui
53 54 from IPython.external.Itpl import itpl, printpl
54 55 from IPython.testing import decorators as testdec
55 56 from IPython.utils.io import Term, file_read, nlprint
56 57 from IPython.utils.path import get_py_filename
57 58 from IPython.utils.process import arg_split, abbrev_cwd
58 59 from IPython.utils.terminal import set_term_title
59 60 from IPython.utils.text import LSString, SList, StringTypes
60 61 from IPython.utils.timing import clock, clock2
61 62 from IPython.utils.warn import warn, error
62 63 from IPython.utils.ipstruct import Struct
63 64 import IPython.utils.generics
64 65
65 66 #-----------------------------------------------------------------------------
66 67 # Utility functions
67 68 #-----------------------------------------------------------------------------
68 69
69 70 def on_off(tag):
70 71 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 72 return ['OFF','ON'][tag]
72 73
73 74 class Bunch: pass
74 75
75 76 def compress_dhist(dh):
76 77 head, tail = dh[:-10], dh[-10:]
77 78
78 79 newhead = []
79 80 done = set()
80 81 for h in head:
81 82 if h in done:
82 83 continue
83 84 newhead.append(h)
84 85 done.add(h)
85 86
86 87 return newhead + tail
87 88
88 89
89 90 #***************************************************************************
90 91 # Main class implementing Magic functionality
91 92
92 93 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
93 94 # on construction of the main InteractiveShell object. Something odd is going
94 95 # on with super() calls, Component and the MRO... For now leave it as-is, but
95 96 # eventually this needs to be clarified.
96 97 # BG: This is because InteractiveShell inherits from this, but is itself a
97 98 # Component. This messes up the MRO in some way. The fix is that we need to
98 99 # make Magic a component that InteractiveShell does not subclass.
99 100
100 101 class Magic:
101 102 """Magic functions for InteractiveShell.
102 103
103 104 Shell functions which can be reached as %function_name. All magic
104 105 functions should accept a string, which they can parse for their own
105 106 needs. This can make some functions easier to type, eg `%cd ../`
106 107 vs. `%cd("../")`
107 108
108 109 ALL definitions MUST begin with the prefix magic_. The user won't need it
109 110 at the command line, but it is is needed in the definition. """
110 111
111 112 # class globals
112 113 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
113 114 'Automagic is ON, % prefix NOT needed for magic functions.']
114 115
115 116 #......................................................................
116 117 # some utility functions
117 118
118 119 def __init__(self,shell):
119 120
120 121 self.options_table = {}
121 122 if profile is None:
122 123 self.magic_prun = self.profile_missing_notice
123 124 self.shell = shell
124 125
125 126 # namespace for holding state we may need
126 127 self._magic_state = Bunch()
127 128
128 129 def profile_missing_notice(self, *args, **kwargs):
129 130 error("""\
130 131 The profile module could not be found. It has been removed from the standard
131 132 python packages because of its non-free license. To use profiling, install the
132 133 python-profiler package from non-free.""")
133 134
134 135 def default_option(self,fn,optstr):
135 136 """Make an entry in the options_table for fn, with value optstr"""
136 137
137 138 if fn not in self.lsmagic():
138 139 error("%s is not a magic function" % fn)
139 140 self.options_table[fn] = optstr
140 141
141 142 def lsmagic(self):
142 143 """Return a list of currently available magic functions.
143 144
144 145 Gives a list of the bare names after mangling (['ls','cd', ...], not
145 146 ['magic_ls','magic_cd',...]"""
146 147
147 148 # FIXME. This needs a cleanup, in the way the magics list is built.
148 149
149 150 # magics in class definition
150 151 class_magic = lambda fn: fn.startswith('magic_') and \
151 152 callable(Magic.__dict__[fn])
152 153 # in instance namespace (run-time user additions)
153 154 inst_magic = lambda fn: fn.startswith('magic_') and \
154 155 callable(self.__dict__[fn])
155 156 # and bound magics by user (so they can access self):
156 157 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
157 158 callable(self.__class__.__dict__[fn])
158 159 magics = filter(class_magic,Magic.__dict__.keys()) + \
159 160 filter(inst_magic,self.__dict__.keys()) + \
160 161 filter(inst_bound_magic,self.__class__.__dict__.keys())
161 162 out = []
162 163 for fn in set(magics):
163 164 out.append(fn.replace('magic_','',1))
164 165 out.sort()
165 166 return out
166 167
167 168 def extract_input_slices(self,slices,raw=False):
168 169 """Return as a string a set of input history slices.
169 170
170 171 Inputs:
171 172
172 173 - slices: the set of slices is given as a list of strings (like
173 174 ['1','4:8','9'], since this function is for use by magic functions
174 175 which get their arguments as strings.
175 176
176 177 Optional inputs:
177 178
178 179 - raw(False): by default, the processed input is used. If this is
179 180 true, the raw input history is used instead.
180 181
181 182 Note that slices can be called with two notations:
182 183
183 184 N:M -> standard python form, means including items N...(M-1).
184 185
185 186 N-M -> include items N..M (closed endpoint)."""
186 187
187 188 if raw:
188 189 hist = self.shell.input_hist_raw
189 190 else:
190 191 hist = self.shell.input_hist
191 192
192 193 cmds = []
193 194 for chunk in slices:
194 195 if ':' in chunk:
195 196 ini,fin = map(int,chunk.split(':'))
196 197 elif '-' in chunk:
197 198 ini,fin = map(int,chunk.split('-'))
198 199 fin += 1
199 200 else:
200 201 ini = int(chunk)
201 202 fin = ini+1
202 203 cmds.append(hist[ini:fin])
203 204 return cmds
204 205
205 206 def _ofind(self, oname, namespaces=None):
206 207 """Find an object in the available namespaces.
207 208
208 209 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
209 210
210 211 Has special code to detect magic functions.
211 212 """
212
213 213 oname = oname.strip()
214
215 214 alias_ns = None
216 215 if namespaces is None:
217 216 # Namespaces to search in:
218 217 # Put them in a list. The order is important so that we
219 218 # find things in the same order that Python finds them.
220 219 namespaces = [ ('Interactive', self.shell.user_ns),
221 220 ('IPython internal', self.shell.internal_ns),
222 221 ('Python builtin', __builtin__.__dict__),
223 222 ('Alias', self.shell.alias_manager.alias_table),
224 223 ]
225 224 alias_ns = self.shell.alias_manager.alias_table
226 225
227 226 # initialize results to 'null'
228 found = 0; obj = None; ospace = None; ds = None;
229 ismagic = 0; isalias = 0; parent = None
227 found = False; obj = None; ospace = None; ds = None;
228 ismagic = False; isalias = False; parent = None
229
230 # We need to special-case 'print', which as of python2.6 registers as a
231 # function but should only be treated as one if print_function was
232 # loaded with a future import. In this case, just bail.
233 if (oname == 'print' and not (self.shell.compile.compiler.flags &
234 __future__.CO_FUTURE_PRINT_FUNCTION)):
235 return {'found':found, 'obj':obj, 'namespace':ospace,
236 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
230 237
231 238 # Look for the given name by splitting it in parts. If the head is
232 239 # found, then we look for all the remaining parts as members, and only
233 240 # declare success if we can find them all.
234 241 oname_parts = oname.split('.')
235 242 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
236 243 for nsname,ns in namespaces:
237 244 try:
238 245 obj = ns[oname_head]
239 246 except KeyError:
240 247 continue
241 248 else:
242 249 #print 'oname_rest:', oname_rest # dbg
243 250 for part in oname_rest:
244 251 try:
245 252 parent = obj
246 253 obj = getattr(obj,part)
247 254 except:
248 255 # Blanket except b/c some badly implemented objects
249 256 # allow __getattr__ to raise exceptions other than
250 257 # AttributeError, which then crashes IPython.
251 258 break
252 259 else:
253 260 # If we finish the for loop (no break), we got all members
254 found = 1
261 found = True
255 262 ospace = nsname
256 263 if ns == alias_ns:
257 isalias = 1
264 isalias = True
258 265 break # namespace loop
259 266
260 267 # Try to see if it's magic
261 268 if not found:
262 269 if oname.startswith(ESC_MAGIC):
263 270 oname = oname[1:]
264 271 obj = getattr(self,'magic_'+oname,None)
265 272 if obj is not None:
266 found = 1
273 found = True
267 274 ospace = 'IPython internal'
268 ismagic = 1
275 ismagic = True
269 276
270 277 # Last try: special-case some literals like '', [], {}, etc:
271 278 if not found and oname_head in ["''",'""','[]','{}','()']:
272 279 obj = eval(oname_head)
273 found = 1
280 found = True
274 281 ospace = 'Interactive'
275 282
276 283 return {'found':found, 'obj':obj, 'namespace':ospace,
277 284 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
278 285
279 286 def arg_err(self,func):
280 287 """Print docstring if incorrect arguments were passed"""
281 288 print 'Error in arguments:'
282 289 print oinspect.getdoc(func)
283 290
284 291 def format_latex(self,strng):
285 292 """Format a string for latex inclusion."""
286 293
287 294 # Characters that need to be escaped for latex:
288 295 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
289 296 # Magic command names as headers:
290 297 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
291 298 re.MULTILINE)
292 299 # Magic commands
293 300 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
294 301 re.MULTILINE)
295 302 # Paragraph continue
296 303 par_re = re.compile(r'\\$',re.MULTILINE)
297 304
298 305 # The "\n" symbol
299 306 newline_re = re.compile(r'\\n')
300 307
301 308 # Now build the string for output:
302 309 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
303 310 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
304 311 strng)
305 312 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
306 313 strng = par_re.sub(r'\\\\',strng)
307 314 strng = escape_re.sub(r'\\\1',strng)
308 315 strng = newline_re.sub(r'\\textbackslash{}n',strng)
309 316 return strng
310 317
311 318 def format_screen(self,strng):
312 319 """Format a string for screen printing.
313 320
314 321 This removes some latex-type format codes."""
315 322 # Paragraph continue
316 323 par_re = re.compile(r'\\$',re.MULTILINE)
317 324 strng = par_re.sub('',strng)
318 325 return strng
319 326
320 327 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
321 328 """Parse options passed to an argument string.
322 329
323 330 The interface is similar to that of getopt(), but it returns back a
324 331 Struct with the options as keys and the stripped argument string still
325 332 as a string.
326 333
327 334 arg_str is quoted as a true sys.argv vector by using shlex.split.
328 335 This allows us to easily expand variables, glob files, quote
329 336 arguments, etc.
330 337
331 338 Options:
332 339 -mode: default 'string'. If given as 'list', the argument string is
333 340 returned as a list (split on whitespace) instead of a string.
334 341
335 342 -list_all: put all option values in lists. Normally only options
336 343 appearing more than once are put in a list.
337 344
338 345 -posix (True): whether to split the input line in POSIX mode or not,
339 346 as per the conventions outlined in the shlex module from the
340 347 standard library."""
341 348
342 349 # inject default options at the beginning of the input line
343 350 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
344 351 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
345 352
346 353 mode = kw.get('mode','string')
347 354 if mode not in ['string','list']:
348 355 raise ValueError,'incorrect mode given: %s' % mode
349 356 # Get options
350 357 list_all = kw.get('list_all',0)
351 358 posix = kw.get('posix', os.name == 'posix')
352 359
353 360 # Check if we have more than one argument to warrant extra processing:
354 361 odict = {} # Dictionary with options
355 362 args = arg_str.split()
356 363 if len(args) >= 1:
357 364 # If the list of inputs only has 0 or 1 thing in it, there's no
358 365 # need to look for options
359 366 argv = arg_split(arg_str,posix)
360 367 # Do regular option processing
361 368 try:
362 369 opts,args = getopt(argv,opt_str,*long_opts)
363 370 except GetoptError,e:
364 371 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
365 372 " ".join(long_opts)))
366 373 for o,a in opts:
367 374 if o.startswith('--'):
368 375 o = o[2:]
369 376 else:
370 377 o = o[1:]
371 378 try:
372 379 odict[o].append(a)
373 380 except AttributeError:
374 381 odict[o] = [odict[o],a]
375 382 except KeyError:
376 383 if list_all:
377 384 odict[o] = [a]
378 385 else:
379 386 odict[o] = a
380 387
381 388 # Prepare opts,args for return
382 389 opts = Struct(odict)
383 390 if mode == 'string':
384 391 args = ' '.join(args)
385 392
386 393 return opts,args
387 394
388 395 #......................................................................
389 396 # And now the actual magic functions
390 397
391 398 # Functions for IPython shell work (vars,funcs, config, etc)
392 399 def magic_lsmagic(self, parameter_s = ''):
393 400 """List currently available magic functions."""
394 401 mesc = ESC_MAGIC
395 402 print 'Available magic functions:\n'+mesc+\
396 403 (' '+mesc).join(self.lsmagic())
397 404 print '\n' + Magic.auto_status[self.shell.automagic]
398 405 return None
399 406
400 407 def magic_magic(self, parameter_s = ''):
401 408 """Print information about the magic function system.
402 409
403 410 Supported formats: -latex, -brief, -rest
404 411 """
405 412
406 413 mode = ''
407 414 try:
408 415 if parameter_s.split()[0] == '-latex':
409 416 mode = 'latex'
410 417 if parameter_s.split()[0] == '-brief':
411 418 mode = 'brief'
412 419 if parameter_s.split()[0] == '-rest':
413 420 mode = 'rest'
414 421 rest_docs = []
415 422 except:
416 423 pass
417 424
418 425 magic_docs = []
419 426 for fname in self.lsmagic():
420 427 mname = 'magic_' + fname
421 428 for space in (Magic,self,self.__class__):
422 429 try:
423 430 fn = space.__dict__[mname]
424 431 except KeyError:
425 432 pass
426 433 else:
427 434 break
428 435 if mode == 'brief':
429 436 # only first line
430 437 if fn.__doc__:
431 438 fndoc = fn.__doc__.split('\n',1)[0]
432 439 else:
433 440 fndoc = 'No documentation'
434 441 else:
435 442 if fn.__doc__:
436 443 fndoc = fn.__doc__.rstrip()
437 444 else:
438 445 fndoc = 'No documentation'
439 446
440 447
441 448 if mode == 'rest':
442 449 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
443 450 fname,fndoc))
444 451
445 452 else:
446 453 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
447 454 fname,fndoc))
448 455
449 456 magic_docs = ''.join(magic_docs)
450 457
451 458 if mode == 'rest':
452 459 return "".join(rest_docs)
453 460
454 461 if mode == 'latex':
455 462 print self.format_latex(magic_docs)
456 463 return
457 464 else:
458 465 magic_docs = self.format_screen(magic_docs)
459 466 if mode == 'brief':
460 467 return magic_docs
461 468
462 469 outmsg = """
463 470 IPython's 'magic' functions
464 471 ===========================
465 472
466 473 The magic function system provides a series of functions which allow you to
467 474 control the behavior of IPython itself, plus a lot of system-type
468 475 features. All these functions are prefixed with a % character, but parameters
469 476 are given without parentheses or quotes.
470 477
471 478 NOTE: If you have 'automagic' enabled (via the command line option or with the
472 479 %automagic function), you don't need to type in the % explicitly. By default,
473 480 IPython ships with automagic on, so you should only rarely need the % escape.
474 481
475 482 Example: typing '%cd mydir' (without the quotes) changes you working directory
476 483 to 'mydir', if it exists.
477 484
478 485 You can define your own magic functions to extend the system. See the supplied
479 486 ipythonrc and example-magic.py files for details (in your ipython
480 487 configuration directory, typically $HOME/.ipython/).
481 488
482 489 You can also define your own aliased names for magic functions. In your
483 490 ipythonrc file, placing a line like:
484 491
485 492 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
486 493
487 494 will define %pf as a new name for %profile.
488 495
489 496 You can also call magics in code using the magic() function, which IPython
490 497 automatically adds to the builtin namespace. Type 'magic?' for details.
491 498
492 499 For a list of the available magic functions, use %lsmagic. For a description
493 500 of any of them, type %magic_name?, e.g. '%cd?'.
494 501
495 502 Currently the magic system has the following functions:\n"""
496 503
497 504 mesc = ESC_MAGIC
498 505 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
499 506 "\n\n%s%s\n\n%s" % (outmsg,
500 507 magic_docs,mesc,mesc,
501 508 (' '+mesc).join(self.lsmagic()),
502 509 Magic.auto_status[self.shell.automagic] ) )
503 510
504 511 page(outmsg,screen_lines=self.shell.usable_screen_length)
505 512
506 513
507 514 def magic_autoindent(self, parameter_s = ''):
508 515 """Toggle autoindent on/off (if available)."""
509 516
510 517 self.shell.set_autoindent()
511 518 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
512 519
513 520
514 521 def magic_automagic(self, parameter_s = ''):
515 522 """Make magic functions callable without having to type the initial %.
516 523
517 524 Without argumentsl toggles on/off (when off, you must call it as
518 525 %automagic, of course). With arguments it sets the value, and you can
519 526 use any of (case insensitive):
520 527
521 528 - on,1,True: to activate
522 529
523 530 - off,0,False: to deactivate.
524 531
525 532 Note that magic functions have lowest priority, so if there's a
526 533 variable whose name collides with that of a magic fn, automagic won't
527 534 work for that function (you get the variable instead). However, if you
528 535 delete the variable (del var), the previously shadowed magic function
529 536 becomes visible to automagic again."""
530 537
531 538 arg = parameter_s.lower()
532 539 if parameter_s in ('on','1','true'):
533 540 self.shell.automagic = True
534 541 elif parameter_s in ('off','0','false'):
535 542 self.shell.automagic = False
536 543 else:
537 544 self.shell.automagic = not self.shell.automagic
538 545 print '\n' + Magic.auto_status[self.shell.automagic]
539 546
540 547 @testdec.skip_doctest
541 548 def magic_autocall(self, parameter_s = ''):
542 549 """Make functions callable without having to type parentheses.
543 550
544 551 Usage:
545 552
546 553 %autocall [mode]
547 554
548 555 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
549 556 value is toggled on and off (remembering the previous state).
550 557
551 558 In more detail, these values mean:
552 559
553 560 0 -> fully disabled
554 561
555 562 1 -> active, but do not apply if there are no arguments on the line.
556 563
557 564 In this mode, you get:
558 565
559 566 In [1]: callable
560 567 Out[1]: <built-in function callable>
561 568
562 569 In [2]: callable 'hello'
563 570 ------> callable('hello')
564 571 Out[2]: False
565 572
566 573 2 -> Active always. Even if no arguments are present, the callable
567 574 object is called:
568 575
569 576 In [2]: float
570 577 ------> float()
571 578 Out[2]: 0.0
572 579
573 580 Note that even with autocall off, you can still use '/' at the start of
574 581 a line to treat the first argument on the command line as a function
575 582 and add parentheses to it:
576 583
577 584 In [8]: /str 43
578 585 ------> str(43)
579 586 Out[8]: '43'
580 587
581 588 # all-random (note for auto-testing)
582 589 """
583 590
584 591 if parameter_s:
585 592 arg = int(parameter_s)
586 593 else:
587 594 arg = 'toggle'
588 595
589 596 if not arg in (0,1,2,'toggle'):
590 597 error('Valid modes: (0->Off, 1->Smart, 2->Full')
591 598 return
592 599
593 600 if arg in (0,1,2):
594 601 self.shell.autocall = arg
595 602 else: # toggle
596 603 if self.shell.autocall:
597 604 self._magic_state.autocall_save = self.shell.autocall
598 605 self.shell.autocall = 0
599 606 else:
600 607 try:
601 608 self.shell.autocall = self._magic_state.autocall_save
602 609 except AttributeError:
603 610 self.shell.autocall = self._magic_state.autocall_save = 1
604 611
605 612 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
606 613
607 614 def magic_system_verbose(self, parameter_s = ''):
608 615 """Set verbose printing of system calls.
609 616
610 617 If called without an argument, act as a toggle"""
611 618
612 619 if parameter_s:
613 620 val = bool(eval(parameter_s))
614 621 else:
615 622 val = None
616 623
617 624 if self.shell.system_verbose:
618 625 self.shell.system_verbose = False
619 626 else:
620 627 self.shell.system_verbose = True
621 628 print "System verbose printing is:",\
622 629 ['OFF','ON'][self.shell.system_verbose]
623 630
624 631
625 632 def magic_page(self, parameter_s=''):
626 633 """Pretty print the object and display it through a pager.
627 634
628 635 %page [options] OBJECT
629 636
630 637 If no object is given, use _ (last output).
631 638
632 639 Options:
633 640
634 641 -r: page str(object), don't pretty-print it."""
635 642
636 643 # After a function contributed by Olivier Aubert, slightly modified.
637 644
638 645 # Process options/args
639 646 opts,args = self.parse_options(parameter_s,'r')
640 647 raw = 'r' in opts
641 648
642 649 oname = args and args or '_'
643 650 info = self._ofind(oname)
644 651 if info['found']:
645 652 txt = (raw and str or pformat)( info['obj'] )
646 653 page(txt)
647 654 else:
648 655 print 'Object `%s` not found' % oname
649 656
650 657 def magic_profile(self, parameter_s=''):
651 658 """Print your currently active IPyhton profile."""
652 659 if self.shell.profile:
653 660 printpl('Current IPython profile: $self.shell.profile.')
654 661 else:
655 662 print 'No profile active.'
656 663
657 664 def magic_pinfo(self, parameter_s='', namespaces=None):
658 665 """Provide detailed information about an object.
659 666
660 667 '%pinfo object' is just a synonym for object? or ?object."""
661 668
662 669 #print 'pinfo par: <%s>' % parameter_s # dbg
663 670
664 671
665 672 # detail_level: 0 -> obj? , 1 -> obj??
666 673 detail_level = 0
667 674 # We need to detect if we got called as 'pinfo pinfo foo', which can
668 675 # happen if the user types 'pinfo foo?' at the cmd line.
669 676 pinfo,qmark1,oname,qmark2 = \
670 677 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
671 678 if pinfo or qmark1 or qmark2:
672 679 detail_level = 1
673 680 if "*" in oname:
674 681 self.magic_psearch(oname)
675 682 else:
676 683 self._inspect('pinfo', oname, detail_level=detail_level,
677 684 namespaces=namespaces)
678 685
679 686 def magic_pdef(self, parameter_s='', namespaces=None):
680 687 """Print the definition header for any callable object.
681 688
682 689 If the object is a class, print the constructor information."""
683 690 self._inspect('pdef',parameter_s, namespaces)
684 691
685 692 def magic_pdoc(self, parameter_s='', namespaces=None):
686 693 """Print the docstring for an object.
687 694
688 695 If the given object is a class, it will print both the class and the
689 696 constructor docstrings."""
690 697 self._inspect('pdoc',parameter_s, namespaces)
691 698
692 699 def magic_psource(self, parameter_s='', namespaces=None):
693 700 """Print (or run through pager) the source code for an object."""
694 701 self._inspect('psource',parameter_s, namespaces)
695 702
696 703 def magic_pfile(self, parameter_s=''):
697 704 """Print (or run through pager) the file where an object is defined.
698 705
699 706 The file opens at the line where the object definition begins. IPython
700 707 will honor the environment variable PAGER if set, and otherwise will
701 708 do its best to print the file in a convenient form.
702 709
703 710 If the given argument is not an object currently defined, IPython will
704 711 try to interpret it as a filename (automatically adding a .py extension
705 712 if needed). You can thus use %pfile as a syntax highlighting code
706 713 viewer."""
707 714
708 715 # first interpret argument as an object name
709 716 out = self._inspect('pfile',parameter_s)
710 717 # if not, try the input as a filename
711 718 if out == 'not found':
712 719 try:
713 720 filename = get_py_filename(parameter_s)
714 721 except IOError,msg:
715 722 print msg
716 723 return
717 724 page(self.shell.inspector.format(file(filename).read()))
718 725
719 726 def _inspect(self,meth,oname,namespaces=None,**kw):
720 727 """Generic interface to the inspector system.
721 728
722 729 This function is meant to be called by pdef, pdoc & friends."""
723 730
724 731 #oname = oname.strip()
725 732 #print '1- oname: <%r>' % oname # dbg
726 733 try:
727 734 oname = oname.strip().encode('ascii')
728 735 #print '2- oname: <%r>' % oname # dbg
729 736 except UnicodeEncodeError:
730 737 print 'Python identifiers can only contain ascii characters.'
731 738 return 'not found'
732 739
733 740 info = Struct(self._ofind(oname, namespaces))
734 741
735 742 if info.found:
736 743 try:
737 744 IPython.utils.generics.inspect_object(info.obj)
738 745 return
739 746 except TryNext:
740 747 pass
741 748 # Get the docstring of the class property if it exists.
742 749 path = oname.split('.')
743 750 root = '.'.join(path[:-1])
744 751 if info.parent is not None:
745 752 try:
746 753 target = getattr(info.parent, '__class__')
747 754 # The object belongs to a class instance.
748 755 try:
749 756 target = getattr(target, path[-1])
750 757 # The class defines the object.
751 758 if isinstance(target, property):
752 759 oname = root + '.__class__.' + path[-1]
753 760 info = Struct(self._ofind(oname))
754 761 except AttributeError: pass
755 762 except AttributeError: pass
756 763
757 764 pmethod = getattr(self.shell.inspector,meth)
758 765 formatter = info.ismagic and self.format_screen or None
759 766 if meth == 'pdoc':
760 767 pmethod(info.obj,oname,formatter)
761 768 elif meth == 'pinfo':
762 769 pmethod(info.obj,oname,formatter,info,**kw)
763 770 else:
764 771 pmethod(info.obj,oname)
765 772 else:
766 773 print 'Object `%s` not found.' % oname
767 774 return 'not found' # so callers can take other action
768 775
769 776 def magic_psearch(self, parameter_s=''):
770 777 """Search for object in namespaces by wildcard.
771 778
772 779 %psearch [options] PATTERN [OBJECT TYPE]
773 780
774 781 Note: ? can be used as a synonym for %psearch, at the beginning or at
775 782 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
776 783 rest of the command line must be unchanged (options come first), so
777 784 for example the following forms are equivalent
778 785
779 786 %psearch -i a* function
780 787 -i a* function?
781 788 ?-i a* function
782 789
783 790 Arguments:
784 791
785 792 PATTERN
786 793
787 794 where PATTERN is a string containing * as a wildcard similar to its
788 795 use in a shell. The pattern is matched in all namespaces on the
789 796 search path. By default objects starting with a single _ are not
790 797 matched, many IPython generated objects have a single
791 798 underscore. The default is case insensitive matching. Matching is
792 799 also done on the attributes of objects and not only on the objects
793 800 in a module.
794 801
795 802 [OBJECT TYPE]
796 803
797 804 Is the name of a python type from the types module. The name is
798 805 given in lowercase without the ending type, ex. StringType is
799 806 written string. By adding a type here only objects matching the
800 807 given type are matched. Using all here makes the pattern match all
801 808 types (this is the default).
802 809
803 810 Options:
804 811
805 812 -a: makes the pattern match even objects whose names start with a
806 813 single underscore. These names are normally ommitted from the
807 814 search.
808 815
809 816 -i/-c: make the pattern case insensitive/sensitive. If neither of
810 817 these options is given, the default is read from your ipythonrc
811 818 file. The option name which sets this value is
812 819 'wildcards_case_sensitive'. If this option is not specified in your
813 820 ipythonrc file, IPython's internal default is to do a case sensitive
814 821 search.
815 822
816 823 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
817 824 specifiy can be searched in any of the following namespaces:
818 825 'builtin', 'user', 'user_global','internal', 'alias', where
819 826 'builtin' and 'user' are the search defaults. Note that you should
820 827 not use quotes when specifying namespaces.
821 828
822 829 'Builtin' contains the python module builtin, 'user' contains all
823 830 user data, 'alias' only contain the shell aliases and no python
824 831 objects, 'internal' contains objects used by IPython. The
825 832 'user_global' namespace is only used by embedded IPython instances,
826 833 and it contains module-level globals. You can add namespaces to the
827 834 search with -s or exclude them with -e (these options can be given
828 835 more than once).
829 836
830 837 Examples:
831 838
832 839 %psearch a* -> objects beginning with an a
833 840 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
834 841 %psearch a* function -> all functions beginning with an a
835 842 %psearch re.e* -> objects beginning with an e in module re
836 843 %psearch r*.e* -> objects that start with e in modules starting in r
837 844 %psearch r*.* string -> all strings in modules beginning with r
838 845
839 846 Case sensitve search:
840 847
841 848 %psearch -c a* list all object beginning with lower case a
842 849
843 850 Show objects beginning with a single _:
844 851
845 852 %psearch -a _* list objects beginning with a single underscore"""
846 853 try:
847 854 parameter_s = parameter_s.encode('ascii')
848 855 except UnicodeEncodeError:
849 856 print 'Python identifiers can only contain ascii characters.'
850 857 return
851 858
852 859 # default namespaces to be searched
853 860 def_search = ['user','builtin']
854 861
855 862 # Process options/args
856 863 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
857 864 opt = opts.get
858 865 shell = self.shell
859 866 psearch = shell.inspector.psearch
860 867
861 868 # select case options
862 869 if opts.has_key('i'):
863 870 ignore_case = True
864 871 elif opts.has_key('c'):
865 872 ignore_case = False
866 873 else:
867 874 ignore_case = not shell.wildcards_case_sensitive
868 875
869 876 # Build list of namespaces to search from user options
870 877 def_search.extend(opt('s',[]))
871 878 ns_exclude = ns_exclude=opt('e',[])
872 879 ns_search = [nm for nm in def_search if nm not in ns_exclude]
873 880
874 881 # Call the actual search
875 882 try:
876 883 psearch(args,shell.ns_table,ns_search,
877 884 show_all=opt('a'),ignore_case=ignore_case)
878 885 except:
879 886 shell.showtraceback()
880 887
881 888 def magic_who_ls(self, parameter_s=''):
882 889 """Return a sorted list of all interactive variables.
883 890
884 891 If arguments are given, only variables of types matching these
885 892 arguments are returned."""
886 893
887 894 user_ns = self.shell.user_ns
888 895 internal_ns = self.shell.internal_ns
889 896 user_ns_hidden = self.shell.user_ns_hidden
890 897 out = [ i for i in user_ns
891 898 if not i.startswith('_') \
892 899 and not (i in internal_ns or i in user_ns_hidden) ]
893 900
894 901 typelist = parameter_s.split()
895 902 if typelist:
896 903 typeset = set(typelist)
897 904 out = [i for i in out if type(i).__name__ in typeset]
898 905
899 906 out.sort()
900 907 return out
901 908
902 909 def magic_who(self, parameter_s=''):
903 910 """Print all interactive variables, with some minimal formatting.
904 911
905 912 If any arguments are given, only variables whose type matches one of
906 913 these are printed. For example:
907 914
908 915 %who function str
909 916
910 917 will only list functions and strings, excluding all other types of
911 918 variables. To find the proper type names, simply use type(var) at a
912 919 command line to see how python prints type names. For example:
913 920
914 921 In [1]: type('hello')\\
915 922 Out[1]: <type 'str'>
916 923
917 924 indicates that the type name for strings is 'str'.
918 925
919 926 %who always excludes executed names loaded through your configuration
920 927 file and things which are internal to IPython.
921 928
922 929 This is deliberate, as typically you may load many modules and the
923 930 purpose of %who is to show you only what you've manually defined."""
924 931
925 932 varlist = self.magic_who_ls(parameter_s)
926 933 if not varlist:
927 934 if parameter_s:
928 935 print 'No variables match your requested type.'
929 936 else:
930 937 print 'Interactive namespace is empty.'
931 938 return
932 939
933 940 # if we have variables, move on...
934 941 count = 0
935 942 for i in varlist:
936 943 print i+'\t',
937 944 count += 1
938 945 if count > 8:
939 946 count = 0
940 947 print
941 948 print
942 949
943 950 def magic_whos(self, parameter_s=''):
944 951 """Like %who, but gives some extra information about each variable.
945 952
946 953 The same type filtering of %who can be applied here.
947 954
948 955 For all variables, the type is printed. Additionally it prints:
949 956
950 957 - For {},[],(): their length.
951 958
952 959 - For numpy and Numeric arrays, a summary with shape, number of
953 960 elements, typecode and size in memory.
954 961
955 962 - Everything else: a string representation, snipping their middle if
956 963 too long."""
957 964
958 965 varnames = self.magic_who_ls(parameter_s)
959 966 if not varnames:
960 967 if parameter_s:
961 968 print 'No variables match your requested type.'
962 969 else:
963 970 print 'Interactive namespace is empty.'
964 971 return
965 972
966 973 # if we have variables, move on...
967 974
968 975 # for these types, show len() instead of data:
969 976 seq_types = [types.DictType,types.ListType,types.TupleType]
970 977
971 978 # for numpy/Numeric arrays, display summary info
972 979 try:
973 980 import numpy
974 981 except ImportError:
975 982 ndarray_type = None
976 983 else:
977 984 ndarray_type = numpy.ndarray.__name__
978 985 try:
979 986 import Numeric
980 987 except ImportError:
981 988 array_type = None
982 989 else:
983 990 array_type = Numeric.ArrayType.__name__
984 991
985 992 # Find all variable names and types so we can figure out column sizes
986 993 def get_vars(i):
987 994 return self.shell.user_ns[i]
988 995
989 996 # some types are well known and can be shorter
990 997 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
991 998 def type_name(v):
992 999 tn = type(v).__name__
993 1000 return abbrevs.get(tn,tn)
994 1001
995 1002 varlist = map(get_vars,varnames)
996 1003
997 1004 typelist = []
998 1005 for vv in varlist:
999 1006 tt = type_name(vv)
1000 1007
1001 1008 if tt=='instance':
1002 1009 typelist.append( abbrevs.get(str(vv.__class__),
1003 1010 str(vv.__class__)))
1004 1011 else:
1005 1012 typelist.append(tt)
1006 1013
1007 1014 # column labels and # of spaces as separator
1008 1015 varlabel = 'Variable'
1009 1016 typelabel = 'Type'
1010 1017 datalabel = 'Data/Info'
1011 1018 colsep = 3
1012 1019 # variable format strings
1013 1020 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1014 1021 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1015 1022 aformat = "%s: %s elems, type `%s`, %s bytes"
1016 1023 # find the size of the columns to format the output nicely
1017 1024 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1018 1025 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1019 1026 # table header
1020 1027 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1021 1028 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1022 1029 # and the table itself
1023 1030 kb = 1024
1024 1031 Mb = 1048576 # kb**2
1025 1032 for vname,var,vtype in zip(varnames,varlist,typelist):
1026 1033 print itpl(vformat),
1027 1034 if vtype in seq_types:
1028 1035 print len(var)
1029 1036 elif vtype in [array_type,ndarray_type]:
1030 1037 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1031 1038 if vtype==ndarray_type:
1032 1039 # numpy
1033 1040 vsize = var.size
1034 1041 vbytes = vsize*var.itemsize
1035 1042 vdtype = var.dtype
1036 1043 else:
1037 1044 # Numeric
1038 1045 vsize = Numeric.size(var)
1039 1046 vbytes = vsize*var.itemsize()
1040 1047 vdtype = var.typecode()
1041 1048
1042 1049 if vbytes < 100000:
1043 1050 print aformat % (vshape,vsize,vdtype,vbytes)
1044 1051 else:
1045 1052 print aformat % (vshape,vsize,vdtype,vbytes),
1046 1053 if vbytes < Mb:
1047 1054 print '(%s kb)' % (vbytes/kb,)
1048 1055 else:
1049 1056 print '(%s Mb)' % (vbytes/Mb,)
1050 1057 else:
1051 1058 try:
1052 1059 vstr = str(var)
1053 1060 except UnicodeEncodeError:
1054 1061 vstr = unicode(var).encode(sys.getdefaultencoding(),
1055 1062 'backslashreplace')
1056 1063 vstr = vstr.replace('\n','\\n')
1057 1064 if len(vstr) < 50:
1058 1065 print vstr
1059 1066 else:
1060 1067 printpl(vfmt_short)
1061 1068
1062 1069 def magic_reset(self, parameter_s=''):
1063 1070 """Resets the namespace by removing all names defined by the user.
1064 1071
1065 1072 Input/Output history are left around in case you need them.
1066 1073
1067 1074 Parameters
1068 1075 ----------
1069 1076 -y : force reset without asking for confirmation.
1070 1077
1071 1078 Examples
1072 1079 --------
1073 1080 In [6]: a = 1
1074 1081
1075 1082 In [7]: a
1076 1083 Out[7]: 1
1077 1084
1078 1085 In [8]: 'a' in _ip.user_ns
1079 1086 Out[8]: True
1080 1087
1081 1088 In [9]: %reset -f
1082 1089
1083 1090 In [10]: 'a' in _ip.user_ns
1084 1091 Out[10]: False
1085 1092 """
1086 1093
1087 1094 if parameter_s == '-f':
1088 1095 ans = True
1089 1096 else:
1090 1097 ans = self.shell.ask_yes_no(
1091 1098 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1092 1099 if not ans:
1093 1100 print 'Nothing done.'
1094 1101 return
1095 1102 user_ns = self.shell.user_ns
1096 1103 for i in self.magic_who_ls():
1097 1104 del(user_ns[i])
1098 1105
1099 1106 # Also flush the private list of module references kept for script
1100 1107 # execution protection
1101 1108 self.shell.clear_main_mod_cache()
1102 1109
1103 1110 def magic_logstart(self,parameter_s=''):
1104 1111 """Start logging anywhere in a session.
1105 1112
1106 1113 %logstart [-o|-r|-t] [log_name [log_mode]]
1107 1114
1108 1115 If no name is given, it defaults to a file named 'ipython_log.py' in your
1109 1116 current directory, in 'rotate' mode (see below).
1110 1117
1111 1118 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1112 1119 history up to that point and then continues logging.
1113 1120
1114 1121 %logstart takes a second optional parameter: logging mode. This can be one
1115 1122 of (note that the modes are given unquoted):\\
1116 1123 append: well, that says it.\\
1117 1124 backup: rename (if exists) to name~ and start name.\\
1118 1125 global: single logfile in your home dir, appended to.\\
1119 1126 over : overwrite existing log.\\
1120 1127 rotate: create rotating logs name.1~, name.2~, etc.
1121 1128
1122 1129 Options:
1123 1130
1124 1131 -o: log also IPython's output. In this mode, all commands which
1125 1132 generate an Out[NN] prompt are recorded to the logfile, right after
1126 1133 their corresponding input line. The output lines are always
1127 1134 prepended with a '#[Out]# ' marker, so that the log remains valid
1128 1135 Python code.
1129 1136
1130 1137 Since this marker is always the same, filtering only the output from
1131 1138 a log is very easy, using for example a simple awk call:
1132 1139
1133 1140 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1134 1141
1135 1142 -r: log 'raw' input. Normally, IPython's logs contain the processed
1136 1143 input, so that user lines are logged in their final form, converted
1137 1144 into valid Python. For example, %Exit is logged as
1138 1145 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1139 1146 exactly as typed, with no transformations applied.
1140 1147
1141 1148 -t: put timestamps before each input line logged (these are put in
1142 1149 comments)."""
1143 1150
1144 1151 opts,par = self.parse_options(parameter_s,'ort')
1145 1152 log_output = 'o' in opts
1146 1153 log_raw_input = 'r' in opts
1147 1154 timestamp = 't' in opts
1148 1155
1149 1156 logger = self.shell.logger
1150 1157
1151 1158 # if no args are given, the defaults set in the logger constructor by
1152 1159 # ipytohn remain valid
1153 1160 if par:
1154 1161 try:
1155 1162 logfname,logmode = par.split()
1156 1163 except:
1157 1164 logfname = par
1158 1165 logmode = 'backup'
1159 1166 else:
1160 1167 logfname = logger.logfname
1161 1168 logmode = logger.logmode
1162 1169 # put logfname into rc struct as if it had been called on the command
1163 1170 # line, so it ends up saved in the log header Save it in case we need
1164 1171 # to restore it...
1165 1172 old_logfile = self.shell.logfile
1166 1173 if logfname:
1167 1174 logfname = os.path.expanduser(logfname)
1168 1175 self.shell.logfile = logfname
1169 1176
1170 1177 loghead = '# IPython log file\n\n'
1171 1178 try:
1172 1179 started = logger.logstart(logfname,loghead,logmode,
1173 1180 log_output,timestamp,log_raw_input)
1174 1181 except:
1175 1182 self.shell.logfile = old_logfile
1176 1183 warn("Couldn't start log: %s" % sys.exc_info()[1])
1177 1184 else:
1178 1185 # log input history up to this point, optionally interleaving
1179 1186 # output if requested
1180 1187
1181 1188 if timestamp:
1182 1189 # disable timestamping for the previous history, since we've
1183 1190 # lost those already (no time machine here).
1184 1191 logger.timestamp = False
1185 1192
1186 1193 if log_raw_input:
1187 1194 input_hist = self.shell.input_hist_raw
1188 1195 else:
1189 1196 input_hist = self.shell.input_hist
1190 1197
1191 1198 if log_output:
1192 1199 log_write = logger.log_write
1193 1200 output_hist = self.shell.output_hist
1194 1201 for n in range(1,len(input_hist)-1):
1195 1202 log_write(input_hist[n].rstrip())
1196 1203 if n in output_hist:
1197 1204 log_write(repr(output_hist[n]),'output')
1198 1205 else:
1199 1206 logger.log_write(input_hist[1:])
1200 1207 if timestamp:
1201 1208 # re-enable timestamping
1202 1209 logger.timestamp = True
1203 1210
1204 1211 print ('Activating auto-logging. '
1205 1212 'Current session state plus future input saved.')
1206 1213 logger.logstate()
1207 1214
1208 1215 def magic_logstop(self,parameter_s=''):
1209 1216 """Fully stop logging and close log file.
1210 1217
1211 1218 In order to start logging again, a new %logstart call needs to be made,
1212 1219 possibly (though not necessarily) with a new filename, mode and other
1213 1220 options."""
1214 1221 self.logger.logstop()
1215 1222
1216 1223 def magic_logoff(self,parameter_s=''):
1217 1224 """Temporarily stop logging.
1218 1225
1219 1226 You must have previously started logging."""
1220 1227 self.shell.logger.switch_log(0)
1221 1228
1222 1229 def magic_logon(self,parameter_s=''):
1223 1230 """Restart logging.
1224 1231
1225 1232 This function is for restarting logging which you've temporarily
1226 1233 stopped with %logoff. For starting logging for the first time, you
1227 1234 must use the %logstart function, which allows you to specify an
1228 1235 optional log filename."""
1229 1236
1230 1237 self.shell.logger.switch_log(1)
1231 1238
1232 1239 def magic_logstate(self,parameter_s=''):
1233 1240 """Print the status of the logging system."""
1234 1241
1235 1242 self.shell.logger.logstate()
1236 1243
1237 1244 def magic_pdb(self, parameter_s=''):
1238 1245 """Control the automatic calling of the pdb interactive debugger.
1239 1246
1240 1247 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1241 1248 argument it works as a toggle.
1242 1249
1243 1250 When an exception is triggered, IPython can optionally call the
1244 1251 interactive pdb debugger after the traceback printout. %pdb toggles
1245 1252 this feature on and off.
1246 1253
1247 1254 The initial state of this feature is set in your ipythonrc
1248 1255 configuration file (the variable is called 'pdb').
1249 1256
1250 1257 If you want to just activate the debugger AFTER an exception has fired,
1251 1258 without having to type '%pdb on' and rerunning your code, you can use
1252 1259 the %debug magic."""
1253 1260
1254 1261 par = parameter_s.strip().lower()
1255 1262
1256 1263 if par:
1257 1264 try:
1258 1265 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1259 1266 except KeyError:
1260 1267 print ('Incorrect argument. Use on/1, off/0, '
1261 1268 'or nothing for a toggle.')
1262 1269 return
1263 1270 else:
1264 1271 # toggle
1265 1272 new_pdb = not self.shell.call_pdb
1266 1273
1267 1274 # set on the shell
1268 1275 self.shell.call_pdb = new_pdb
1269 1276 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1270 1277
1271 1278 def magic_debug(self, parameter_s=''):
1272 1279 """Activate the interactive debugger in post-mortem mode.
1273 1280
1274 1281 If an exception has just occurred, this lets you inspect its stack
1275 1282 frames interactively. Note that this will always work only on the last
1276 1283 traceback that occurred, so you must call this quickly after an
1277 1284 exception that you wish to inspect has fired, because if another one
1278 1285 occurs, it clobbers the previous one.
1279 1286
1280 1287 If you want IPython to automatically do this on every exception, see
1281 1288 the %pdb magic for more details.
1282 1289 """
1283 1290 self.shell.debugger(force=True)
1284 1291
1285 1292 @testdec.skip_doctest
1286 1293 def magic_prun(self, parameter_s ='',user_mode=1,
1287 1294 opts=None,arg_lst=None,prog_ns=None):
1288 1295
1289 1296 """Run a statement through the python code profiler.
1290 1297
1291 1298 Usage:
1292 1299 %prun [options] statement
1293 1300
1294 1301 The given statement (which doesn't require quote marks) is run via the
1295 1302 python profiler in a manner similar to the profile.run() function.
1296 1303 Namespaces are internally managed to work correctly; profile.run
1297 1304 cannot be used in IPython because it makes certain assumptions about
1298 1305 namespaces which do not hold under IPython.
1299 1306
1300 1307 Options:
1301 1308
1302 1309 -l <limit>: you can place restrictions on what or how much of the
1303 1310 profile gets printed. The limit value can be:
1304 1311
1305 1312 * A string: only information for function names containing this string
1306 1313 is printed.
1307 1314
1308 1315 * An integer: only these many lines are printed.
1309 1316
1310 1317 * A float (between 0 and 1): this fraction of the report is printed
1311 1318 (for example, use a limit of 0.4 to see the topmost 40% only).
1312 1319
1313 1320 You can combine several limits with repeated use of the option. For
1314 1321 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1315 1322 information about class constructors.
1316 1323
1317 1324 -r: return the pstats.Stats object generated by the profiling. This
1318 1325 object has all the information about the profile in it, and you can
1319 1326 later use it for further analysis or in other functions.
1320 1327
1321 1328 -s <key>: sort profile by given key. You can provide more than one key
1322 1329 by using the option several times: '-s key1 -s key2 -s key3...'. The
1323 1330 default sorting key is 'time'.
1324 1331
1325 1332 The following is copied verbatim from the profile documentation
1326 1333 referenced below:
1327 1334
1328 1335 When more than one key is provided, additional keys are used as
1329 1336 secondary criteria when the there is equality in all keys selected
1330 1337 before them.
1331 1338
1332 1339 Abbreviations can be used for any key names, as long as the
1333 1340 abbreviation is unambiguous. The following are the keys currently
1334 1341 defined:
1335 1342
1336 1343 Valid Arg Meaning
1337 1344 "calls" call count
1338 1345 "cumulative" cumulative time
1339 1346 "file" file name
1340 1347 "module" file name
1341 1348 "pcalls" primitive call count
1342 1349 "line" line number
1343 1350 "name" function name
1344 1351 "nfl" name/file/line
1345 1352 "stdname" standard name
1346 1353 "time" internal time
1347 1354
1348 1355 Note that all sorts on statistics are in descending order (placing
1349 1356 most time consuming items first), where as name, file, and line number
1350 1357 searches are in ascending order (i.e., alphabetical). The subtle
1351 1358 distinction between "nfl" and "stdname" is that the standard name is a
1352 1359 sort of the name as printed, which means that the embedded line
1353 1360 numbers get compared in an odd way. For example, lines 3, 20, and 40
1354 1361 would (if the file names were the same) appear in the string order
1355 1362 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1356 1363 line numbers. In fact, sort_stats("nfl") is the same as
1357 1364 sort_stats("name", "file", "line").
1358 1365
1359 1366 -T <filename>: save profile results as shown on screen to a text
1360 1367 file. The profile is still shown on screen.
1361 1368
1362 1369 -D <filename>: save (via dump_stats) profile statistics to given
1363 1370 filename. This data is in a format understod by the pstats module, and
1364 1371 is generated by a call to the dump_stats() method of profile
1365 1372 objects. The profile is still shown on screen.
1366 1373
1367 1374 If you want to run complete programs under the profiler's control, use
1368 1375 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1369 1376 contains profiler specific options as described here.
1370 1377
1371 1378 You can read the complete documentation for the profile module with::
1372 1379
1373 1380 In [1]: import profile; profile.help()
1374 1381 """
1375 1382
1376 1383 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1377 1384 # protect user quote marks
1378 1385 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1379 1386
1380 1387 if user_mode: # regular user call
1381 1388 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1382 1389 list_all=1)
1383 1390 namespace = self.shell.user_ns
1384 1391 else: # called to run a program by %run -p
1385 1392 try:
1386 1393 filename = get_py_filename(arg_lst[0])
1387 1394 except IOError,msg:
1388 1395 error(msg)
1389 1396 return
1390 1397
1391 1398 arg_str = 'execfile(filename,prog_ns)'
1392 1399 namespace = locals()
1393 1400
1394 1401 opts.merge(opts_def)
1395 1402
1396 1403 prof = profile.Profile()
1397 1404 try:
1398 1405 prof = prof.runctx(arg_str,namespace,namespace)
1399 1406 sys_exit = ''
1400 1407 except SystemExit:
1401 1408 sys_exit = """*** SystemExit exception caught in code being profiled."""
1402 1409
1403 1410 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1404 1411
1405 1412 lims = opts.l
1406 1413 if lims:
1407 1414 lims = [] # rebuild lims with ints/floats/strings
1408 1415 for lim in opts.l:
1409 1416 try:
1410 1417 lims.append(int(lim))
1411 1418 except ValueError:
1412 1419 try:
1413 1420 lims.append(float(lim))
1414 1421 except ValueError:
1415 1422 lims.append(lim)
1416 1423
1417 1424 # Trap output.
1418 1425 stdout_trap = StringIO()
1419 1426
1420 1427 if hasattr(stats,'stream'):
1421 1428 # In newer versions of python, the stats object has a 'stream'
1422 1429 # attribute to write into.
1423 1430 stats.stream = stdout_trap
1424 1431 stats.print_stats(*lims)
1425 1432 else:
1426 1433 # For older versions, we manually redirect stdout during printing
1427 1434 sys_stdout = sys.stdout
1428 1435 try:
1429 1436 sys.stdout = stdout_trap
1430 1437 stats.print_stats(*lims)
1431 1438 finally:
1432 1439 sys.stdout = sys_stdout
1433 1440
1434 1441 output = stdout_trap.getvalue()
1435 1442 output = output.rstrip()
1436 1443
1437 1444 page(output,screen_lines=self.shell.usable_screen_length)
1438 1445 print sys_exit,
1439 1446
1440 1447 dump_file = opts.D[0]
1441 1448 text_file = opts.T[0]
1442 1449 if dump_file:
1443 1450 prof.dump_stats(dump_file)
1444 1451 print '\n*** Profile stats marshalled to file',\
1445 1452 `dump_file`+'.',sys_exit
1446 1453 if text_file:
1447 1454 pfile = file(text_file,'w')
1448 1455 pfile.write(output)
1449 1456 pfile.close()
1450 1457 print '\n*** Profile printout saved to text file',\
1451 1458 `text_file`+'.',sys_exit
1452 1459
1453 1460 if opts.has_key('r'):
1454 1461 return stats
1455 1462 else:
1456 1463 return None
1457 1464
1458 1465 @testdec.skip_doctest
1459 1466 def magic_run(self, parameter_s ='',runner=None,
1460 1467 file_finder=get_py_filename):
1461 1468 """Run the named file inside IPython as a program.
1462 1469
1463 1470 Usage:\\
1464 1471 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1465 1472
1466 1473 Parameters after the filename are passed as command-line arguments to
1467 1474 the program (put in sys.argv). Then, control returns to IPython's
1468 1475 prompt.
1469 1476
1470 1477 This is similar to running at a system prompt:\\
1471 1478 $ python file args\\
1472 1479 but with the advantage of giving you IPython's tracebacks, and of
1473 1480 loading all variables into your interactive namespace for further use
1474 1481 (unless -p is used, see below).
1475 1482
1476 1483 The file is executed in a namespace initially consisting only of
1477 1484 __name__=='__main__' and sys.argv constructed as indicated. It thus
1478 1485 sees its environment as if it were being run as a stand-alone program
1479 1486 (except for sharing global objects such as previously imported
1480 1487 modules). But after execution, the IPython interactive namespace gets
1481 1488 updated with all variables defined in the program (except for __name__
1482 1489 and sys.argv). This allows for very convenient loading of code for
1483 1490 interactive work, while giving each program a 'clean sheet' to run in.
1484 1491
1485 1492 Options:
1486 1493
1487 1494 -n: __name__ is NOT set to '__main__', but to the running file's name
1488 1495 without extension (as python does under import). This allows running
1489 1496 scripts and reloading the definitions in them without calling code
1490 1497 protected by an ' if __name__ == "__main__" ' clause.
1491 1498
1492 1499 -i: run the file in IPython's namespace instead of an empty one. This
1493 1500 is useful if you are experimenting with code written in a text editor
1494 1501 which depends on variables defined interactively.
1495 1502
1496 1503 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1497 1504 being run. This is particularly useful if IPython is being used to
1498 1505 run unittests, which always exit with a sys.exit() call. In such
1499 1506 cases you are interested in the output of the test results, not in
1500 1507 seeing a traceback of the unittest module.
1501 1508
1502 1509 -t: print timing information at the end of the run. IPython will give
1503 1510 you an estimated CPU time consumption for your script, which under
1504 1511 Unix uses the resource module to avoid the wraparound problems of
1505 1512 time.clock(). Under Unix, an estimate of time spent on system tasks
1506 1513 is also given (for Windows platforms this is reported as 0.0).
1507 1514
1508 1515 If -t is given, an additional -N<N> option can be given, where <N>
1509 1516 must be an integer indicating how many times you want the script to
1510 1517 run. The final timing report will include total and per run results.
1511 1518
1512 1519 For example (testing the script uniq_stable.py):
1513 1520
1514 1521 In [1]: run -t uniq_stable
1515 1522
1516 1523 IPython CPU timings (estimated):\\
1517 1524 User : 0.19597 s.\\
1518 1525 System: 0.0 s.\\
1519 1526
1520 1527 In [2]: run -t -N5 uniq_stable
1521 1528
1522 1529 IPython CPU timings (estimated):\\
1523 1530 Total runs performed: 5\\
1524 1531 Times : Total Per run\\
1525 1532 User : 0.910862 s, 0.1821724 s.\\
1526 1533 System: 0.0 s, 0.0 s.
1527 1534
1528 1535 -d: run your program under the control of pdb, the Python debugger.
1529 1536 This allows you to execute your program step by step, watch variables,
1530 1537 etc. Internally, what IPython does is similar to calling:
1531 1538
1532 1539 pdb.run('execfile("YOURFILENAME")')
1533 1540
1534 1541 with a breakpoint set on line 1 of your file. You can change the line
1535 1542 number for this automatic breakpoint to be <N> by using the -bN option
1536 1543 (where N must be an integer). For example:
1537 1544
1538 1545 %run -d -b40 myscript
1539 1546
1540 1547 will set the first breakpoint at line 40 in myscript.py. Note that
1541 1548 the first breakpoint must be set on a line which actually does
1542 1549 something (not a comment or docstring) for it to stop execution.
1543 1550
1544 1551 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1545 1552 first enter 'c' (without qoutes) to start execution up to the first
1546 1553 breakpoint.
1547 1554
1548 1555 Entering 'help' gives information about the use of the debugger. You
1549 1556 can easily see pdb's full documentation with "import pdb;pdb.help()"
1550 1557 at a prompt.
1551 1558
1552 1559 -p: run program under the control of the Python profiler module (which
1553 1560 prints a detailed report of execution times, function calls, etc).
1554 1561
1555 1562 You can pass other options after -p which affect the behavior of the
1556 1563 profiler itself. See the docs for %prun for details.
1557 1564
1558 1565 In this mode, the program's variables do NOT propagate back to the
1559 1566 IPython interactive namespace (because they remain in the namespace
1560 1567 where the profiler executes them).
1561 1568
1562 1569 Internally this triggers a call to %prun, see its documentation for
1563 1570 details on the options available specifically for profiling.
1564 1571
1565 1572 There is one special usage for which the text above doesn't apply:
1566 1573 if the filename ends with .ipy, the file is run as ipython script,
1567 1574 just as if the commands were written on IPython prompt.
1568 1575 """
1569 1576
1570 1577 # get arguments and set sys.argv for program to be run.
1571 1578 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1572 1579 mode='list',list_all=1)
1573 1580
1574 1581 try:
1575 1582 filename = file_finder(arg_lst[0])
1576 1583 except IndexError:
1577 1584 warn('you must provide at least a filename.')
1578 1585 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1579 1586 return
1580 1587 except IOError,msg:
1581 1588 error(msg)
1582 1589 return
1583 1590
1584 1591 if filename.lower().endswith('.ipy'):
1585 1592 self.shell.safe_execfile_ipy(filename)
1586 1593 return
1587 1594
1588 1595 # Control the response to exit() calls made by the script being run
1589 1596 exit_ignore = opts.has_key('e')
1590 1597
1591 1598 # Make sure that the running script gets a proper sys.argv as if it
1592 1599 # were run from a system shell.
1593 1600 save_argv = sys.argv # save it for later restoring
1594 1601 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1595 1602
1596 1603 if opts.has_key('i'):
1597 1604 # Run in user's interactive namespace
1598 1605 prog_ns = self.shell.user_ns
1599 1606 __name__save = self.shell.user_ns['__name__']
1600 1607 prog_ns['__name__'] = '__main__'
1601 1608 main_mod = self.shell.new_main_mod(prog_ns)
1602 1609 else:
1603 1610 # Run in a fresh, empty namespace
1604 1611 if opts.has_key('n'):
1605 1612 name = os.path.splitext(os.path.basename(filename))[0]
1606 1613 else:
1607 1614 name = '__main__'
1608 1615
1609 1616 main_mod = self.shell.new_main_mod()
1610 1617 prog_ns = main_mod.__dict__
1611 1618 prog_ns['__name__'] = name
1612 1619
1613 1620 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1614 1621 # set the __file__ global in the script's namespace
1615 1622 prog_ns['__file__'] = filename
1616 1623
1617 1624 # pickle fix. See iplib for an explanation. But we need to make sure
1618 1625 # that, if we overwrite __main__, we replace it at the end
1619 1626 main_mod_name = prog_ns['__name__']
1620 1627
1621 1628 if main_mod_name == '__main__':
1622 1629 restore_main = sys.modules['__main__']
1623 1630 else:
1624 1631 restore_main = False
1625 1632
1626 1633 # This needs to be undone at the end to prevent holding references to
1627 1634 # every single object ever created.
1628 1635 sys.modules[main_mod_name] = main_mod
1629 1636
1630 1637 stats = None
1631 1638 try:
1632 1639 self.shell.savehist()
1633 1640
1634 1641 if opts.has_key('p'):
1635 1642 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1636 1643 else:
1637 1644 if opts.has_key('d'):
1638 1645 deb = debugger.Pdb(self.shell.colors)
1639 1646 # reset Breakpoint state, which is moronically kept
1640 1647 # in a class
1641 1648 bdb.Breakpoint.next = 1
1642 1649 bdb.Breakpoint.bplist = {}
1643 1650 bdb.Breakpoint.bpbynumber = [None]
1644 1651 # Set an initial breakpoint to stop execution
1645 1652 maxtries = 10
1646 1653 bp = int(opts.get('b',[1])[0])
1647 1654 checkline = deb.checkline(filename,bp)
1648 1655 if not checkline:
1649 1656 for bp in range(bp+1,bp+maxtries+1):
1650 1657 if deb.checkline(filename,bp):
1651 1658 break
1652 1659 else:
1653 1660 msg = ("\nI failed to find a valid line to set "
1654 1661 "a breakpoint\n"
1655 1662 "after trying up to line: %s.\n"
1656 1663 "Please set a valid breakpoint manually "
1657 1664 "with the -b option." % bp)
1658 1665 error(msg)
1659 1666 return
1660 1667 # if we find a good linenumber, set the breakpoint
1661 1668 deb.do_break('%s:%s' % (filename,bp))
1662 1669 # Start file run
1663 1670 print "NOTE: Enter 'c' at the",
1664 1671 print "%s prompt to start your script." % deb.prompt
1665 1672 try:
1666 1673 deb.run('execfile("%s")' % filename,prog_ns)
1667 1674
1668 1675 except:
1669 1676 etype, value, tb = sys.exc_info()
1670 1677 # Skip three frames in the traceback: the %run one,
1671 1678 # one inside bdb.py, and the command-line typed by the
1672 1679 # user (run by exec in pdb itself).
1673 1680 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1674 1681 else:
1675 1682 if runner is None:
1676 1683 runner = self.shell.safe_execfile
1677 1684 if opts.has_key('t'):
1678 1685 # timed execution
1679 1686 try:
1680 1687 nruns = int(opts['N'][0])
1681 1688 if nruns < 1:
1682 1689 error('Number of runs must be >=1')
1683 1690 return
1684 1691 except (KeyError):
1685 1692 nruns = 1
1686 1693 if nruns == 1:
1687 1694 t0 = clock2()
1688 1695 runner(filename,prog_ns,prog_ns,
1689 1696 exit_ignore=exit_ignore)
1690 1697 t1 = clock2()
1691 1698 t_usr = t1[0]-t0[0]
1692 1699 t_sys = t1[1]-t0[1]
1693 1700 print "\nIPython CPU timings (estimated):"
1694 1701 print " User : %10s s." % t_usr
1695 1702 print " System: %10s s." % t_sys
1696 1703 else:
1697 1704 runs = range(nruns)
1698 1705 t0 = clock2()
1699 1706 for nr in runs:
1700 1707 runner(filename,prog_ns,prog_ns,
1701 1708 exit_ignore=exit_ignore)
1702 1709 t1 = clock2()
1703 1710 t_usr = t1[0]-t0[0]
1704 1711 t_sys = t1[1]-t0[1]
1705 1712 print "\nIPython CPU timings (estimated):"
1706 1713 print "Total runs performed:",nruns
1707 1714 print " Times : %10s %10s" % ('Total','Per run')
1708 1715 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1709 1716 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1710 1717
1711 1718 else:
1712 1719 # regular execution
1713 1720 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1714 1721
1715 1722 if opts.has_key('i'):
1716 1723 self.shell.user_ns['__name__'] = __name__save
1717 1724 else:
1718 1725 # The shell MUST hold a reference to prog_ns so after %run
1719 1726 # exits, the python deletion mechanism doesn't zero it out
1720 1727 # (leaving dangling references).
1721 1728 self.shell.cache_main_mod(prog_ns,filename)
1722 1729 # update IPython interactive namespace
1723 1730
1724 1731 # Some forms of read errors on the file may mean the
1725 1732 # __name__ key was never set; using pop we don't have to
1726 1733 # worry about a possible KeyError.
1727 1734 prog_ns.pop('__name__', None)
1728 1735
1729 1736 self.shell.user_ns.update(prog_ns)
1730 1737 finally:
1731 1738 # It's a bit of a mystery why, but __builtins__ can change from
1732 1739 # being a module to becoming a dict missing some key data after
1733 1740 # %run. As best I can see, this is NOT something IPython is doing
1734 1741 # at all, and similar problems have been reported before:
1735 1742 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1736 1743 # Since this seems to be done by the interpreter itself, the best
1737 1744 # we can do is to at least restore __builtins__ for the user on
1738 1745 # exit.
1739 1746 self.shell.user_ns['__builtins__'] = __builtin__
1740 1747
1741 1748 # Ensure key global structures are restored
1742 1749 sys.argv = save_argv
1743 1750 if restore_main:
1744 1751 sys.modules['__main__'] = restore_main
1745 1752 else:
1746 1753 # Remove from sys.modules the reference to main_mod we'd
1747 1754 # added. Otherwise it will trap references to objects
1748 1755 # contained therein.
1749 1756 del sys.modules[main_mod_name]
1750 1757
1751 1758 self.shell.reloadhist()
1752 1759
1753 1760 return stats
1754 1761
1755 1762 @testdec.skip_doctest
1756 1763 def magic_timeit(self, parameter_s =''):
1757 1764 """Time execution of a Python statement or expression
1758 1765
1759 1766 Usage:\\
1760 1767 %timeit [-n<N> -r<R> [-t|-c]] statement
1761 1768
1762 1769 Time execution of a Python statement or expression using the timeit
1763 1770 module.
1764 1771
1765 1772 Options:
1766 1773 -n<N>: execute the given statement <N> times in a loop. If this value
1767 1774 is not given, a fitting value is chosen.
1768 1775
1769 1776 -r<R>: repeat the loop iteration <R> times and take the best result.
1770 1777 Default: 3
1771 1778
1772 1779 -t: use time.time to measure the time, which is the default on Unix.
1773 1780 This function measures wall time.
1774 1781
1775 1782 -c: use time.clock to measure the time, which is the default on
1776 1783 Windows and measures wall time. On Unix, resource.getrusage is used
1777 1784 instead and returns the CPU user time.
1778 1785
1779 1786 -p<P>: use a precision of <P> digits to display the timing result.
1780 1787 Default: 3
1781 1788
1782 1789
1783 1790 Examples:
1784 1791
1785 1792 In [1]: %timeit pass
1786 1793 10000000 loops, best of 3: 53.3 ns per loop
1787 1794
1788 1795 In [2]: u = None
1789 1796
1790 1797 In [3]: %timeit u is None
1791 1798 10000000 loops, best of 3: 184 ns per loop
1792 1799
1793 1800 In [4]: %timeit -r 4 u == None
1794 1801 1000000 loops, best of 4: 242 ns per loop
1795 1802
1796 1803 In [5]: import time
1797 1804
1798 1805 In [6]: %timeit -n1 time.sleep(2)
1799 1806 1 loops, best of 3: 2 s per loop
1800 1807
1801 1808
1802 1809 The times reported by %timeit will be slightly higher than those
1803 1810 reported by the timeit.py script when variables are accessed. This is
1804 1811 due to the fact that %timeit executes the statement in the namespace
1805 1812 of the shell, compared with timeit.py, which uses a single setup
1806 1813 statement to import function or create variables. Generally, the bias
1807 1814 does not matter as long as results from timeit.py are not mixed with
1808 1815 those from %timeit."""
1809 1816
1810 1817 import timeit
1811 1818 import math
1812 1819
1813 1820 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1814 1821 # certain terminals. Until we figure out a robust way of
1815 1822 # auto-detecting if the terminal can deal with it, use plain 'us' for
1816 1823 # microseconds. I am really NOT happy about disabling the proper
1817 1824 # 'micro' prefix, but crashing is worse... If anyone knows what the
1818 1825 # right solution for this is, I'm all ears...
1819 1826 #
1820 1827 # Note: using
1821 1828 #
1822 1829 # s = u'\xb5'
1823 1830 # s.encode(sys.getdefaultencoding())
1824 1831 #
1825 1832 # is not sufficient, as I've seen terminals where that fails but
1826 1833 # print s
1827 1834 #
1828 1835 # succeeds
1829 1836 #
1830 1837 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1831 1838
1832 1839 #units = [u"s", u"ms",u'\xb5',"ns"]
1833 1840 units = [u"s", u"ms",u'us',"ns"]
1834 1841
1835 1842 scaling = [1, 1e3, 1e6, 1e9]
1836 1843
1837 1844 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1838 1845 posix=False)
1839 1846 if stmt == "":
1840 1847 return
1841 1848 timefunc = timeit.default_timer
1842 1849 number = int(getattr(opts, "n", 0))
1843 1850 repeat = int(getattr(opts, "r", timeit.default_repeat))
1844 1851 precision = int(getattr(opts, "p", 3))
1845 1852 if hasattr(opts, "t"):
1846 1853 timefunc = time.time
1847 1854 if hasattr(opts, "c"):
1848 1855 timefunc = clock
1849 1856
1850 1857 timer = timeit.Timer(timer=timefunc)
1851 1858 # this code has tight coupling to the inner workings of timeit.Timer,
1852 1859 # but is there a better way to achieve that the code stmt has access
1853 1860 # to the shell namespace?
1854 1861
1855 1862 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1856 1863 'setup': "pass"}
1857 1864 # Track compilation time so it can be reported if too long
1858 1865 # Minimum time above which compilation time will be reported
1859 1866 tc_min = 0.1
1860 1867
1861 1868 t0 = clock()
1862 1869 code = compile(src, "<magic-timeit>", "exec")
1863 1870 tc = clock()-t0
1864 1871
1865 1872 ns = {}
1866 1873 exec code in self.shell.user_ns, ns
1867 1874 timer.inner = ns["inner"]
1868 1875
1869 1876 if number == 0:
1870 1877 # determine number so that 0.2 <= total time < 2.0
1871 1878 number = 1
1872 1879 for i in range(1, 10):
1873 1880 if timer.timeit(number) >= 0.2:
1874 1881 break
1875 1882 number *= 10
1876 1883
1877 1884 best = min(timer.repeat(repeat, number)) / number
1878 1885
1879 1886 if best > 0.0:
1880 1887 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1881 1888 else:
1882 1889 order = 3
1883 1890 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1884 1891 precision,
1885 1892 best * scaling[order],
1886 1893 units[order])
1887 1894 if tc > tc_min:
1888 1895 print "Compiler time: %.2f s" % tc
1889 1896
1890 1897 @testdec.skip_doctest
1891 1898 def magic_time(self,parameter_s = ''):
1892 1899 """Time execution of a Python statement or expression.
1893 1900
1894 1901 The CPU and wall clock times are printed, and the value of the
1895 1902 expression (if any) is returned. Note that under Win32, system time
1896 1903 is always reported as 0, since it can not be measured.
1897 1904
1898 1905 This function provides very basic timing functionality. In Python
1899 1906 2.3, the timeit module offers more control and sophistication, so this
1900 1907 could be rewritten to use it (patches welcome).
1901 1908
1902 1909 Some examples:
1903 1910
1904 1911 In [1]: time 2**128
1905 1912 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1906 1913 Wall time: 0.00
1907 1914 Out[1]: 340282366920938463463374607431768211456L
1908 1915
1909 1916 In [2]: n = 1000000
1910 1917
1911 1918 In [3]: time sum(range(n))
1912 1919 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1913 1920 Wall time: 1.37
1914 1921 Out[3]: 499999500000L
1915 1922
1916 1923 In [4]: time print 'hello world'
1917 1924 hello world
1918 1925 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1919 1926 Wall time: 0.00
1920 1927
1921 1928 Note that the time needed by Python to compile the given expression
1922 1929 will be reported if it is more than 0.1s. In this example, the
1923 1930 actual exponentiation is done by Python at compilation time, so while
1924 1931 the expression can take a noticeable amount of time to compute, that
1925 1932 time is purely due to the compilation:
1926 1933
1927 1934 In [5]: time 3**9999;
1928 1935 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1929 1936 Wall time: 0.00 s
1930 1937
1931 1938 In [6]: time 3**999999;
1932 1939 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1933 1940 Wall time: 0.00 s
1934 1941 Compiler : 0.78 s
1935 1942 """
1936 1943
1937 1944 # fail immediately if the given expression can't be compiled
1938 1945
1939 1946 expr = self.shell.prefilter(parameter_s,False)
1940 1947
1941 1948 # Minimum time above which compilation time will be reported
1942 1949 tc_min = 0.1
1943 1950
1944 1951 try:
1945 1952 mode = 'eval'
1946 1953 t0 = clock()
1947 1954 code = compile(expr,'<timed eval>',mode)
1948 1955 tc = clock()-t0
1949 1956 except SyntaxError:
1950 1957 mode = 'exec'
1951 1958 t0 = clock()
1952 1959 code = compile(expr,'<timed exec>',mode)
1953 1960 tc = clock()-t0
1954 1961 # skew measurement as little as possible
1955 1962 glob = self.shell.user_ns
1956 1963 clk = clock2
1957 1964 wtime = time.time
1958 1965 # time execution
1959 1966 wall_st = wtime()
1960 1967 if mode=='eval':
1961 1968 st = clk()
1962 1969 out = eval(code,glob)
1963 1970 end = clk()
1964 1971 else:
1965 1972 st = clk()
1966 1973 exec code in glob
1967 1974 end = clk()
1968 1975 out = None
1969 1976 wall_end = wtime()
1970 1977 # Compute actual times and report
1971 1978 wall_time = wall_end-wall_st
1972 1979 cpu_user = end[0]-st[0]
1973 1980 cpu_sys = end[1]-st[1]
1974 1981 cpu_tot = cpu_user+cpu_sys
1975 1982 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1976 1983 (cpu_user,cpu_sys,cpu_tot)
1977 1984 print "Wall time: %.2f s" % wall_time
1978 1985 if tc > tc_min:
1979 1986 print "Compiler : %.2f s" % tc
1980 1987 return out
1981 1988
1982 1989 @testdec.skip_doctest
1983 1990 def magic_macro(self,parameter_s = ''):
1984 1991 """Define a set of input lines as a macro for future re-execution.
1985 1992
1986 1993 Usage:\\
1987 1994 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1988 1995
1989 1996 Options:
1990 1997
1991 1998 -r: use 'raw' input. By default, the 'processed' history is used,
1992 1999 so that magics are loaded in their transformed version to valid
1993 2000 Python. If this option is given, the raw input as typed as the
1994 2001 command line is used instead.
1995 2002
1996 2003 This will define a global variable called `name` which is a string
1997 2004 made of joining the slices and lines you specify (n1,n2,... numbers
1998 2005 above) from your input history into a single string. This variable
1999 2006 acts like an automatic function which re-executes those lines as if
2000 2007 you had typed them. You just type 'name' at the prompt and the code
2001 2008 executes.
2002 2009
2003 2010 The notation for indicating number ranges is: n1-n2 means 'use line
2004 2011 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2005 2012 using the lines numbered 5,6 and 7.
2006 2013
2007 2014 Note: as a 'hidden' feature, you can also use traditional python slice
2008 2015 notation, where N:M means numbers N through M-1.
2009 2016
2010 2017 For example, if your history contains (%hist prints it):
2011 2018
2012 2019 44: x=1
2013 2020 45: y=3
2014 2021 46: z=x+y
2015 2022 47: print x
2016 2023 48: a=5
2017 2024 49: print 'x',x,'y',y
2018 2025
2019 2026 you can create a macro with lines 44 through 47 (included) and line 49
2020 2027 called my_macro with:
2021 2028
2022 2029 In [55]: %macro my_macro 44-47 49
2023 2030
2024 2031 Now, typing `my_macro` (without quotes) will re-execute all this code
2025 2032 in one pass.
2026 2033
2027 2034 You don't need to give the line-numbers in order, and any given line
2028 2035 number can appear multiple times. You can assemble macros with any
2029 2036 lines from your input history in any order.
2030 2037
2031 2038 The macro is a simple object which holds its value in an attribute,
2032 2039 but IPython's display system checks for macros and executes them as
2033 2040 code instead of printing them when you type their name.
2034 2041
2035 2042 You can view a macro's contents by explicitly printing it with:
2036 2043
2037 2044 'print macro_name'.
2038 2045
2039 2046 For one-off cases which DON'T contain magic function calls in them you
2040 2047 can obtain similar results by explicitly executing slices from your
2041 2048 input history with:
2042 2049
2043 2050 In [60]: exec In[44:48]+In[49]"""
2044 2051
2045 2052 opts,args = self.parse_options(parameter_s,'r',mode='list')
2046 2053 if not args:
2047 2054 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2048 2055 macs.sort()
2049 2056 return macs
2050 2057 if len(args) == 1:
2051 2058 raise UsageError(
2052 2059 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2053 2060 name,ranges = args[0], args[1:]
2054 2061
2055 2062 #print 'rng',ranges # dbg
2056 2063 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2057 2064 macro = Macro(lines)
2058 2065 self.shell.define_macro(name, macro)
2059 2066 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2060 2067 print 'Macro contents:'
2061 2068 print macro,
2062 2069
2063 2070 def magic_save(self,parameter_s = ''):
2064 2071 """Save a set of lines to a given filename.
2065 2072
2066 2073 Usage:\\
2067 2074 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2068 2075
2069 2076 Options:
2070 2077
2071 2078 -r: use 'raw' input. By default, the 'processed' history is used,
2072 2079 so that magics are loaded in their transformed version to valid
2073 2080 Python. If this option is given, the raw input as typed as the
2074 2081 command line is used instead.
2075 2082
2076 2083 This function uses the same syntax as %macro for line extraction, but
2077 2084 instead of creating a macro it saves the resulting string to the
2078 2085 filename you specify.
2079 2086
2080 2087 It adds a '.py' extension to the file if you don't do so yourself, and
2081 2088 it asks for confirmation before overwriting existing files."""
2082 2089
2083 2090 opts,args = self.parse_options(parameter_s,'r',mode='list')
2084 2091 fname,ranges = args[0], args[1:]
2085 2092 if not fname.endswith('.py'):
2086 2093 fname += '.py'
2087 2094 if os.path.isfile(fname):
2088 2095 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2089 2096 if ans.lower() not in ['y','yes']:
2090 2097 print 'Operation cancelled.'
2091 2098 return
2092 2099 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2093 2100 f = file(fname,'w')
2094 2101 f.write(cmds)
2095 2102 f.close()
2096 2103 print 'The following commands were written to file `%s`:' % fname
2097 2104 print cmds
2098 2105
2099 2106 def _edit_macro(self,mname,macro):
2100 2107 """open an editor with the macro data in a file"""
2101 2108 filename = self.shell.mktempfile(macro.value)
2102 2109 self.shell.hooks.editor(filename)
2103 2110
2104 2111 # and make a new macro object, to replace the old one
2105 2112 mfile = open(filename)
2106 2113 mvalue = mfile.read()
2107 2114 mfile.close()
2108 2115 self.shell.user_ns[mname] = Macro(mvalue)
2109 2116
2110 2117 def magic_ed(self,parameter_s=''):
2111 2118 """Alias to %edit."""
2112 2119 return self.magic_edit(parameter_s)
2113 2120
2114 2121 @testdec.skip_doctest
2115 2122 def magic_edit(self,parameter_s='',last_call=['','']):
2116 2123 """Bring up an editor and execute the resulting code.
2117 2124
2118 2125 Usage:
2119 2126 %edit [options] [args]
2120 2127
2121 2128 %edit runs IPython's editor hook. The default version of this hook is
2122 2129 set to call the __IPYTHON__.rc.editor command. This is read from your
2123 2130 environment variable $EDITOR. If this isn't found, it will default to
2124 2131 vi under Linux/Unix and to notepad under Windows. See the end of this
2125 2132 docstring for how to change the editor hook.
2126 2133
2127 2134 You can also set the value of this editor via the command line option
2128 2135 '-editor' or in your ipythonrc file. This is useful if you wish to use
2129 2136 specifically for IPython an editor different from your typical default
2130 2137 (and for Windows users who typically don't set environment variables).
2131 2138
2132 2139 This command allows you to conveniently edit multi-line code right in
2133 2140 your IPython session.
2134 2141
2135 2142 If called without arguments, %edit opens up an empty editor with a
2136 2143 temporary file and will execute the contents of this file when you
2137 2144 close it (don't forget to save it!).
2138 2145
2139 2146
2140 2147 Options:
2141 2148
2142 2149 -n <number>: open the editor at a specified line number. By default,
2143 2150 the IPython editor hook uses the unix syntax 'editor +N filename', but
2144 2151 you can configure this by providing your own modified hook if your
2145 2152 favorite editor supports line-number specifications with a different
2146 2153 syntax.
2147 2154
2148 2155 -p: this will call the editor with the same data as the previous time
2149 2156 it was used, regardless of how long ago (in your current session) it
2150 2157 was.
2151 2158
2152 2159 -r: use 'raw' input. This option only applies to input taken from the
2153 2160 user's history. By default, the 'processed' history is used, so that
2154 2161 magics are loaded in their transformed version to valid Python. If
2155 2162 this option is given, the raw input as typed as the command line is
2156 2163 used instead. When you exit the editor, it will be executed by
2157 2164 IPython's own processor.
2158 2165
2159 2166 -x: do not execute the edited code immediately upon exit. This is
2160 2167 mainly useful if you are editing programs which need to be called with
2161 2168 command line arguments, which you can then do using %run.
2162 2169
2163 2170
2164 2171 Arguments:
2165 2172
2166 2173 If arguments are given, the following possibilites exist:
2167 2174
2168 2175 - The arguments are numbers or pairs of colon-separated numbers (like
2169 2176 1 4:8 9). These are interpreted as lines of previous input to be
2170 2177 loaded into the editor. The syntax is the same of the %macro command.
2171 2178
2172 2179 - If the argument doesn't start with a number, it is evaluated as a
2173 2180 variable and its contents loaded into the editor. You can thus edit
2174 2181 any string which contains python code (including the result of
2175 2182 previous edits).
2176 2183
2177 2184 - If the argument is the name of an object (other than a string),
2178 2185 IPython will try to locate the file where it was defined and open the
2179 2186 editor at the point where it is defined. You can use `%edit function`
2180 2187 to load an editor exactly at the point where 'function' is defined,
2181 2188 edit it and have the file be executed automatically.
2182 2189
2183 2190 If the object is a macro (see %macro for details), this opens up your
2184 2191 specified editor with a temporary file containing the macro's data.
2185 2192 Upon exit, the macro is reloaded with the contents of the file.
2186 2193
2187 2194 Note: opening at an exact line is only supported under Unix, and some
2188 2195 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2189 2196 '+NUMBER' parameter necessary for this feature. Good editors like
2190 2197 (X)Emacs, vi, jed, pico and joe all do.
2191 2198
2192 2199 - If the argument is not found as a variable, IPython will look for a
2193 2200 file with that name (adding .py if necessary) and load it into the
2194 2201 editor. It will execute its contents with execfile() when you exit,
2195 2202 loading any code in the file into your interactive namespace.
2196 2203
2197 2204 After executing your code, %edit will return as output the code you
2198 2205 typed in the editor (except when it was an existing file). This way
2199 2206 you can reload the code in further invocations of %edit as a variable,
2200 2207 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2201 2208 the output.
2202 2209
2203 2210 Note that %edit is also available through the alias %ed.
2204 2211
2205 2212 This is an example of creating a simple function inside the editor and
2206 2213 then modifying it. First, start up the editor:
2207 2214
2208 2215 In [1]: ed
2209 2216 Editing... done. Executing edited code...
2210 2217 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2211 2218
2212 2219 We can then call the function foo():
2213 2220
2214 2221 In [2]: foo()
2215 2222 foo() was defined in an editing session
2216 2223
2217 2224 Now we edit foo. IPython automatically loads the editor with the
2218 2225 (temporary) file where foo() was previously defined:
2219 2226
2220 2227 In [3]: ed foo
2221 2228 Editing... done. Executing edited code...
2222 2229
2223 2230 And if we call foo() again we get the modified version:
2224 2231
2225 2232 In [4]: foo()
2226 2233 foo() has now been changed!
2227 2234
2228 2235 Here is an example of how to edit a code snippet successive
2229 2236 times. First we call the editor:
2230 2237
2231 2238 In [5]: ed
2232 2239 Editing... done. Executing edited code...
2233 2240 hello
2234 2241 Out[5]: "print 'hello'n"
2235 2242
2236 2243 Now we call it again with the previous output (stored in _):
2237 2244
2238 2245 In [6]: ed _
2239 2246 Editing... done. Executing edited code...
2240 2247 hello world
2241 2248 Out[6]: "print 'hello world'n"
2242 2249
2243 2250 Now we call it with the output #8 (stored in _8, also as Out[8]):
2244 2251
2245 2252 In [7]: ed _8
2246 2253 Editing... done. Executing edited code...
2247 2254 hello again
2248 2255 Out[7]: "print 'hello again'n"
2249 2256
2250 2257
2251 2258 Changing the default editor hook:
2252 2259
2253 2260 If you wish to write your own editor hook, you can put it in a
2254 2261 configuration file which you load at startup time. The default hook
2255 2262 is defined in the IPython.core.hooks module, and you can use that as a
2256 2263 starting example for further modifications. That file also has
2257 2264 general instructions on how to set a new hook for use once you've
2258 2265 defined it."""
2259 2266
2260 2267 # FIXME: This function has become a convoluted mess. It needs a
2261 2268 # ground-up rewrite with clean, simple logic.
2262 2269
2263 2270 def make_filename(arg):
2264 2271 "Make a filename from the given args"
2265 2272 try:
2266 2273 filename = get_py_filename(arg)
2267 2274 except IOError:
2268 2275 if args.endswith('.py'):
2269 2276 filename = arg
2270 2277 else:
2271 2278 filename = None
2272 2279 return filename
2273 2280
2274 2281 # custom exceptions
2275 2282 class DataIsObject(Exception): pass
2276 2283
2277 2284 opts,args = self.parse_options(parameter_s,'prxn:')
2278 2285 # Set a few locals from the options for convenience:
2279 2286 opts_p = opts.has_key('p')
2280 2287 opts_r = opts.has_key('r')
2281 2288
2282 2289 # Default line number value
2283 2290 lineno = opts.get('n',None)
2284 2291
2285 2292 if opts_p:
2286 2293 args = '_%s' % last_call[0]
2287 2294 if not self.shell.user_ns.has_key(args):
2288 2295 args = last_call[1]
2289 2296
2290 2297 # use last_call to remember the state of the previous call, but don't
2291 2298 # let it be clobbered by successive '-p' calls.
2292 2299 try:
2293 2300 last_call[0] = self.shell.outputcache.prompt_count
2294 2301 if not opts_p:
2295 2302 last_call[1] = parameter_s
2296 2303 except:
2297 2304 pass
2298 2305
2299 2306 # by default this is done with temp files, except when the given
2300 2307 # arg is a filename
2301 2308 use_temp = 1
2302 2309
2303 2310 if re.match(r'\d',args):
2304 2311 # Mode where user specifies ranges of lines, like in %macro.
2305 2312 # This means that you can't edit files whose names begin with
2306 2313 # numbers this way. Tough.
2307 2314 ranges = args.split()
2308 2315 data = ''.join(self.extract_input_slices(ranges,opts_r))
2309 2316 elif args.endswith('.py'):
2310 2317 filename = make_filename(args)
2311 2318 data = ''
2312 2319 use_temp = 0
2313 2320 elif args:
2314 2321 try:
2315 2322 # Load the parameter given as a variable. If not a string,
2316 2323 # process it as an object instead (below)
2317 2324
2318 2325 #print '*** args',args,'type',type(args) # dbg
2319 2326 data = eval(args,self.shell.user_ns)
2320 2327 if not type(data) in StringTypes:
2321 2328 raise DataIsObject
2322 2329
2323 2330 except (NameError,SyntaxError):
2324 2331 # given argument is not a variable, try as a filename
2325 2332 filename = make_filename(args)
2326 2333 if filename is None:
2327 2334 warn("Argument given (%s) can't be found as a variable "
2328 2335 "or as a filename." % args)
2329 2336 return
2330 2337
2331 2338 data = ''
2332 2339 use_temp = 0
2333 2340 except DataIsObject:
2334 2341
2335 2342 # macros have a special edit function
2336 2343 if isinstance(data,Macro):
2337 2344 self._edit_macro(args,data)
2338 2345 return
2339 2346
2340 2347 # For objects, try to edit the file where they are defined
2341 2348 try:
2342 2349 filename = inspect.getabsfile(data)
2343 2350 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2344 2351 # class created by %edit? Try to find source
2345 2352 # by looking for method definitions instead, the
2346 2353 # __module__ in those classes is FakeModule.
2347 2354 attrs = [getattr(data, aname) for aname in dir(data)]
2348 2355 for attr in attrs:
2349 2356 if not inspect.ismethod(attr):
2350 2357 continue
2351 2358 filename = inspect.getabsfile(attr)
2352 2359 if filename and 'fakemodule' not in filename.lower():
2353 2360 # change the attribute to be the edit target instead
2354 2361 data = attr
2355 2362 break
2356 2363
2357 2364 datafile = 1
2358 2365 except TypeError:
2359 2366 filename = make_filename(args)
2360 2367 datafile = 1
2361 2368 warn('Could not find file where `%s` is defined.\n'
2362 2369 'Opening a file named `%s`' % (args,filename))
2363 2370 # Now, make sure we can actually read the source (if it was in
2364 2371 # a temp file it's gone by now).
2365 2372 if datafile:
2366 2373 try:
2367 2374 if lineno is None:
2368 2375 lineno = inspect.getsourcelines(data)[1]
2369 2376 except IOError:
2370 2377 filename = make_filename(args)
2371 2378 if filename is None:
2372 2379 warn('The file `%s` where `%s` was defined cannot '
2373 2380 'be read.' % (filename,data))
2374 2381 return
2375 2382 use_temp = 0
2376 2383 else:
2377 2384 data = ''
2378 2385
2379 2386 if use_temp:
2380 2387 filename = self.shell.mktempfile(data)
2381 2388 print 'IPython will make a temporary file named:',filename
2382 2389
2383 2390 # do actual editing here
2384 2391 print 'Editing...',
2385 2392 sys.stdout.flush()
2386 2393 try:
2387 2394 self.shell.hooks.editor(filename,lineno)
2388 2395 except TryNext:
2389 2396 warn('Could not open editor')
2390 2397 return
2391 2398
2392 2399 # XXX TODO: should this be generalized for all string vars?
2393 2400 # For now, this is special-cased to blocks created by cpaste
2394 2401 if args.strip() == 'pasted_block':
2395 2402 self.shell.user_ns['pasted_block'] = file_read(filename)
2396 2403
2397 2404 if opts.has_key('x'): # -x prevents actual execution
2398 2405 print
2399 2406 else:
2400 2407 print 'done. Executing edited code...'
2401 2408 if opts_r:
2402 2409 self.shell.runlines(file_read(filename))
2403 2410 else:
2404 2411 self.shell.safe_execfile(filename,self.shell.user_ns,
2405 2412 self.shell.user_ns)
2406 2413
2407 2414
2408 2415 if use_temp:
2409 2416 try:
2410 2417 return open(filename).read()
2411 2418 except IOError,msg:
2412 2419 if msg.filename == filename:
2413 2420 warn('File not found. Did you forget to save?')
2414 2421 return
2415 2422 else:
2416 2423 self.shell.showtraceback()
2417 2424
2418 2425 def magic_xmode(self,parameter_s = ''):
2419 2426 """Switch modes for the exception handlers.
2420 2427
2421 2428 Valid modes: Plain, Context and Verbose.
2422 2429
2423 2430 If called without arguments, acts as a toggle."""
2424 2431
2425 2432 def xmode_switch_err(name):
2426 2433 warn('Error changing %s exception modes.\n%s' %
2427 2434 (name,sys.exc_info()[1]))
2428 2435
2429 2436 shell = self.shell
2430 2437 new_mode = parameter_s.strip().capitalize()
2431 2438 try:
2432 2439 shell.InteractiveTB.set_mode(mode=new_mode)
2433 2440 print 'Exception reporting mode:',shell.InteractiveTB.mode
2434 2441 except:
2435 2442 xmode_switch_err('user')
2436 2443
2437 2444 # threaded shells use a special handler in sys.excepthook
2438 2445 if shell.isthreaded:
2439 2446 try:
2440 2447 shell.sys_excepthook.set_mode(mode=new_mode)
2441 2448 except:
2442 2449 xmode_switch_err('threaded')
2443 2450
2444 2451 def magic_colors(self,parameter_s = ''):
2445 2452 """Switch color scheme for prompts, info system and exception handlers.
2446 2453
2447 2454 Currently implemented schemes: NoColor, Linux, LightBG.
2448 2455
2449 2456 Color scheme names are not case-sensitive."""
2450 2457
2451 2458 def color_switch_err(name):
2452 2459 warn('Error changing %s color schemes.\n%s' %
2453 2460 (name,sys.exc_info()[1]))
2454 2461
2455 2462
2456 2463 new_scheme = parameter_s.strip()
2457 2464 if not new_scheme:
2458 2465 raise UsageError(
2459 2466 "%colors: you must specify a color scheme. See '%colors?'")
2460 2467 return
2461 2468 # local shortcut
2462 2469 shell = self.shell
2463 2470
2464 2471 import IPython.utils.rlineimpl as readline
2465 2472
2466 2473 if not readline.have_readline and sys.platform == "win32":
2467 2474 msg = """\
2468 2475 Proper color support under MS Windows requires the pyreadline library.
2469 2476 You can find it at:
2470 2477 http://ipython.scipy.org/moin/PyReadline/Intro
2471 2478 Gary's readline needs the ctypes module, from:
2472 2479 http://starship.python.net/crew/theller/ctypes
2473 2480 (Note that ctypes is already part of Python versions 2.5 and newer).
2474 2481
2475 2482 Defaulting color scheme to 'NoColor'"""
2476 2483 new_scheme = 'NoColor'
2477 2484 warn(msg)
2478 2485
2479 2486 # readline option is 0
2480 2487 if not shell.has_readline:
2481 2488 new_scheme = 'NoColor'
2482 2489
2483 2490 # Set prompt colors
2484 2491 try:
2485 2492 shell.outputcache.set_colors(new_scheme)
2486 2493 except:
2487 2494 color_switch_err('prompt')
2488 2495 else:
2489 2496 shell.colors = \
2490 2497 shell.outputcache.color_table.active_scheme_name
2491 2498 # Set exception colors
2492 2499 try:
2493 2500 shell.InteractiveTB.set_colors(scheme = new_scheme)
2494 2501 shell.SyntaxTB.set_colors(scheme = new_scheme)
2495 2502 except:
2496 2503 color_switch_err('exception')
2497 2504
2498 2505 # threaded shells use a verbose traceback in sys.excepthook
2499 2506 if shell.isthreaded:
2500 2507 try:
2501 2508 shell.sys_excepthook.set_colors(scheme=new_scheme)
2502 2509 except:
2503 2510 color_switch_err('system exception handler')
2504 2511
2505 2512 # Set info (for 'object?') colors
2506 2513 if shell.color_info:
2507 2514 try:
2508 2515 shell.inspector.set_active_scheme(new_scheme)
2509 2516 except:
2510 2517 color_switch_err('object inspector')
2511 2518 else:
2512 2519 shell.inspector.set_active_scheme('NoColor')
2513 2520
2514 2521 def magic_color_info(self,parameter_s = ''):
2515 2522 """Toggle color_info.
2516 2523
2517 2524 The color_info configuration parameter controls whether colors are
2518 2525 used for displaying object details (by things like %psource, %pfile or
2519 2526 the '?' system). This function toggles this value with each call.
2520 2527
2521 2528 Note that unless you have a fairly recent pager (less works better
2522 2529 than more) in your system, using colored object information displays
2523 2530 will not work properly. Test it and see."""
2524 2531
2525 2532 self.shell.color_info = not self.shell.color_info
2526 2533 self.magic_colors(self.shell.colors)
2527 2534 print 'Object introspection functions have now coloring:',
2528 2535 print ['OFF','ON'][int(self.shell.color_info)]
2529 2536
2530 2537 def magic_Pprint(self, parameter_s=''):
2531 2538 """Toggle pretty printing on/off."""
2532 2539
2533 2540 self.shell.pprint = 1 - self.shell.pprint
2534 2541 print 'Pretty printing has been turned', \
2535 2542 ['OFF','ON'][self.shell.pprint]
2536 2543
2537 2544 def magic_Exit(self, parameter_s=''):
2538 2545 """Exit IPython without confirmation."""
2539 2546
2540 2547 self.shell.ask_exit()
2541 2548
2542 2549 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2543 2550 magic_exit = magic_quit = magic_Quit = magic_Exit
2544 2551
2545 2552 #......................................................................
2546 2553 # Functions to implement unix shell-type things
2547 2554
2548 2555 @testdec.skip_doctest
2549 2556 def magic_alias(self, parameter_s = ''):
2550 2557 """Define an alias for a system command.
2551 2558
2552 2559 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2553 2560
2554 2561 Then, typing 'alias_name params' will execute the system command 'cmd
2555 2562 params' (from your underlying operating system).
2556 2563
2557 2564 Aliases have lower precedence than magic functions and Python normal
2558 2565 variables, so if 'foo' is both a Python variable and an alias, the
2559 2566 alias can not be executed until 'del foo' removes the Python variable.
2560 2567
2561 2568 You can use the %l specifier in an alias definition to represent the
2562 2569 whole line when the alias is called. For example:
2563 2570
2564 2571 In [2]: alias all echo "Input in brackets: <%l>"
2565 2572 In [3]: all hello world
2566 2573 Input in brackets: <hello world>
2567 2574
2568 2575 You can also define aliases with parameters using %s specifiers (one
2569 2576 per parameter):
2570 2577
2571 2578 In [1]: alias parts echo first %s second %s
2572 2579 In [2]: %parts A B
2573 2580 first A second B
2574 2581 In [3]: %parts A
2575 2582 Incorrect number of arguments: 2 expected.
2576 2583 parts is an alias to: 'echo first %s second %s'
2577 2584
2578 2585 Note that %l and %s are mutually exclusive. You can only use one or
2579 2586 the other in your aliases.
2580 2587
2581 2588 Aliases expand Python variables just like system calls using ! or !!
2582 2589 do: all expressions prefixed with '$' get expanded. For details of
2583 2590 the semantic rules, see PEP-215:
2584 2591 http://www.python.org/peps/pep-0215.html. This is the library used by
2585 2592 IPython for variable expansion. If you want to access a true shell
2586 2593 variable, an extra $ is necessary to prevent its expansion by IPython:
2587 2594
2588 2595 In [6]: alias show echo
2589 2596 In [7]: PATH='A Python string'
2590 2597 In [8]: show $PATH
2591 2598 A Python string
2592 2599 In [9]: show $$PATH
2593 2600 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2594 2601
2595 2602 You can use the alias facility to acess all of $PATH. See the %rehash
2596 2603 and %rehashx functions, which automatically create aliases for the
2597 2604 contents of your $PATH.
2598 2605
2599 2606 If called with no parameters, %alias prints the current alias table."""
2600 2607
2601 2608 par = parameter_s.strip()
2602 2609 if not par:
2603 2610 stored = self.db.get('stored_aliases', {} )
2604 2611 aliases = sorted(self.shell.alias_manager.aliases)
2605 2612 # for k, v in stored:
2606 2613 # atab.append(k, v[0])
2607 2614
2608 2615 print "Total number of aliases:", len(aliases)
2609 2616 return aliases
2610 2617
2611 2618 # Now try to define a new one
2612 2619 try:
2613 2620 alias,cmd = par.split(None, 1)
2614 2621 except:
2615 2622 print oinspect.getdoc(self.magic_alias)
2616 2623 else:
2617 2624 self.shell.alias_manager.soft_define_alias(alias, cmd)
2618 2625 # end magic_alias
2619 2626
2620 2627 def magic_unalias(self, parameter_s = ''):
2621 2628 """Remove an alias"""
2622 2629
2623 2630 aname = parameter_s.strip()
2624 2631 self.shell.alias_manager.undefine_alias(aname)
2625 2632 stored = self.db.get('stored_aliases', {} )
2626 2633 if aname in stored:
2627 2634 print "Removing %stored alias",aname
2628 2635 del stored[aname]
2629 2636 self.db['stored_aliases'] = stored
2630 2637
2631 2638
2632 2639 def magic_rehashx(self, parameter_s = ''):
2633 2640 """Update the alias table with all executable files in $PATH.
2634 2641
2635 2642 This version explicitly checks that every entry in $PATH is a file
2636 2643 with execute access (os.X_OK), so it is much slower than %rehash.
2637 2644
2638 2645 Under Windows, it checks executability as a match agains a
2639 2646 '|'-separated string of extensions, stored in the IPython config
2640 2647 variable win_exec_ext. This defaults to 'exe|com|bat'.
2641 2648
2642 2649 This function also resets the root module cache of module completer,
2643 2650 used on slow filesystems.
2644 2651 """
2645 2652 from IPython.core.alias import InvalidAliasError
2646 2653
2647 2654 # for the benefit of module completer in ipy_completers.py
2648 2655 del self.db['rootmodules']
2649 2656
2650 2657 path = [os.path.abspath(os.path.expanduser(p)) for p in
2651 2658 os.environ.get('PATH','').split(os.pathsep)]
2652 2659 path = filter(os.path.isdir,path)
2653 2660
2654 2661 syscmdlist = []
2655 2662 # Now define isexec in a cross platform manner.
2656 2663 if os.name == 'posix':
2657 2664 isexec = lambda fname:os.path.isfile(fname) and \
2658 2665 os.access(fname,os.X_OK)
2659 2666 else:
2660 2667 try:
2661 2668 winext = os.environ['pathext'].replace(';','|').replace('.','')
2662 2669 except KeyError:
2663 2670 winext = 'exe|com|bat|py'
2664 2671 if 'py' not in winext:
2665 2672 winext += '|py'
2666 2673 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2667 2674 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2668 2675 savedir = os.getcwd()
2669 2676
2670 2677 # Now walk the paths looking for executables to alias.
2671 2678 try:
2672 2679 # write the whole loop for posix/Windows so we don't have an if in
2673 2680 # the innermost part
2674 2681 if os.name == 'posix':
2675 2682 for pdir in path:
2676 2683 os.chdir(pdir)
2677 2684 for ff in os.listdir(pdir):
2678 2685 if isexec(ff):
2679 2686 try:
2680 2687 # Removes dots from the name since ipython
2681 2688 # will assume names with dots to be python.
2682 2689 self.shell.alias_manager.define_alias(
2683 2690 ff.replace('.',''), ff)
2684 2691 except InvalidAliasError:
2685 2692 pass
2686 2693 else:
2687 2694 syscmdlist.append(ff)
2688 2695 else:
2689 2696 no_alias = self.shell.alias_manager.no_alias
2690 2697 for pdir in path:
2691 2698 os.chdir(pdir)
2692 2699 for ff in os.listdir(pdir):
2693 2700 base, ext = os.path.splitext(ff)
2694 2701 if isexec(ff) and base.lower() not in no_alias:
2695 2702 if ext.lower() == '.exe':
2696 2703 ff = base
2697 2704 try:
2698 2705 # Removes dots from the name since ipython
2699 2706 # will assume names with dots to be python.
2700 2707 self.shell.alias_manager.define_alias(
2701 2708 base.lower().replace('.',''), ff)
2702 2709 except InvalidAliasError:
2703 2710 pass
2704 2711 syscmdlist.append(ff)
2705 2712 db = self.db
2706 2713 db['syscmdlist'] = syscmdlist
2707 2714 finally:
2708 2715 os.chdir(savedir)
2709 2716
2710 2717 def magic_pwd(self, parameter_s = ''):
2711 2718 """Return the current working directory path."""
2712 2719 return os.getcwd()
2713 2720
2714 2721 def magic_cd(self, parameter_s=''):
2715 2722 """Change the current working directory.
2716 2723
2717 2724 This command automatically maintains an internal list of directories
2718 2725 you visit during your IPython session, in the variable _dh. The
2719 2726 command %dhist shows this history nicely formatted. You can also
2720 2727 do 'cd -<tab>' to see directory history conveniently.
2721 2728
2722 2729 Usage:
2723 2730
2724 2731 cd 'dir': changes to directory 'dir'.
2725 2732
2726 2733 cd -: changes to the last visited directory.
2727 2734
2728 2735 cd -<n>: changes to the n-th directory in the directory history.
2729 2736
2730 2737 cd --foo: change to directory that matches 'foo' in history
2731 2738
2732 2739 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2733 2740 (note: cd <bookmark_name> is enough if there is no
2734 2741 directory <bookmark_name>, but a bookmark with the name exists.)
2735 2742 'cd -b <tab>' allows you to tab-complete bookmark names.
2736 2743
2737 2744 Options:
2738 2745
2739 2746 -q: quiet. Do not print the working directory after the cd command is
2740 2747 executed. By default IPython's cd command does print this directory,
2741 2748 since the default prompts do not display path information.
2742 2749
2743 2750 Note that !cd doesn't work for this purpose because the shell where
2744 2751 !command runs is immediately discarded after executing 'command'."""
2745 2752
2746 2753 parameter_s = parameter_s.strip()
2747 2754 #bkms = self.shell.persist.get("bookmarks",{})
2748 2755
2749 2756 oldcwd = os.getcwd()
2750 2757 numcd = re.match(r'(-)(\d+)$',parameter_s)
2751 2758 # jump in directory history by number
2752 2759 if numcd:
2753 2760 nn = int(numcd.group(2))
2754 2761 try:
2755 2762 ps = self.shell.user_ns['_dh'][nn]
2756 2763 except IndexError:
2757 2764 print 'The requested directory does not exist in history.'
2758 2765 return
2759 2766 else:
2760 2767 opts = {}
2761 2768 elif parameter_s.startswith('--'):
2762 2769 ps = None
2763 2770 fallback = None
2764 2771 pat = parameter_s[2:]
2765 2772 dh = self.shell.user_ns['_dh']
2766 2773 # first search only by basename (last component)
2767 2774 for ent in reversed(dh):
2768 2775 if pat in os.path.basename(ent) and os.path.isdir(ent):
2769 2776 ps = ent
2770 2777 break
2771 2778
2772 2779 if fallback is None and pat in ent and os.path.isdir(ent):
2773 2780 fallback = ent
2774 2781
2775 2782 # if we have no last part match, pick the first full path match
2776 2783 if ps is None:
2777 2784 ps = fallback
2778 2785
2779 2786 if ps is None:
2780 2787 print "No matching entry in directory history"
2781 2788 return
2782 2789 else:
2783 2790 opts = {}
2784 2791
2785 2792
2786 2793 else:
2787 2794 #turn all non-space-escaping backslashes to slashes,
2788 2795 # for c:\windows\directory\names\
2789 2796 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2790 2797 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2791 2798 # jump to previous
2792 2799 if ps == '-':
2793 2800 try:
2794 2801 ps = self.shell.user_ns['_dh'][-2]
2795 2802 except IndexError:
2796 2803 raise UsageError('%cd -: No previous directory to change to.')
2797 2804 # jump to bookmark if needed
2798 2805 else:
2799 2806 if not os.path.isdir(ps) or opts.has_key('b'):
2800 2807 bkms = self.db.get('bookmarks', {})
2801 2808
2802 2809 if bkms.has_key(ps):
2803 2810 target = bkms[ps]
2804 2811 print '(bookmark:%s) -> %s' % (ps,target)
2805 2812 ps = target
2806 2813 else:
2807 2814 if opts.has_key('b'):
2808 2815 raise UsageError("Bookmark '%s' not found. "
2809 2816 "Use '%%bookmark -l' to see your bookmarks." % ps)
2810 2817
2811 2818 # at this point ps should point to the target dir
2812 2819 if ps:
2813 2820 try:
2814 2821 os.chdir(os.path.expanduser(ps))
2815 2822 if self.shell.term_title:
2816 2823 set_term_title('IPython: ' + abbrev_cwd())
2817 2824 except OSError:
2818 2825 print sys.exc_info()[1]
2819 2826 else:
2820 2827 cwd = os.getcwd()
2821 2828 dhist = self.shell.user_ns['_dh']
2822 2829 if oldcwd != cwd:
2823 2830 dhist.append(cwd)
2824 2831 self.db['dhist'] = compress_dhist(dhist)[-100:]
2825 2832
2826 2833 else:
2827 2834 os.chdir(self.shell.home_dir)
2828 2835 if self.shell.term_title:
2829 2836 set_term_title('IPython: ' + '~')
2830 2837 cwd = os.getcwd()
2831 2838 dhist = self.shell.user_ns['_dh']
2832 2839
2833 2840 if oldcwd != cwd:
2834 2841 dhist.append(cwd)
2835 2842 self.db['dhist'] = compress_dhist(dhist)[-100:]
2836 2843 if not 'q' in opts and self.shell.user_ns['_dh']:
2837 2844 print self.shell.user_ns['_dh'][-1]
2838 2845
2839 2846
2840 2847 def magic_env(self, parameter_s=''):
2841 2848 """List environment variables."""
2842 2849
2843 2850 return os.environ.data
2844 2851
2845 2852 def magic_pushd(self, parameter_s=''):
2846 2853 """Place the current dir on stack and change directory.
2847 2854
2848 2855 Usage:\\
2849 2856 %pushd ['dirname']
2850 2857 """
2851 2858
2852 2859 dir_s = self.shell.dir_stack
2853 2860 tgt = os.path.expanduser(parameter_s)
2854 2861 cwd = os.getcwd().replace(self.home_dir,'~')
2855 2862 if tgt:
2856 2863 self.magic_cd(parameter_s)
2857 2864 dir_s.insert(0,cwd)
2858 2865 return self.magic_dirs()
2859 2866
2860 2867 def magic_popd(self, parameter_s=''):
2861 2868 """Change to directory popped off the top of the stack.
2862 2869 """
2863 2870 if not self.shell.dir_stack:
2864 2871 raise UsageError("%popd on empty stack")
2865 2872 top = self.shell.dir_stack.pop(0)
2866 2873 self.magic_cd(top)
2867 2874 print "popd ->",top
2868 2875
2869 2876 def magic_dirs(self, parameter_s=''):
2870 2877 """Return the current directory stack."""
2871 2878
2872 2879 return self.shell.dir_stack
2873 2880
2874 2881 def magic_dhist(self, parameter_s=''):
2875 2882 """Print your history of visited directories.
2876 2883
2877 2884 %dhist -> print full history\\
2878 2885 %dhist n -> print last n entries only\\
2879 2886 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2880 2887
2881 2888 This history is automatically maintained by the %cd command, and
2882 2889 always available as the global list variable _dh. You can use %cd -<n>
2883 2890 to go to directory number <n>.
2884 2891
2885 2892 Note that most of time, you should view directory history by entering
2886 2893 cd -<TAB>.
2887 2894
2888 2895 """
2889 2896
2890 2897 dh = self.shell.user_ns['_dh']
2891 2898 if parameter_s:
2892 2899 try:
2893 2900 args = map(int,parameter_s.split())
2894 2901 except:
2895 2902 self.arg_err(Magic.magic_dhist)
2896 2903 return
2897 2904 if len(args) == 1:
2898 2905 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2899 2906 elif len(args) == 2:
2900 2907 ini,fin = args
2901 2908 else:
2902 2909 self.arg_err(Magic.magic_dhist)
2903 2910 return
2904 2911 else:
2905 2912 ini,fin = 0,len(dh)
2906 2913 nlprint(dh,
2907 2914 header = 'Directory history (kept in _dh)',
2908 2915 start=ini,stop=fin)
2909 2916
2910 2917 @testdec.skip_doctest
2911 2918 def magic_sc(self, parameter_s=''):
2912 2919 """Shell capture - execute a shell command and capture its output.
2913 2920
2914 2921 DEPRECATED. Suboptimal, retained for backwards compatibility.
2915 2922
2916 2923 You should use the form 'var = !command' instead. Example:
2917 2924
2918 2925 "%sc -l myfiles = ls ~" should now be written as
2919 2926
2920 2927 "myfiles = !ls ~"
2921 2928
2922 2929 myfiles.s, myfiles.l and myfiles.n still apply as documented
2923 2930 below.
2924 2931
2925 2932 --
2926 2933 %sc [options] varname=command
2927 2934
2928 2935 IPython will run the given command using commands.getoutput(), and
2929 2936 will then update the user's interactive namespace with a variable
2930 2937 called varname, containing the value of the call. Your command can
2931 2938 contain shell wildcards, pipes, etc.
2932 2939
2933 2940 The '=' sign in the syntax is mandatory, and the variable name you
2934 2941 supply must follow Python's standard conventions for valid names.
2935 2942
2936 2943 (A special format without variable name exists for internal use)
2937 2944
2938 2945 Options:
2939 2946
2940 2947 -l: list output. Split the output on newlines into a list before
2941 2948 assigning it to the given variable. By default the output is stored
2942 2949 as a single string.
2943 2950
2944 2951 -v: verbose. Print the contents of the variable.
2945 2952
2946 2953 In most cases you should not need to split as a list, because the
2947 2954 returned value is a special type of string which can automatically
2948 2955 provide its contents either as a list (split on newlines) or as a
2949 2956 space-separated string. These are convenient, respectively, either
2950 2957 for sequential processing or to be passed to a shell command.
2951 2958
2952 2959 For example:
2953 2960
2954 2961 # all-random
2955 2962
2956 2963 # Capture into variable a
2957 2964 In [1]: sc a=ls *py
2958 2965
2959 2966 # a is a string with embedded newlines
2960 2967 In [2]: a
2961 2968 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2962 2969
2963 2970 # which can be seen as a list:
2964 2971 In [3]: a.l
2965 2972 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2966 2973
2967 2974 # or as a whitespace-separated string:
2968 2975 In [4]: a.s
2969 2976 Out[4]: 'setup.py win32_manual_post_install.py'
2970 2977
2971 2978 # a.s is useful to pass as a single command line:
2972 2979 In [5]: !wc -l $a.s
2973 2980 146 setup.py
2974 2981 130 win32_manual_post_install.py
2975 2982 276 total
2976 2983
2977 2984 # while the list form is useful to loop over:
2978 2985 In [6]: for f in a.l:
2979 2986 ...: !wc -l $f
2980 2987 ...:
2981 2988 146 setup.py
2982 2989 130 win32_manual_post_install.py
2983 2990
2984 2991 Similiarly, the lists returned by the -l option are also special, in
2985 2992 the sense that you can equally invoke the .s attribute on them to
2986 2993 automatically get a whitespace-separated string from their contents:
2987 2994
2988 2995 In [7]: sc -l b=ls *py
2989 2996
2990 2997 In [8]: b
2991 2998 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2992 2999
2993 3000 In [9]: b.s
2994 3001 Out[9]: 'setup.py win32_manual_post_install.py'
2995 3002
2996 3003 In summary, both the lists and strings used for ouptut capture have
2997 3004 the following special attributes:
2998 3005
2999 3006 .l (or .list) : value as list.
3000 3007 .n (or .nlstr): value as newline-separated string.
3001 3008 .s (or .spstr): value as space-separated string.
3002 3009 """
3003 3010
3004 3011 opts,args = self.parse_options(parameter_s,'lv')
3005 3012 # Try to get a variable name and command to run
3006 3013 try:
3007 3014 # the variable name must be obtained from the parse_options
3008 3015 # output, which uses shlex.split to strip options out.
3009 3016 var,_ = args.split('=',1)
3010 3017 var = var.strip()
3011 3018 # But the the command has to be extracted from the original input
3012 3019 # parameter_s, not on what parse_options returns, to avoid the
3013 3020 # quote stripping which shlex.split performs on it.
3014 3021 _,cmd = parameter_s.split('=',1)
3015 3022 except ValueError:
3016 3023 var,cmd = '',''
3017 3024 # If all looks ok, proceed
3018 3025 out,err = self.shell.getoutputerror(cmd)
3019 3026 if err:
3020 3027 print >> Term.cerr,err
3021 3028 if opts.has_key('l'):
3022 3029 out = SList(out.split('\n'))
3023 3030 else:
3024 3031 out = LSString(out)
3025 3032 if opts.has_key('v'):
3026 3033 print '%s ==\n%s' % (var,pformat(out))
3027 3034 if var:
3028 3035 self.shell.user_ns.update({var:out})
3029 3036 else:
3030 3037 return out
3031 3038
3032 3039 def magic_sx(self, parameter_s=''):
3033 3040 """Shell execute - run a shell command and capture its output.
3034 3041
3035 3042 %sx command
3036 3043
3037 3044 IPython will run the given command using commands.getoutput(), and
3038 3045 return the result formatted as a list (split on '\\n'). Since the
3039 3046 output is _returned_, it will be stored in ipython's regular output
3040 3047 cache Out[N] and in the '_N' automatic variables.
3041 3048
3042 3049 Notes:
3043 3050
3044 3051 1) If an input line begins with '!!', then %sx is automatically
3045 3052 invoked. That is, while:
3046 3053 !ls
3047 3054 causes ipython to simply issue system('ls'), typing
3048 3055 !!ls
3049 3056 is a shorthand equivalent to:
3050 3057 %sx ls
3051 3058
3052 3059 2) %sx differs from %sc in that %sx automatically splits into a list,
3053 3060 like '%sc -l'. The reason for this is to make it as easy as possible
3054 3061 to process line-oriented shell output via further python commands.
3055 3062 %sc is meant to provide much finer control, but requires more
3056 3063 typing.
3057 3064
3058 3065 3) Just like %sc -l, this is a list with special attributes:
3059 3066
3060 3067 .l (or .list) : value as list.
3061 3068 .n (or .nlstr): value as newline-separated string.
3062 3069 .s (or .spstr): value as whitespace-separated string.
3063 3070
3064 3071 This is very useful when trying to use such lists as arguments to
3065 3072 system commands."""
3066 3073
3067 3074 if parameter_s:
3068 3075 out,err = self.shell.getoutputerror(parameter_s)
3069 3076 if err:
3070 3077 print >> Term.cerr,err
3071 3078 return SList(out.split('\n'))
3072 3079
3073 3080 def magic_bg(self, parameter_s=''):
3074 3081 """Run a job in the background, in a separate thread.
3075 3082
3076 3083 For example,
3077 3084
3078 3085 %bg myfunc(x,y,z=1)
3079 3086
3080 3087 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3081 3088 execution starts, a message will be printed indicating the job
3082 3089 number. If your job number is 5, you can use
3083 3090
3084 3091 myvar = jobs.result(5) or myvar = jobs[5].result
3085 3092
3086 3093 to assign this result to variable 'myvar'.
3087 3094
3088 3095 IPython has a job manager, accessible via the 'jobs' object. You can
3089 3096 type jobs? to get more information about it, and use jobs.<TAB> to see
3090 3097 its attributes. All attributes not starting with an underscore are
3091 3098 meant for public use.
3092 3099
3093 3100 In particular, look at the jobs.new() method, which is used to create
3094 3101 new jobs. This magic %bg function is just a convenience wrapper
3095 3102 around jobs.new(), for expression-based jobs. If you want to create a
3096 3103 new job with an explicit function object and arguments, you must call
3097 3104 jobs.new() directly.
3098 3105
3099 3106 The jobs.new docstring also describes in detail several important
3100 3107 caveats associated with a thread-based model for background job
3101 3108 execution. Type jobs.new? for details.
3102 3109
3103 3110 You can check the status of all jobs with jobs.status().
3104 3111
3105 3112 The jobs variable is set by IPython into the Python builtin namespace.
3106 3113 If you ever declare a variable named 'jobs', you will shadow this
3107 3114 name. You can either delete your global jobs variable to regain
3108 3115 access to the job manager, or make a new name and assign it manually
3109 3116 to the manager (stored in IPython's namespace). For example, to
3110 3117 assign the job manager to the Jobs name, use:
3111 3118
3112 3119 Jobs = __builtins__.jobs"""
3113 3120
3114 3121 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3115 3122
3116 3123 def magic_r(self, parameter_s=''):
3117 3124 """Repeat previous input.
3118 3125
3119 3126 Note: Consider using the more powerfull %rep instead!
3120 3127
3121 3128 If given an argument, repeats the previous command which starts with
3122 3129 the same string, otherwise it just repeats the previous input.
3123 3130
3124 3131 Shell escaped commands (with ! as first character) are not recognized
3125 3132 by this system, only pure python code and magic commands.
3126 3133 """
3127 3134
3128 3135 start = parameter_s.strip()
3129 3136 esc_magic = ESC_MAGIC
3130 3137 # Identify magic commands even if automagic is on (which means
3131 3138 # the in-memory version is different from that typed by the user).
3132 3139 if self.shell.automagic:
3133 3140 start_magic = esc_magic+start
3134 3141 else:
3135 3142 start_magic = start
3136 3143 # Look through the input history in reverse
3137 3144 for n in range(len(self.shell.input_hist)-2,0,-1):
3138 3145 input = self.shell.input_hist[n]
3139 3146 # skip plain 'r' lines so we don't recurse to infinity
3140 3147 if input != '_ip.magic("r")\n' and \
3141 3148 (input.startswith(start) or input.startswith(start_magic)):
3142 3149 #print 'match',`input` # dbg
3143 3150 print 'Executing:',input,
3144 3151 self.shell.runlines(input)
3145 3152 return
3146 3153 print 'No previous input matching `%s` found.' % start
3147 3154
3148 3155
3149 3156 def magic_bookmark(self, parameter_s=''):
3150 3157 """Manage IPython's bookmark system.
3151 3158
3152 3159 %bookmark <name> - set bookmark to current dir
3153 3160 %bookmark <name> <dir> - set bookmark to <dir>
3154 3161 %bookmark -l - list all bookmarks
3155 3162 %bookmark -d <name> - remove bookmark
3156 3163 %bookmark -r - remove all bookmarks
3157 3164
3158 3165 You can later on access a bookmarked folder with:
3159 3166 %cd -b <name>
3160 3167 or simply '%cd <name>' if there is no directory called <name> AND
3161 3168 there is such a bookmark defined.
3162 3169
3163 3170 Your bookmarks persist through IPython sessions, but they are
3164 3171 associated with each profile."""
3165 3172
3166 3173 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3167 3174 if len(args) > 2:
3168 3175 raise UsageError("%bookmark: too many arguments")
3169 3176
3170 3177 bkms = self.db.get('bookmarks',{})
3171 3178
3172 3179 if opts.has_key('d'):
3173 3180 try:
3174 3181 todel = args[0]
3175 3182 except IndexError:
3176 3183 raise UsageError(
3177 3184 "%bookmark -d: must provide a bookmark to delete")
3178 3185 else:
3179 3186 try:
3180 3187 del bkms[todel]
3181 3188 except KeyError:
3182 3189 raise UsageError(
3183 3190 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3184 3191
3185 3192 elif opts.has_key('r'):
3186 3193 bkms = {}
3187 3194 elif opts.has_key('l'):
3188 3195 bks = bkms.keys()
3189 3196 bks.sort()
3190 3197 if bks:
3191 3198 size = max(map(len,bks))
3192 3199 else:
3193 3200 size = 0
3194 3201 fmt = '%-'+str(size)+'s -> %s'
3195 3202 print 'Current bookmarks:'
3196 3203 for bk in bks:
3197 3204 print fmt % (bk,bkms[bk])
3198 3205 else:
3199 3206 if not args:
3200 3207 raise UsageError("%bookmark: You must specify the bookmark name")
3201 3208 elif len(args)==1:
3202 3209 bkms[args[0]] = os.getcwd()
3203 3210 elif len(args)==2:
3204 3211 bkms[args[0]] = args[1]
3205 3212 self.db['bookmarks'] = bkms
3206 3213
3207 3214 def magic_pycat(self, parameter_s=''):
3208 3215 """Show a syntax-highlighted file through a pager.
3209 3216
3210 3217 This magic is similar to the cat utility, but it will assume the file
3211 3218 to be Python source and will show it with syntax highlighting. """
3212 3219
3213 3220 try:
3214 3221 filename = get_py_filename(parameter_s)
3215 3222 cont = file_read(filename)
3216 3223 except IOError:
3217 3224 try:
3218 3225 cont = eval(parameter_s,self.user_ns)
3219 3226 except NameError:
3220 3227 cont = None
3221 3228 if cont is None:
3222 3229 print "Error: no such file or variable"
3223 3230 return
3224 3231
3225 3232 page(self.shell.pycolorize(cont),
3226 3233 screen_lines=self.shell.usable_screen_length)
3227 3234
3228 3235 def _rerun_pasted(self):
3229 3236 """ Rerun a previously pasted command.
3230 3237 """
3231 3238 b = self.user_ns.get('pasted_block', None)
3232 3239 if b is None:
3233 3240 raise UsageError('No previous pasted block available')
3234 3241 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3235 3242 exec b in self.user_ns
3236 3243
3237 3244 def _get_pasted_lines(self, sentinel):
3238 3245 """ Yield pasted lines until the user enters the given sentinel value.
3239 3246 """
3240 3247 from IPython.core import iplib
3241 3248 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3242 3249 while True:
3243 3250 l = iplib.raw_input_original(':')
3244 3251 if l == sentinel:
3245 3252 return
3246 3253 else:
3247 3254 yield l
3248 3255
3249 3256 def _strip_pasted_lines_for_code(self, raw_lines):
3250 3257 """ Strip non-code parts of a sequence of lines to return a block of
3251 3258 code.
3252 3259 """
3253 3260 # Regular expressions that declare text we strip from the input:
3254 3261 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3255 3262 r'^\s*(\s?>)+', # Python input prompt
3256 3263 r'^\s*\.{3,}', # Continuation prompts
3257 3264 r'^\++',
3258 3265 ]
3259 3266
3260 3267 strip_from_start = map(re.compile,strip_re)
3261 3268
3262 3269 lines = []
3263 3270 for l in raw_lines:
3264 3271 for pat in strip_from_start:
3265 3272 l = pat.sub('',l)
3266 3273 lines.append(l)
3267 3274
3268 3275 block = "\n".join(lines) + '\n'
3269 3276 #print "block:\n",block
3270 3277 return block
3271 3278
3272 3279 def _execute_block(self, block, par):
3273 3280 """ Execute a block, or store it in a variable, per the user's request.
3274 3281 """
3275 3282 if not par:
3276 3283 b = textwrap.dedent(block)
3277 3284 self.user_ns['pasted_block'] = b
3278 3285 exec b in self.user_ns
3279 3286 else:
3280 3287 self.user_ns[par] = SList(block.splitlines())
3281 3288 print "Block assigned to '%s'" % par
3282 3289
3283 3290 def magic_cpaste(self, parameter_s=''):
3284 3291 """Allows you to paste & execute a pre-formatted code block from clipboard.
3285 3292
3286 3293 You must terminate the block with '--' (two minus-signs) alone on the
3287 3294 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3288 3295 is the new sentinel for this operation)
3289 3296
3290 3297 The block is dedented prior to execution to enable execution of method
3291 3298 definitions. '>' and '+' characters at the beginning of a line are
3292 3299 ignored, to allow pasting directly from e-mails, diff files and
3293 3300 doctests (the '...' continuation prompt is also stripped). The
3294 3301 executed block is also assigned to variable named 'pasted_block' for
3295 3302 later editing with '%edit pasted_block'.
3296 3303
3297 3304 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3298 3305 This assigns the pasted block to variable 'foo' as string, without
3299 3306 dedenting or executing it (preceding >>> and + is still stripped)
3300 3307
3301 3308 '%cpaste -r' re-executes the block previously entered by cpaste.
3302 3309
3303 3310 Do not be alarmed by garbled output on Windows (it's a readline bug).
3304 3311 Just press enter and type -- (and press enter again) and the block
3305 3312 will be what was just pasted.
3306 3313
3307 3314 IPython statements (magics, shell escapes) are not supported (yet).
3308 3315
3309 3316 See also
3310 3317 --------
3311 3318 paste: automatically pull code from clipboard.
3312 3319 """
3313 3320
3314 3321 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3315 3322 par = args.strip()
3316 3323 if opts.has_key('r'):
3317 3324 self._rerun_pasted()
3318 3325 return
3319 3326
3320 3327 sentinel = opts.get('s','--')
3321 3328
3322 3329 block = self._strip_pasted_lines_for_code(
3323 3330 self._get_pasted_lines(sentinel))
3324 3331
3325 3332 self._execute_block(block, par)
3326 3333
3327 3334 def magic_paste(self, parameter_s=''):
3328 3335 """Allows you to paste & execute a pre-formatted code block from clipboard.
3329 3336
3330 3337 The text is pulled directly from the clipboard without user
3331 3338 intervention and printed back on the screen before execution (unless
3332 3339 the -q flag is given to force quiet mode).
3333 3340
3334 3341 The block is dedented prior to execution to enable execution of method
3335 3342 definitions. '>' and '+' characters at the beginning of a line are
3336 3343 ignored, to allow pasting directly from e-mails, diff files and
3337 3344 doctests (the '...' continuation prompt is also stripped). The
3338 3345 executed block is also assigned to variable named 'pasted_block' for
3339 3346 later editing with '%edit pasted_block'.
3340 3347
3341 3348 You can also pass a variable name as an argument, e.g. '%paste foo'.
3342 3349 This assigns the pasted block to variable 'foo' as string, without
3343 3350 dedenting or executing it (preceding >>> and + is still stripped)
3344 3351
3345 3352 Options
3346 3353 -------
3347 3354
3348 3355 -r: re-executes the block previously entered by cpaste.
3349 3356
3350 3357 -q: quiet mode: do not echo the pasted text back to the terminal.
3351 3358
3352 3359 IPython statements (magics, shell escapes) are not supported (yet).
3353 3360
3354 3361 See also
3355 3362 --------
3356 3363 cpaste: manually paste code into terminal until you mark its end.
3357 3364 """
3358 3365 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3359 3366 par = args.strip()
3360 3367 if opts.has_key('r'):
3361 3368 self._rerun_pasted()
3362 3369 return
3363 3370
3364 3371 text = self.shell.hooks.clipboard_get()
3365 3372 block = self._strip_pasted_lines_for_code(text.splitlines())
3366 3373
3367 3374 # By default, echo back to terminal unless quiet mode is requested
3368 3375 if not opts.has_key('q'):
3369 3376 write = self.shell.write
3370 3377 write(self.shell.pycolorize(block))
3371 3378 if not block.endswith('\n'):
3372 3379 write('\n')
3373 3380 write("## -- End pasted text --\n")
3374 3381
3375 3382 self._execute_block(block, par)
3376 3383
3377 3384 def magic_quickref(self,arg):
3378 3385 """ Show a quick reference sheet """
3379 3386 import IPython.core.usage
3380 3387 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3381 3388
3382 3389 page(qr)
3383 3390
3384 3391 def magic_doctest_mode(self,parameter_s=''):
3385 3392 """Toggle doctest mode on and off.
3386 3393
3387 3394 This mode allows you to toggle the prompt behavior between normal
3388 3395 IPython prompts and ones that are as similar to the default IPython
3389 3396 interpreter as possible.
3390 3397
3391 3398 It also supports the pasting of code snippets that have leading '>>>'
3392 3399 and '...' prompts in them. This means that you can paste doctests from
3393 3400 files or docstrings (even if they have leading whitespace), and the
3394 3401 code will execute correctly. You can then use '%history -tn' to see
3395 3402 the translated history without line numbers; this will give you the
3396 3403 input after removal of all the leading prompts and whitespace, which
3397 3404 can be pasted back into an editor.
3398 3405
3399 3406 With these features, you can switch into this mode easily whenever you
3400 3407 need to do testing and changes to doctests, without having to leave
3401 3408 your existing IPython session.
3402 3409 """
3403 3410
3404 3411 from IPython.utils.ipstruct import Struct
3405 3412
3406 3413 # Shorthands
3407 3414 shell = self.shell
3408 3415 oc = shell.outputcache
3409 3416 meta = shell.meta
3410 3417 # dstore is a data store kept in the instance metadata bag to track any
3411 3418 # changes we make, so we can undo them later.
3412 3419 dstore = meta.setdefault('doctest_mode',Struct())
3413 3420 save_dstore = dstore.setdefault
3414 3421
3415 3422 # save a few values we'll need to recover later
3416 3423 mode = save_dstore('mode',False)
3417 3424 save_dstore('rc_pprint',shell.pprint)
3418 3425 save_dstore('xmode',shell.InteractiveTB.mode)
3419 3426 save_dstore('rc_separate_out',shell.separate_out)
3420 3427 save_dstore('rc_separate_out2',shell.separate_out2)
3421 3428 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3422 3429 save_dstore('rc_separate_in',shell.separate_in)
3423 3430
3424 3431 if mode == False:
3425 3432 # turn on
3426 3433 oc.prompt1.p_template = '>>> '
3427 3434 oc.prompt2.p_template = '... '
3428 3435 oc.prompt_out.p_template = ''
3429 3436
3430 3437 # Prompt separators like plain python
3431 3438 oc.input_sep = oc.prompt1.sep = ''
3432 3439 oc.output_sep = ''
3433 3440 oc.output_sep2 = ''
3434 3441
3435 3442 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3436 3443 oc.prompt_out.pad_left = False
3437 3444
3438 3445 shell.pprint = False
3439 3446
3440 3447 shell.magic_xmode('Plain')
3441 3448
3442 3449 else:
3443 3450 # turn off
3444 3451 oc.prompt1.p_template = shell.prompt_in1
3445 3452 oc.prompt2.p_template = shell.prompt_in2
3446 3453 oc.prompt_out.p_template = shell.prompt_out
3447 3454
3448 3455 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3449 3456
3450 3457 oc.output_sep = dstore.rc_separate_out
3451 3458 oc.output_sep2 = dstore.rc_separate_out2
3452 3459
3453 3460 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3454 3461 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3455 3462
3456 3463 shell.pprint = dstore.rc_pprint
3457 3464
3458 3465 shell.magic_xmode(dstore.xmode)
3459 3466
3460 3467 # Store new mode and inform
3461 3468 dstore.mode = bool(1-int(mode))
3462 3469 print 'Doctest mode is:',
3463 3470 print ['OFF','ON'][dstore.mode]
3464 3471
3465 3472 def magic_gui(self, parameter_s=''):
3466 3473 """Enable or disable IPython GUI event loop integration.
3467 3474
3468 3475 %gui [-a] [GUINAME]
3469 3476
3470 3477 This magic replaces IPython's threaded shells that were activated
3471 3478 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3472 3479 can now be enabled, disabled and swtiched at runtime and keyboard
3473 3480 interrupts should work without any problems. The following toolkits
3474 3481 are supported: wxPython, PyQt4, PyGTK, and Tk::
3475 3482
3476 3483 %gui wx # enable wxPython event loop integration
3477 3484 %gui qt4|qt # enable PyQt4 event loop integration
3478 3485 %gui gtk # enable PyGTK event loop integration
3479 3486 %gui tk # enable Tk event loop integration
3480 3487 %gui # disable all event loop integration
3481 3488
3482 3489 WARNING: after any of these has been called you can simply create
3483 3490 an application object, but DO NOT start the event loop yourself, as
3484 3491 we have already handled that.
3485 3492
3486 3493 If you want us to create an appropriate application object add the
3487 3494 "-a" flag to your command::
3488 3495
3489 3496 %gui -a wx
3490 3497
3491 3498 This is highly recommended for most users.
3492 3499 """
3493 3500 opts, arg = self.parse_options(parameter_s,'a')
3494 3501 if arg=='': arg = None
3495 3502 return enable_gui(arg, 'a' in opts)
3496 3503
3497 3504 def magic_load_ext(self, module_str):
3498 3505 """Load an IPython extension by its module name."""
3499 3506 return self.load_extension(module_str)
3500 3507
3501 3508 def magic_unload_ext(self, module_str):
3502 3509 """Unload an IPython extension by its module name."""
3503 3510 self.unload_extension(module_str)
3504 3511
3505 3512 def magic_reload_ext(self, module_str):
3506 3513 """Reload an IPython extension by its module name."""
3507 3514 self.reload_extension(module_str)
3508 3515
3509 3516 @testdec.skip_doctest
3510 3517 def magic_install_profiles(self, s):
3511 3518 """Install the default IPython profiles into the .ipython dir.
3512 3519
3513 3520 If the default profiles have already been installed, they will not
3514 3521 be overwritten. You can force overwriting them by using the ``-o``
3515 3522 option::
3516 3523
3517 3524 In [1]: %install_profiles -o
3518 3525 """
3519 3526 if '-o' in s:
3520 3527 overwrite = True
3521 3528 else:
3522 3529 overwrite = False
3523 3530 from IPython.config import profile
3524 3531 profile_dir = os.path.split(profile.__file__)[0]
3525 3532 ipython_dir = self.ipython_dir
3526 3533 files = os.listdir(profile_dir)
3527 3534
3528 3535 to_install = []
3529 3536 for f in files:
3530 3537 if f.startswith('ipython_config'):
3531 3538 src = os.path.join(profile_dir, f)
3532 3539 dst = os.path.join(ipython_dir, f)
3533 3540 if (not os.path.isfile(dst)) or overwrite:
3534 3541 to_install.append((f, src, dst))
3535 3542 if len(to_install)>0:
3536 3543 print "Installing profiles to: ", ipython_dir
3537 3544 for (f, src, dst) in to_install:
3538 3545 shutil.copy(src, dst)
3539 3546 print " %s" % f
3540 3547
3541 3548 def magic_install_default_config(self, s):
3542 3549 """Install IPython's default config file into the .ipython dir.
3543 3550
3544 3551 If the default config file (:file:`ipython_config.py`) is already
3545 3552 installed, it will not be overwritten. You can force overwriting
3546 3553 by using the ``-o`` option::
3547 3554
3548 3555 In [1]: %install_default_config
3549 3556 """
3550 3557 if '-o' in s:
3551 3558 overwrite = True
3552 3559 else:
3553 3560 overwrite = False
3554 3561 from IPython.config import default
3555 3562 config_dir = os.path.split(default.__file__)[0]
3556 3563 ipython_dir = self.ipython_dir
3557 3564 default_config_file_name = 'ipython_config.py'
3558 3565 src = os.path.join(config_dir, default_config_file_name)
3559 3566 dst = os.path.join(ipython_dir, default_config_file_name)
3560 3567 if (not os.path.isfile(dst)) or overwrite:
3561 3568 shutil.copy(src, dst)
3562 3569 print "Installing default config file: %s" % dst
3563 3570
3564 3571 # Pylab support: simple wrappers that activate pylab, load gui input
3565 3572 # handling and modify slightly %run
3566 3573
3567 3574 @testdec.skip_doctest
3568 3575 def _pylab_magic_run(self, parameter_s=''):
3569 3576 Magic.magic_run(self, parameter_s,
3570 3577 runner=mpl_runner(self.shell.safe_execfile))
3571 3578
3572 3579 _pylab_magic_run.__doc__ = magic_run.__doc__
3573 3580
3574 3581 @testdec.skip_doctest
3575 3582 def magic_pylab(self, s):
3576 3583 """Load numpy and matplotlib to work interactively.
3577 3584
3578 3585 %pylab [GUINAME]
3579 3586
3580 3587 This function lets you activate pylab (matplotlib, numpy and
3581 3588 interactive support) at any point during an IPython session.
3582 3589
3583 3590 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3584 3591 pylab and mlab, as well as all names from numpy and pylab.
3585 3592
3586 3593 Parameters
3587 3594 ----------
3588 3595 guiname : optional
3589 3596 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3590 3597 'tk'). If given, the corresponding Matplotlib backend is used,
3591 3598 otherwise matplotlib's default (which you can override in your
3592 3599 matplotlib config file) is used.
3593 3600
3594 3601 Examples
3595 3602 --------
3596 3603 In this case, where the MPL default is TkAgg:
3597 3604 In [2]: %pylab
3598 3605
3599 3606 Welcome to pylab, a matplotlib-based Python environment.
3600 3607 Backend in use: TkAgg
3601 3608 For more information, type 'help(pylab)'.
3602 3609
3603 3610 But you can explicitly request a different backend:
3604 3611 In [3]: %pylab qt
3605 3612
3606 3613 Welcome to pylab, a matplotlib-based Python environment.
3607 3614 Backend in use: Qt4Agg
3608 3615 For more information, type 'help(pylab)'.
3609 3616 """
3610 3617 self.shell.enable_pylab(s)
3611 3618
3612 3619 def magic_tb(self, s):
3613 3620 """Print the last traceback with the currently active exception mode.
3614 3621
3615 3622 See %xmode for changing exception reporting modes."""
3616 3623 self.shell.showtraceback()
3617 3624
3618 3625 # end Magic
General Comments 0
You need to be logged in to leave comments. Login now