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