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