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