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