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