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