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