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