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