##// END OF EJS Templates
Fix display of SyntaxError in Python 3....
Thomas Kluyver -
Show More
@@ -1,2756 +1,2748 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 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 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__ as builtin_mod
21 21 import __future__
22 22 import abc
23 23 import ast
24 24 import atexit
25 25 import codeop
26 26 import inspect
27 27 import os
28 28 import re
29 29 import sys
30 30 import tempfile
31 31 import types
32 32
33 33 try:
34 34 from contextlib import nested
35 35 except:
36 36 from IPython.utils.nested_context import nested
37 37
38 38 from IPython.config.configurable import SingletonConfigurable
39 39 from IPython.core import debugger, oinspect
40 40 from IPython.core import history as ipcorehist
41 41 from IPython.core import page
42 42 from IPython.core import prefilter
43 43 from IPython.core import shadowns
44 44 from IPython.core import ultratb
45 45 from IPython.core.alias import AliasManager, AliasError
46 46 from IPython.core.autocall import ExitAutocall
47 47 from IPython.core.builtin_trap import BuiltinTrap
48 48 from IPython.core.compilerop import CachingCompiler
49 49 from IPython.core.display_trap import DisplayTrap
50 50 from IPython.core.displayhook import DisplayHook
51 51 from IPython.core.displaypub import DisplayPublisher
52 52 from IPython.core.error import TryNext, UsageError
53 53 from IPython.core.extensions import ExtensionManager
54 54 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
55 55 from IPython.core.formatters import DisplayFormatter
56 56 from IPython.core.history import HistoryManager
57 57 from IPython.core.inputsplitter import IPythonInputSplitter
58 58 from IPython.core.logger import Logger
59 59 from IPython.core.macro import Macro
60 60 from IPython.core.magic import Magic
61 61 from IPython.core.payload import PayloadManager
62 62 from IPython.core.plugin import PluginManager
63 63 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
64 64 from IPython.core.profiledir import ProfileDir
65 65 from IPython.core.pylabtools import pylab_activate
66 66 from IPython.core.prompts import PromptManager
67 67 from IPython.utils import PyColorize
68 68 from IPython.utils import io
69 69 from IPython.utils import py3compat
70 70 from IPython.utils.doctestreload import doctest_reload
71 71 from IPython.utils.io import ask_yes_no, rprint
72 72 from IPython.utils.ipstruct import Struct
73 73 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
74 74 from IPython.utils.pickleshare import PickleShareDB
75 75 from IPython.utils.process import system, getoutput
76 76 from IPython.utils.strdispatch import StrDispatch
77 77 from IPython.utils.syspathcontext import prepended_to_syspath
78 78 from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList,
79 79 DollarFormatter)
80 80 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
81 81 List, Unicode, Instance, Type)
82 82 from IPython.utils.warn import warn, error, fatal
83 83 import IPython.core.hooks
84 84
85 85 #-----------------------------------------------------------------------------
86 86 # Globals
87 87 #-----------------------------------------------------------------------------
88 88
89 89 # compiled regexps for autoindent management
90 90 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
91 91
92 92 #-----------------------------------------------------------------------------
93 93 # Utilities
94 94 #-----------------------------------------------------------------------------
95 95
96 96 def softspace(file, newvalue):
97 97 """Copied from code.py, to remove the dependency"""
98 98
99 99 oldvalue = 0
100 100 try:
101 101 oldvalue = file.softspace
102 102 except AttributeError:
103 103 pass
104 104 try:
105 105 file.softspace = newvalue
106 106 except (AttributeError, TypeError):
107 107 # "attribute-less object" or "read-only attributes"
108 108 pass
109 109 return oldvalue
110 110
111 111
112 112 def no_op(*a, **kw): pass
113 113
114 114 class NoOpContext(object):
115 115 def __enter__(self): pass
116 116 def __exit__(self, type, value, traceback): pass
117 117 no_op_context = NoOpContext()
118 118
119 119 class SpaceInInput(Exception): pass
120 120
121 121 class Bunch: pass
122 122
123 123
124 124 def get_default_colors():
125 125 if sys.platform=='darwin':
126 126 return "LightBG"
127 127 elif os.name=='nt':
128 128 return 'Linux'
129 129 else:
130 130 return 'Linux'
131 131
132 132
133 133 class SeparateUnicode(Unicode):
134 134 """A Unicode subclass to validate separate_in, separate_out, etc.
135 135
136 136 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
137 137 """
138 138
139 139 def validate(self, obj, value):
140 140 if value == '0': value = ''
141 141 value = value.replace('\\n','\n')
142 142 return super(SeparateUnicode, self).validate(obj, value)
143 143
144 144
145 145 class ReadlineNoRecord(object):
146 146 """Context manager to execute some code, then reload readline history
147 147 so that interactive input to the code doesn't appear when pressing up."""
148 148 def __init__(self, shell):
149 149 self.shell = shell
150 150 self._nested_level = 0
151 151
152 152 def __enter__(self):
153 153 if self._nested_level == 0:
154 154 try:
155 155 self.orig_length = self.current_length()
156 156 self.readline_tail = self.get_readline_tail()
157 157 except (AttributeError, IndexError): # Can fail with pyreadline
158 158 self.orig_length, self.readline_tail = 999999, []
159 159 self._nested_level += 1
160 160
161 161 def __exit__(self, type, value, traceback):
162 162 self._nested_level -= 1
163 163 if self._nested_level == 0:
164 164 # Try clipping the end if it's got longer
165 165 try:
166 166 e = self.current_length() - self.orig_length
167 167 if e > 0:
168 168 for _ in range(e):
169 169 self.shell.readline.remove_history_item(self.orig_length)
170 170
171 171 # If it still doesn't match, just reload readline history.
172 172 if self.current_length() != self.orig_length \
173 173 or self.get_readline_tail() != self.readline_tail:
174 174 self.shell.refill_readline_hist()
175 175 except (AttributeError, IndexError):
176 176 pass
177 177 # Returning False will cause exceptions to propagate
178 178 return False
179 179
180 180 def current_length(self):
181 181 return self.shell.readline.get_current_history_length()
182 182
183 183 def get_readline_tail(self, n=10):
184 184 """Get the last n items in readline history."""
185 185 end = self.shell.readline.get_current_history_length() + 1
186 186 start = max(end-n, 1)
187 187 ghi = self.shell.readline.get_history_item
188 188 return [ghi(x) for x in range(start, end)]
189 189
190 190 #-----------------------------------------------------------------------------
191 191 # Main IPython class
192 192 #-----------------------------------------------------------------------------
193 193
194 194 class InteractiveShell(SingletonConfigurable, Magic):
195 195 """An enhanced, interactive shell for Python."""
196 196
197 197 _instance = None
198 198
199 199 autocall = Enum((0,1,2), default_value=0, config=True, help=
200 200 """
201 201 Make IPython automatically call any callable object even if you didn't
202 202 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
203 203 automatically. The value can be '0' to disable the feature, '1' for
204 204 'smart' autocall, where it is not applied if there are no more
205 205 arguments on the line, and '2' for 'full' autocall, where all callable
206 206 objects are automatically called (even if no arguments are present).
207 207 """
208 208 )
209 209 # TODO: remove all autoindent logic and put into frontends.
210 210 # We can't do this yet because even runlines uses the autoindent.
211 211 autoindent = CBool(True, config=True, help=
212 212 """
213 213 Autoindent IPython code entered interactively.
214 214 """
215 215 )
216 216 automagic = CBool(True, config=True, help=
217 217 """
218 218 Enable magic commands to be called without the leading %.
219 219 """
220 220 )
221 221 cache_size = Integer(1000, config=True, help=
222 222 """
223 223 Set the size of the output cache. The default is 1000, you can
224 224 change it permanently in your config file. Setting it to 0 completely
225 225 disables the caching system, and the minimum value accepted is 20 (if
226 226 you provide a value less than 20, it is reset to 0 and a warning is
227 227 issued). This limit is defined because otherwise you'll spend more
228 228 time re-flushing a too small cache than working
229 229 """
230 230 )
231 231 color_info = CBool(True, config=True, help=
232 232 """
233 233 Use colors for displaying information about objects. Because this
234 234 information is passed through a pager (like 'less'), and some pagers
235 235 get confused with color codes, this capability can be turned off.
236 236 """
237 237 )
238 238 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
239 239 default_value=get_default_colors(), config=True,
240 240 help="Set the color scheme (NoColor, Linux, or LightBG)."
241 241 )
242 242 colors_force = CBool(False, help=
243 243 """
244 244 Force use of ANSI color codes, regardless of OS and readline
245 245 availability.
246 246 """
247 247 # FIXME: This is essentially a hack to allow ZMQShell to show colors
248 248 # without readline on Win32. When the ZMQ formatting system is
249 249 # refactored, this should be removed.
250 250 )
251 251 debug = CBool(False, config=True)
252 252 deep_reload = CBool(False, config=True, help=
253 253 """
254 254 Enable deep (recursive) reloading by default. IPython can use the
255 255 deep_reload module which reloads changes in modules recursively (it
256 256 replaces the reload() function, so you don't need to change anything to
257 257 use it). deep_reload() forces a full reload of modules whose code may
258 258 have changed, which the default reload() function does not. When
259 259 deep_reload is off, IPython will use the normal reload(), but
260 260 deep_reload will still be available as dreload().
261 261 """
262 262 )
263 263 disable_failing_post_execute = CBool(False, config=True,
264 264 help="Don't call post-execute functions that have failed in the past."""
265 265 )
266 266 display_formatter = Instance(DisplayFormatter)
267 267 displayhook_class = Type(DisplayHook)
268 268 display_pub_class = Type(DisplayPublisher)
269 269
270 270 exit_now = CBool(False)
271 271 exiter = Instance(ExitAutocall)
272 272 def _exiter_default(self):
273 273 return ExitAutocall(self)
274 274 # Monotonically increasing execution counter
275 275 execution_count = Integer(1)
276 276 filename = Unicode("<ipython console>")
277 277 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
278 278
279 279 # Input splitter, to split entire cells of input into either individual
280 280 # interactive statements or whole blocks.
281 281 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
282 282 (), {})
283 283 logstart = CBool(False, config=True, help=
284 284 """
285 285 Start logging to the default log file.
286 286 """
287 287 )
288 288 logfile = Unicode('', config=True, help=
289 289 """
290 290 The name of the logfile to use.
291 291 """
292 292 )
293 293 logappend = Unicode('', config=True, help=
294 294 """
295 295 Start logging to the given file in append mode.
296 296 """
297 297 )
298 298 object_info_string_level = Enum((0,1,2), default_value=0,
299 299 config=True)
300 300 pdb = CBool(False, config=True, help=
301 301 """
302 302 Automatically call the pdb debugger after every exception.
303 303 """
304 304 )
305 305 multiline_history = CBool(sys.platform != 'win32', config=True,
306 306 help="Save multi-line entries as one entry in readline history"
307 307 )
308 308
309 309 # deprecated prompt traits:
310 310
311 311 prompt_in1 = Unicode('In [\\#]: ', config=True,
312 312 help="Deprecated, use PromptManager.in_template")
313 313 prompt_in2 = Unicode(' .\\D.: ', config=True,
314 314 help="Deprecated, use PromptManager.in2_template")
315 315 prompt_out = Unicode('Out[\\#]: ', config=True,
316 316 help="Deprecated, use PromptManager.out_template")
317 317 prompts_pad_left = CBool(True, config=True,
318 318 help="Deprecated, use PromptManager.justify")
319 319
320 320 def _prompt_trait_changed(self, name, old, new):
321 321 table = {
322 322 'prompt_in1' : 'in_template',
323 323 'prompt_in2' : 'in2_template',
324 324 'prompt_out' : 'out_template',
325 325 'prompts_pad_left' : 'justify',
326 326 }
327 327 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
328 328 name=name, newname=table[name])
329 329 )
330 330 # protect against weird cases where self.config may not exist:
331 331 if self.config is not None:
332 332 # propagate to corresponding PromptManager trait
333 333 setattr(self.config.PromptManager, table[name], new)
334 334
335 335 _prompt_in1_changed = _prompt_trait_changed
336 336 _prompt_in2_changed = _prompt_trait_changed
337 337 _prompt_out_changed = _prompt_trait_changed
338 338 _prompt_pad_left_changed = _prompt_trait_changed
339 339
340 340 show_rewritten_input = CBool(True, config=True,
341 341 help="Show rewritten input, e.g. for autocall."
342 342 )
343 343
344 344 quiet = CBool(False, config=True)
345 345
346 346 history_length = Integer(10000, config=True)
347 347
348 348 # The readline stuff will eventually be moved to the terminal subclass
349 349 # but for now, we can't do that as readline is welded in everywhere.
350 350 readline_use = CBool(True, config=True)
351 351 readline_remove_delims = Unicode('-/~', config=True)
352 352 # don't use \M- bindings by default, because they
353 353 # conflict with 8-bit encodings. See gh-58,gh-88
354 354 readline_parse_and_bind = List([
355 355 'tab: complete',
356 356 '"\C-l": clear-screen',
357 357 'set show-all-if-ambiguous on',
358 358 '"\C-o": tab-insert',
359 359 '"\C-r": reverse-search-history',
360 360 '"\C-s": forward-search-history',
361 361 '"\C-p": history-search-backward',
362 362 '"\C-n": history-search-forward',
363 363 '"\e[A": history-search-backward',
364 364 '"\e[B": history-search-forward',
365 365 '"\C-k": kill-line',
366 366 '"\C-u": unix-line-discard',
367 367 ], allow_none=False, config=True)
368 368
369 369 # TODO: this part of prompt management should be moved to the frontends.
370 370 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
371 371 separate_in = SeparateUnicode('\n', config=True)
372 372 separate_out = SeparateUnicode('', config=True)
373 373 separate_out2 = SeparateUnicode('', config=True)
374 374 wildcards_case_sensitive = CBool(True, config=True)
375 375 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
376 376 default_value='Context', config=True)
377 377
378 378 # Subcomponents of InteractiveShell
379 379 alias_manager = Instance('IPython.core.alias.AliasManager')
380 380 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
381 381 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
382 382 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
383 383 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
384 384 plugin_manager = Instance('IPython.core.plugin.PluginManager')
385 385 payload_manager = Instance('IPython.core.payload.PayloadManager')
386 386 history_manager = Instance('IPython.core.history.HistoryManager')
387 387
388 388 profile_dir = Instance('IPython.core.application.ProfileDir')
389 389 @property
390 390 def profile(self):
391 391 if self.profile_dir is not None:
392 392 name = os.path.basename(self.profile_dir.location)
393 393 return name.replace('profile_','')
394 394
395 395
396 396 # Private interface
397 397 _post_execute = Instance(dict)
398 398
399 399 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
400 400 user_module=None, user_ns=None,
401 401 custom_exceptions=((), None)):
402 402
403 403 # This is where traits with a config_key argument are updated
404 404 # from the values on config.
405 405 super(InteractiveShell, self).__init__(config=config)
406 406 self.configurables = [self]
407 407
408 408 # These are relatively independent and stateless
409 409 self.init_ipython_dir(ipython_dir)
410 410 self.init_profile_dir(profile_dir)
411 411 self.init_instance_attrs()
412 412 self.init_environment()
413 413
414 414 # Create namespaces (user_ns, user_global_ns, etc.)
415 415 self.init_create_namespaces(user_module, user_ns)
416 416 # This has to be done after init_create_namespaces because it uses
417 417 # something in self.user_ns, but before init_sys_modules, which
418 418 # is the first thing to modify sys.
419 419 # TODO: When we override sys.stdout and sys.stderr before this class
420 420 # is created, we are saving the overridden ones here. Not sure if this
421 421 # is what we want to do.
422 422 self.save_sys_module_state()
423 423 self.init_sys_modules()
424 424
425 425 # While we're trying to have each part of the code directly access what
426 426 # it needs without keeping redundant references to objects, we have too
427 427 # much legacy code that expects ip.db to exist.
428 428 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
429 429
430 430 self.init_history()
431 431 self.init_encoding()
432 432 self.init_prefilter()
433 433
434 434 Magic.__init__(self, self)
435 435
436 436 self.init_syntax_highlighting()
437 437 self.init_hooks()
438 438 self.init_pushd_popd_magic()
439 439 # self.init_traceback_handlers use to be here, but we moved it below
440 440 # because it and init_io have to come after init_readline.
441 441 self.init_user_ns()
442 442 self.init_logger()
443 443 self.init_alias()
444 444 self.init_builtins()
445 445
446 446 # pre_config_initialization
447 447
448 448 # The next section should contain everything that was in ipmaker.
449 449 self.init_logstart()
450 450
451 451 # The following was in post_config_initialization
452 452 self.init_inspector()
453 453 # init_readline() must come before init_io(), because init_io uses
454 454 # readline related things.
455 455 self.init_readline()
456 456 # We save this here in case user code replaces raw_input, but it needs
457 457 # to be after init_readline(), because PyPy's readline works by replacing
458 458 # raw_input.
459 459 if py3compat.PY3:
460 460 self.raw_input_original = input
461 461 else:
462 462 self.raw_input_original = raw_input
463 463 # init_completer must come after init_readline, because it needs to
464 464 # know whether readline is present or not system-wide to configure the
465 465 # completers, since the completion machinery can now operate
466 466 # independently of readline (e.g. over the network)
467 467 self.init_completer()
468 468 # TODO: init_io() needs to happen before init_traceback handlers
469 469 # because the traceback handlers hardcode the stdout/stderr streams.
470 470 # This logic in in debugger.Pdb and should eventually be changed.
471 471 self.init_io()
472 472 self.init_traceback_handlers(custom_exceptions)
473 473 self.init_prompts()
474 474 self.init_display_formatter()
475 475 self.init_display_pub()
476 476 self.init_displayhook()
477 477 self.init_reload_doctest()
478 478 self.init_magics()
479 479 self.init_pdb()
480 480 self.init_extension_manager()
481 481 self.init_plugin_manager()
482 482 self.init_payload()
483 483 self.hooks.late_startup_hook()
484 484 atexit.register(self.atexit_operations)
485 485
486 486 def get_ipython(self):
487 487 """Return the currently running IPython instance."""
488 488 return self
489 489
490 490 #-------------------------------------------------------------------------
491 491 # Trait changed handlers
492 492 #-------------------------------------------------------------------------
493 493
494 494 def _ipython_dir_changed(self, name, new):
495 495 if not os.path.isdir(new):
496 496 os.makedirs(new, mode = 0777)
497 497
498 498 def set_autoindent(self,value=None):
499 499 """Set the autoindent flag, checking for readline support.
500 500
501 501 If called with no arguments, it acts as a toggle."""
502 502
503 503 if value != 0 and not self.has_readline:
504 504 if os.name == 'posix':
505 505 warn("The auto-indent feature requires the readline library")
506 506 self.autoindent = 0
507 507 return
508 508 if value is None:
509 509 self.autoindent = not self.autoindent
510 510 else:
511 511 self.autoindent = value
512 512
513 513 #-------------------------------------------------------------------------
514 514 # init_* methods called by __init__
515 515 #-------------------------------------------------------------------------
516 516
517 517 def init_ipython_dir(self, ipython_dir):
518 518 if ipython_dir is not None:
519 519 self.ipython_dir = ipython_dir
520 520 return
521 521
522 522 self.ipython_dir = get_ipython_dir()
523 523
524 524 def init_profile_dir(self, profile_dir):
525 525 if profile_dir is not None:
526 526 self.profile_dir = profile_dir
527 527 return
528 528 self.profile_dir =\
529 529 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
530 530
531 531 def init_instance_attrs(self):
532 532 self.more = False
533 533
534 534 # command compiler
535 535 self.compile = CachingCompiler()
536 536
537 537 # Make an empty namespace, which extension writers can rely on both
538 538 # existing and NEVER being used by ipython itself. This gives them a
539 539 # convenient location for storing additional information and state
540 540 # their extensions may require, without fear of collisions with other
541 541 # ipython names that may develop later.
542 542 self.meta = Struct()
543 543
544 544 # Temporary files used for various purposes. Deleted at exit.
545 545 self.tempfiles = []
546 546
547 547 # Keep track of readline usage (later set by init_readline)
548 548 self.has_readline = False
549 549
550 550 # keep track of where we started running (mainly for crash post-mortem)
551 551 # This is not being used anywhere currently.
552 552 self.starting_dir = os.getcwdu()
553 553
554 554 # Indentation management
555 555 self.indent_current_nsp = 0
556 556
557 557 # Dict to track post-execution functions that have been registered
558 558 self._post_execute = {}
559 559
560 560 def init_environment(self):
561 561 """Any changes we need to make to the user's environment."""
562 562 pass
563 563
564 564 def init_encoding(self):
565 565 # Get system encoding at startup time. Certain terminals (like Emacs
566 566 # under Win32 have it set to None, and we need to have a known valid
567 567 # encoding to use in the raw_input() method
568 568 try:
569 569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
570 570 except AttributeError:
571 571 self.stdin_encoding = 'ascii'
572 572
573 573 def init_syntax_highlighting(self):
574 574 # Python source parser/formatter for syntax highlighting
575 575 pyformat = PyColorize.Parser().format
576 576 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
577 577
578 578 def init_pushd_popd_magic(self):
579 579 # for pushd/popd management
580 580 self.home_dir = get_home_dir()
581 581
582 582 self.dir_stack = []
583 583
584 584 def init_logger(self):
585 585 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
586 586 logmode='rotate')
587 587
588 588 def init_logstart(self):
589 589 """Initialize logging in case it was requested at the command line.
590 590 """
591 591 if self.logappend:
592 592 self.magic_logstart(self.logappend + ' append')
593 593 elif self.logfile:
594 594 self.magic_logstart(self.logfile)
595 595 elif self.logstart:
596 596 self.magic_logstart()
597 597
598 598 def init_builtins(self):
599 599 # A single, static flag that we set to True. Its presence indicates
600 600 # that an IPython shell has been created, and we make no attempts at
601 601 # removing on exit or representing the existence of more than one
602 602 # IPython at a time.
603 603 builtin_mod.__dict__['__IPYTHON__'] = True
604 604
605 605 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
606 606 # manage on enter/exit, but with all our shells it's virtually
607 607 # impossible to get all the cases right. We're leaving the name in for
608 608 # those who adapted their codes to check for this flag, but will
609 609 # eventually remove it after a few more releases.
610 610 builtin_mod.__dict__['__IPYTHON__active'] = \
611 611 'Deprecated, check for __IPYTHON__'
612 612
613 613 self.builtin_trap = BuiltinTrap(shell=self)
614 614
615 615 def init_inspector(self):
616 616 # Object inspector
617 617 self.inspector = oinspect.Inspector(oinspect.InspectColors,
618 618 PyColorize.ANSICodeColors,
619 619 'NoColor',
620 620 self.object_info_string_level)
621 621
622 622 def init_io(self):
623 623 # This will just use sys.stdout and sys.stderr. If you want to
624 624 # override sys.stdout and sys.stderr themselves, you need to do that
625 625 # *before* instantiating this class, because io holds onto
626 626 # references to the underlying streams.
627 627 if sys.platform == 'win32' and self.has_readline:
628 628 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
629 629 else:
630 630 io.stdout = io.IOStream(sys.stdout)
631 631 io.stderr = io.IOStream(sys.stderr)
632 632
633 633 def init_prompts(self):
634 634 self.prompt_manager = PromptManager(shell=self, config=self.config)
635 635 self.configurables.append(self.prompt_manager)
636 636
637 637 def init_display_formatter(self):
638 638 self.display_formatter = DisplayFormatter(config=self.config)
639 639 self.configurables.append(self.display_formatter)
640 640
641 641 def init_display_pub(self):
642 642 self.display_pub = self.display_pub_class(config=self.config)
643 643 self.configurables.append(self.display_pub)
644 644
645 645 def init_displayhook(self):
646 646 # Initialize displayhook, set in/out prompts and printing system
647 647 self.displayhook = self.displayhook_class(
648 648 config=self.config,
649 649 shell=self,
650 650 cache_size=self.cache_size,
651 651 )
652 652 self.configurables.append(self.displayhook)
653 653 # This is a context manager that installs/revmoes the displayhook at
654 654 # the appropriate time.
655 655 self.display_trap = DisplayTrap(hook=self.displayhook)
656 656
657 657 def init_reload_doctest(self):
658 658 # Do a proper resetting of doctest, including the necessary displayhook
659 659 # monkeypatching
660 660 try:
661 661 doctest_reload()
662 662 except ImportError:
663 663 warn("doctest module does not exist.")
664 664
665 665 #-------------------------------------------------------------------------
666 666 # Things related to injections into the sys module
667 667 #-------------------------------------------------------------------------
668 668
669 669 def save_sys_module_state(self):
670 670 """Save the state of hooks in the sys module.
671 671
672 672 This has to be called after self.user_module is created.
673 673 """
674 674 self._orig_sys_module_state = {}
675 675 self._orig_sys_module_state['stdin'] = sys.stdin
676 676 self._orig_sys_module_state['stdout'] = sys.stdout
677 677 self._orig_sys_module_state['stderr'] = sys.stderr
678 678 self._orig_sys_module_state['excepthook'] = sys.excepthook
679 679 self._orig_sys_modules_main_name = self.user_module.__name__
680 680
681 681 def restore_sys_module_state(self):
682 682 """Restore the state of the sys module."""
683 683 try:
684 684 for k, v in self._orig_sys_module_state.iteritems():
685 685 setattr(sys, k, v)
686 686 except AttributeError:
687 687 pass
688 688 # Reset what what done in self.init_sys_modules
689 689 sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name
690 690
691 691 #-------------------------------------------------------------------------
692 692 # Things related to hooks
693 693 #-------------------------------------------------------------------------
694 694
695 695 def init_hooks(self):
696 696 # hooks holds pointers used for user-side customizations
697 697 self.hooks = Struct()
698 698
699 699 self.strdispatchers = {}
700 700
701 701 # Set all default hooks, defined in the IPython.hooks module.
702 702 hooks = IPython.core.hooks
703 703 for hook_name in hooks.__all__:
704 704 # default hooks have priority 100, i.e. low; user hooks should have
705 705 # 0-100 priority
706 706 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
707 707
708 708 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
709 709 """set_hook(name,hook) -> sets an internal IPython hook.
710 710
711 711 IPython exposes some of its internal API as user-modifiable hooks. By
712 712 adding your function to one of these hooks, you can modify IPython's
713 713 behavior to call at runtime your own routines."""
714 714
715 715 # At some point in the future, this should validate the hook before it
716 716 # accepts it. Probably at least check that the hook takes the number
717 717 # of args it's supposed to.
718 718
719 719 f = types.MethodType(hook,self)
720 720
721 721 # check if the hook is for strdispatcher first
722 722 if str_key is not None:
723 723 sdp = self.strdispatchers.get(name, StrDispatch())
724 724 sdp.add_s(str_key, f, priority )
725 725 self.strdispatchers[name] = sdp
726 726 return
727 727 if re_key is not None:
728 728 sdp = self.strdispatchers.get(name, StrDispatch())
729 729 sdp.add_re(re.compile(re_key), f, priority )
730 730 self.strdispatchers[name] = sdp
731 731 return
732 732
733 733 dp = getattr(self.hooks, name, None)
734 734 if name not in IPython.core.hooks.__all__:
735 735 print "Warning! Hook '%s' is not one of %s" % \
736 736 (name, IPython.core.hooks.__all__ )
737 737 if not dp:
738 738 dp = IPython.core.hooks.CommandChainDispatcher()
739 739
740 740 try:
741 741 dp.add(f,priority)
742 742 except AttributeError:
743 743 # it was not commandchain, plain old func - replace
744 744 dp = f
745 745
746 746 setattr(self.hooks,name, dp)
747 747
748 748 def register_post_execute(self, func):
749 749 """Register a function for calling after code execution.
750 750 """
751 751 if not callable(func):
752 752 raise ValueError('argument %s must be callable' % func)
753 753 self._post_execute[func] = True
754 754
755 755 #-------------------------------------------------------------------------
756 756 # Things related to the "main" module
757 757 #-------------------------------------------------------------------------
758 758
759 759 def new_main_mod(self,ns=None):
760 760 """Return a new 'main' module object for user code execution.
761 761 """
762 762 main_mod = self._user_main_module
763 763 init_fakemod_dict(main_mod,ns)
764 764 return main_mod
765 765
766 766 def cache_main_mod(self,ns,fname):
767 767 """Cache a main module's namespace.
768 768
769 769 When scripts are executed via %run, we must keep a reference to the
770 770 namespace of their __main__ module (a FakeModule instance) around so
771 771 that Python doesn't clear it, rendering objects defined therein
772 772 useless.
773 773
774 774 This method keeps said reference in a private dict, keyed by the
775 775 absolute path of the module object (which corresponds to the script
776 776 path). This way, for multiple executions of the same script we only
777 777 keep one copy of the namespace (the last one), thus preventing memory
778 778 leaks from old references while allowing the objects from the last
779 779 execution to be accessible.
780 780
781 781 Note: we can not allow the actual FakeModule instances to be deleted,
782 782 because of how Python tears down modules (it hard-sets all their
783 783 references to None without regard for reference counts). This method
784 784 must therefore make a *copy* of the given namespace, to allow the
785 785 original module's __dict__ to be cleared and reused.
786 786
787 787
788 788 Parameters
789 789 ----------
790 790 ns : a namespace (a dict, typically)
791 791
792 792 fname : str
793 793 Filename associated with the namespace.
794 794
795 795 Examples
796 796 --------
797 797
798 798 In [10]: import IPython
799 799
800 800 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
801 801
802 802 In [12]: IPython.__file__ in _ip._main_ns_cache
803 803 Out[12]: True
804 804 """
805 805 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
806 806
807 807 def clear_main_mod_cache(self):
808 808 """Clear the cache of main modules.
809 809
810 810 Mainly for use by utilities like %reset.
811 811
812 812 Examples
813 813 --------
814 814
815 815 In [15]: import IPython
816 816
817 817 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
818 818
819 819 In [17]: len(_ip._main_ns_cache) > 0
820 820 Out[17]: True
821 821
822 822 In [18]: _ip.clear_main_mod_cache()
823 823
824 824 In [19]: len(_ip._main_ns_cache) == 0
825 825 Out[19]: True
826 826 """
827 827 self._main_ns_cache.clear()
828 828
829 829 #-------------------------------------------------------------------------
830 830 # Things related to debugging
831 831 #-------------------------------------------------------------------------
832 832
833 833 def init_pdb(self):
834 834 # Set calling of pdb on exceptions
835 835 # self.call_pdb is a property
836 836 self.call_pdb = self.pdb
837 837
838 838 def _get_call_pdb(self):
839 839 return self._call_pdb
840 840
841 841 def _set_call_pdb(self,val):
842 842
843 843 if val not in (0,1,False,True):
844 844 raise ValueError,'new call_pdb value must be boolean'
845 845
846 846 # store value in instance
847 847 self._call_pdb = val
848 848
849 849 # notify the actual exception handlers
850 850 self.InteractiveTB.call_pdb = val
851 851
852 852 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
853 853 'Control auto-activation of pdb at exceptions')
854 854
855 855 def debugger(self,force=False):
856 856 """Call the pydb/pdb debugger.
857 857
858 858 Keywords:
859 859
860 860 - force(False): by default, this routine checks the instance call_pdb
861 861 flag and does not actually invoke the debugger if the flag is false.
862 862 The 'force' option forces the debugger to activate even if the flag
863 863 is false.
864 864 """
865 865
866 866 if not (force or self.call_pdb):
867 867 return
868 868
869 869 if not hasattr(sys,'last_traceback'):
870 870 error('No traceback has been produced, nothing to debug.')
871 871 return
872 872
873 873 # use pydb if available
874 874 if debugger.has_pydb:
875 875 from pydb import pm
876 876 else:
877 877 # fallback to our internal debugger
878 878 pm = lambda : self.InteractiveTB.debugger(force=True)
879 879
880 880 with self.readline_no_record:
881 881 pm()
882 882
883 883 #-------------------------------------------------------------------------
884 884 # Things related to IPython's various namespaces
885 885 #-------------------------------------------------------------------------
886 886 default_user_namespaces = True
887 887
888 888 def init_create_namespaces(self, user_module=None, user_ns=None):
889 889 # Create the namespace where the user will operate. user_ns is
890 890 # normally the only one used, and it is passed to the exec calls as
891 891 # the locals argument. But we do carry a user_global_ns namespace
892 892 # given as the exec 'globals' argument, This is useful in embedding
893 893 # situations where the ipython shell opens in a context where the
894 894 # distinction between locals and globals is meaningful. For
895 895 # non-embedded contexts, it is just the same object as the user_ns dict.
896 896
897 897 # FIXME. For some strange reason, __builtins__ is showing up at user
898 898 # level as a dict instead of a module. This is a manual fix, but I
899 899 # should really track down where the problem is coming from. Alex
900 900 # Schmolck reported this problem first.
901 901
902 902 # A useful post by Alex Martelli on this topic:
903 903 # Re: inconsistent value from __builtins__
904 904 # Von: Alex Martelli <aleaxit@yahoo.com>
905 905 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
906 906 # Gruppen: comp.lang.python
907 907
908 908 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
909 909 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
910 910 # > <type 'dict'>
911 911 # > >>> print type(__builtins__)
912 912 # > <type 'module'>
913 913 # > Is this difference in return value intentional?
914 914
915 915 # Well, it's documented that '__builtins__' can be either a dictionary
916 916 # or a module, and it's been that way for a long time. Whether it's
917 917 # intentional (or sensible), I don't know. In any case, the idea is
918 918 # that if you need to access the built-in namespace directly, you
919 919 # should start with "import __builtin__" (note, no 's') which will
920 920 # definitely give you a module. Yeah, it's somewhat confusing:-(.
921 921
922 922 # These routines return a properly built module and dict as needed by
923 923 # the rest of the code, and can also be used by extension writers to
924 924 # generate properly initialized namespaces.
925 925 if (user_ns is not None) or (user_module is not None):
926 926 self.default_user_namespaces = False
927 927 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
928 928
929 929 # A record of hidden variables we have added to the user namespace, so
930 930 # we can list later only variables defined in actual interactive use.
931 931 self.user_ns_hidden = set()
932 932
933 933 # Now that FakeModule produces a real module, we've run into a nasty
934 934 # problem: after script execution (via %run), the module where the user
935 935 # code ran is deleted. Now that this object is a true module (needed
936 936 # so docetst and other tools work correctly), the Python module
937 937 # teardown mechanism runs over it, and sets to None every variable
938 938 # present in that module. Top-level references to objects from the
939 939 # script survive, because the user_ns is updated with them. However,
940 940 # calling functions defined in the script that use other things from
941 941 # the script will fail, because the function's closure had references
942 942 # to the original objects, which are now all None. So we must protect
943 943 # these modules from deletion by keeping a cache.
944 944 #
945 945 # To avoid keeping stale modules around (we only need the one from the
946 946 # last run), we use a dict keyed with the full path to the script, so
947 947 # only the last version of the module is held in the cache. Note,
948 948 # however, that we must cache the module *namespace contents* (their
949 949 # __dict__). Because if we try to cache the actual modules, old ones
950 950 # (uncached) could be destroyed while still holding references (such as
951 951 # those held by GUI objects that tend to be long-lived)>
952 952 #
953 953 # The %reset command will flush this cache. See the cache_main_mod()
954 954 # and clear_main_mod_cache() methods for details on use.
955 955
956 956 # This is the cache used for 'main' namespaces
957 957 self._main_ns_cache = {}
958 958 # And this is the single instance of FakeModule whose __dict__ we keep
959 959 # copying and clearing for reuse on each %run
960 960 self._user_main_module = FakeModule()
961 961
962 962 # A table holding all the namespaces IPython deals with, so that
963 963 # introspection facilities can search easily.
964 964 self.ns_table = {'user_global':self.user_module.__dict__,
965 965 'user_local':self.user_ns,
966 966 'builtin':builtin_mod.__dict__
967 967 }
968 968
969 969 @property
970 970 def user_global_ns(self):
971 971 return self.user_module.__dict__
972 972
973 973 def prepare_user_module(self, user_module=None, user_ns=None):
974 974 """Prepare the module and namespace in which user code will be run.
975 975
976 976 When IPython is started normally, both parameters are None: a new module
977 977 is created automatically, and its __dict__ used as the namespace.
978 978
979 979 If only user_module is provided, its __dict__ is used as the namespace.
980 980 If only user_ns is provided, a dummy module is created, and user_ns
981 981 becomes the global namespace. If both are provided (as they may be
982 982 when embedding), user_ns is the local namespace, and user_module
983 983 provides the global namespace.
984 984
985 985 Parameters
986 986 ----------
987 987 user_module : module, optional
988 988 The current user module in which IPython is being run. If None,
989 989 a clean module will be created.
990 990 user_ns : dict, optional
991 991 A namespace in which to run interactive commands.
992 992
993 993 Returns
994 994 -------
995 995 A tuple of user_module and user_ns, each properly initialised.
996 996 """
997 997 if user_module is None and user_ns is not None:
998 998 user_ns.setdefault("__name__", "__main__")
999 999 class DummyMod(object):
1000 1000 "A dummy module used for IPython's interactive namespace."
1001 1001 pass
1002 1002 user_module = DummyMod()
1003 1003 user_module.__dict__ = user_ns
1004 1004
1005 1005 if user_module is None:
1006 1006 user_module = types.ModuleType("__main__",
1007 1007 doc="Automatically created module for IPython interactive environment")
1008 1008
1009 1009 # We must ensure that __builtin__ (without the final 's') is always
1010 1010 # available and pointing to the __builtin__ *module*. For more details:
1011 1011 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1012 1012 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1013 1013 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1014 1014
1015 1015 if user_ns is None:
1016 1016 user_ns = user_module.__dict__
1017 1017
1018 1018 return user_module, user_ns
1019 1019
1020 1020 def init_sys_modules(self):
1021 1021 # We need to insert into sys.modules something that looks like a
1022 1022 # module but which accesses the IPython namespace, for shelve and
1023 1023 # pickle to work interactively. Normally they rely on getting
1024 1024 # everything out of __main__, but for embedding purposes each IPython
1025 1025 # instance has its own private namespace, so we can't go shoving
1026 1026 # everything into __main__.
1027 1027
1028 1028 # note, however, that we should only do this for non-embedded
1029 1029 # ipythons, which really mimic the __main__.__dict__ with their own
1030 1030 # namespace. Embedded instances, on the other hand, should not do
1031 1031 # this because they need to manage the user local/global namespaces
1032 1032 # only, but they live within a 'normal' __main__ (meaning, they
1033 1033 # shouldn't overtake the execution environment of the script they're
1034 1034 # embedded in).
1035 1035
1036 1036 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1037 1037 main_name = self.user_module.__name__
1038 1038 sys.modules[main_name] = self.user_module
1039 1039
1040 1040 def init_user_ns(self):
1041 1041 """Initialize all user-visible namespaces to their minimum defaults.
1042 1042
1043 1043 Certain history lists are also initialized here, as they effectively
1044 1044 act as user namespaces.
1045 1045
1046 1046 Notes
1047 1047 -----
1048 1048 All data structures here are only filled in, they are NOT reset by this
1049 1049 method. If they were not empty before, data will simply be added to
1050 1050 therm.
1051 1051 """
1052 1052 # This function works in two parts: first we put a few things in
1053 1053 # user_ns, and we sync that contents into user_ns_hidden so that these
1054 1054 # initial variables aren't shown by %who. After the sync, we add the
1055 1055 # rest of what we *do* want the user to see with %who even on a new
1056 1056 # session (probably nothing, so theye really only see their own stuff)
1057 1057
1058 1058 # The user dict must *always* have a __builtin__ reference to the
1059 1059 # Python standard __builtin__ namespace, which must be imported.
1060 1060 # This is so that certain operations in prompt evaluation can be
1061 1061 # reliably executed with builtins. Note that we can NOT use
1062 1062 # __builtins__ (note the 's'), because that can either be a dict or a
1063 1063 # module, and can even mutate at runtime, depending on the context
1064 1064 # (Python makes no guarantees on it). In contrast, __builtin__ is
1065 1065 # always a module object, though it must be explicitly imported.
1066 1066
1067 1067 # For more details:
1068 1068 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1069 1069 ns = dict()
1070 1070
1071 1071 # Put 'help' in the user namespace
1072 1072 try:
1073 1073 from site import _Helper
1074 1074 ns['help'] = _Helper()
1075 1075 except ImportError:
1076 1076 warn('help() not available - check site.py')
1077 1077
1078 1078 # make global variables for user access to the histories
1079 1079 ns['_ih'] = self.history_manager.input_hist_parsed
1080 1080 ns['_oh'] = self.history_manager.output_hist
1081 1081 ns['_dh'] = self.history_manager.dir_hist
1082 1082
1083 1083 ns['_sh'] = shadowns
1084 1084
1085 1085 # user aliases to input and output histories. These shouldn't show up
1086 1086 # in %who, as they can have very large reprs.
1087 1087 ns['In'] = self.history_manager.input_hist_parsed
1088 1088 ns['Out'] = self.history_manager.output_hist
1089 1089
1090 1090 # Store myself as the public api!!!
1091 1091 ns['get_ipython'] = self.get_ipython
1092 1092
1093 1093 ns['exit'] = self.exiter
1094 1094 ns['quit'] = self.exiter
1095 1095
1096 1096 # Sync what we've added so far to user_ns_hidden so these aren't seen
1097 1097 # by %who
1098 1098 self.user_ns_hidden.update(ns)
1099 1099
1100 1100 # Anything put into ns now would show up in %who. Think twice before
1101 1101 # putting anything here, as we really want %who to show the user their
1102 1102 # stuff, not our variables.
1103 1103
1104 1104 # Finally, update the real user's namespace
1105 1105 self.user_ns.update(ns)
1106 1106
1107 1107 @property
1108 1108 def all_ns_refs(self):
1109 1109 """Get a list of references to all the namespace dictionaries in which
1110 1110 IPython might store a user-created object.
1111 1111
1112 1112 Note that this does not include the displayhook, which also caches
1113 1113 objects from the output."""
1114 1114 return [self.user_ns, self.user_global_ns,
1115 1115 self._user_main_module.__dict__] + self._main_ns_cache.values()
1116 1116
1117 1117 def reset(self, new_session=True):
1118 1118 """Clear all internal namespaces, and attempt to release references to
1119 1119 user objects.
1120 1120
1121 1121 If new_session is True, a new history session will be opened.
1122 1122 """
1123 1123 # Clear histories
1124 1124 self.history_manager.reset(new_session)
1125 1125 # Reset counter used to index all histories
1126 1126 if new_session:
1127 1127 self.execution_count = 1
1128 1128
1129 1129 # Flush cached output items
1130 1130 if self.displayhook.do_full_cache:
1131 1131 self.displayhook.flush()
1132 1132
1133 1133 # The main execution namespaces must be cleared very carefully,
1134 1134 # skipping the deletion of the builtin-related keys, because doing so
1135 1135 # would cause errors in many object's __del__ methods.
1136 1136 if self.user_ns is not self.user_global_ns:
1137 1137 self.user_ns.clear()
1138 1138 ns = self.user_global_ns
1139 1139 drop_keys = set(ns.keys())
1140 1140 drop_keys.discard('__builtin__')
1141 1141 drop_keys.discard('__builtins__')
1142 1142 drop_keys.discard('__name__')
1143 1143 for k in drop_keys:
1144 1144 del ns[k]
1145 1145
1146 1146 self.user_ns_hidden.clear()
1147 1147
1148 1148 # Restore the user namespaces to minimal usability
1149 1149 self.init_user_ns()
1150 1150
1151 1151 # Restore the default and user aliases
1152 1152 self.alias_manager.clear_aliases()
1153 1153 self.alias_manager.init_aliases()
1154 1154
1155 1155 # Flush the private list of module references kept for script
1156 1156 # execution protection
1157 1157 self.clear_main_mod_cache()
1158 1158
1159 1159 # Clear out the namespace from the last %run
1160 1160 self.new_main_mod()
1161 1161
1162 1162 def del_var(self, varname, by_name=False):
1163 1163 """Delete a variable from the various namespaces, so that, as
1164 1164 far as possible, we're not keeping any hidden references to it.
1165 1165
1166 1166 Parameters
1167 1167 ----------
1168 1168 varname : str
1169 1169 The name of the variable to delete.
1170 1170 by_name : bool
1171 1171 If True, delete variables with the given name in each
1172 1172 namespace. If False (default), find the variable in the user
1173 1173 namespace, and delete references to it.
1174 1174 """
1175 1175 if varname in ('__builtin__', '__builtins__'):
1176 1176 raise ValueError("Refusing to delete %s" % varname)
1177 1177
1178 1178 ns_refs = self.all_ns_refs
1179 1179
1180 1180 if by_name: # Delete by name
1181 1181 for ns in ns_refs:
1182 1182 try:
1183 1183 del ns[varname]
1184 1184 except KeyError:
1185 1185 pass
1186 1186 else: # Delete by object
1187 1187 try:
1188 1188 obj = self.user_ns[varname]
1189 1189 except KeyError:
1190 1190 raise NameError("name '%s' is not defined" % varname)
1191 1191 # Also check in output history
1192 1192 ns_refs.append(self.history_manager.output_hist)
1193 1193 for ns in ns_refs:
1194 1194 to_delete = [n for n, o in ns.iteritems() if o is obj]
1195 1195 for name in to_delete:
1196 1196 del ns[name]
1197 1197
1198 1198 # displayhook keeps extra references, but not in a dictionary
1199 1199 for name in ('_', '__', '___'):
1200 1200 if getattr(self.displayhook, name) is obj:
1201 1201 setattr(self.displayhook, name, None)
1202 1202
1203 1203 def reset_selective(self, regex=None):
1204 1204 """Clear selective variables from internal namespaces based on a
1205 1205 specified regular expression.
1206 1206
1207 1207 Parameters
1208 1208 ----------
1209 1209 regex : string or compiled pattern, optional
1210 1210 A regular expression pattern that will be used in searching
1211 1211 variable names in the users namespaces.
1212 1212 """
1213 1213 if regex is not None:
1214 1214 try:
1215 1215 m = re.compile(regex)
1216 1216 except TypeError:
1217 1217 raise TypeError('regex must be a string or compiled pattern')
1218 1218 # Search for keys in each namespace that match the given regex
1219 1219 # If a match is found, delete the key/value pair.
1220 1220 for ns in self.all_ns_refs:
1221 1221 for var in ns:
1222 1222 if m.search(var):
1223 1223 del ns[var]
1224 1224
1225 1225 def push(self, variables, interactive=True):
1226 1226 """Inject a group of variables into the IPython user namespace.
1227 1227
1228 1228 Parameters
1229 1229 ----------
1230 1230 variables : dict, str or list/tuple of str
1231 1231 The variables to inject into the user's namespace. If a dict, a
1232 1232 simple update is done. If a str, the string is assumed to have
1233 1233 variable names separated by spaces. A list/tuple of str can also
1234 1234 be used to give the variable names. If just the variable names are
1235 1235 give (list/tuple/str) then the variable values looked up in the
1236 1236 callers frame.
1237 1237 interactive : bool
1238 1238 If True (default), the variables will be listed with the ``who``
1239 1239 magic.
1240 1240 """
1241 1241 vdict = None
1242 1242
1243 1243 # We need a dict of name/value pairs to do namespace updates.
1244 1244 if isinstance(variables, dict):
1245 1245 vdict = variables
1246 1246 elif isinstance(variables, (basestring, list, tuple)):
1247 1247 if isinstance(variables, basestring):
1248 1248 vlist = variables.split()
1249 1249 else:
1250 1250 vlist = variables
1251 1251 vdict = {}
1252 1252 cf = sys._getframe(1)
1253 1253 for name in vlist:
1254 1254 try:
1255 1255 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1256 1256 except:
1257 1257 print ('Could not get variable %s from %s' %
1258 1258 (name,cf.f_code.co_name))
1259 1259 else:
1260 1260 raise ValueError('variables must be a dict/str/list/tuple')
1261 1261
1262 1262 # Propagate variables to user namespace
1263 1263 self.user_ns.update(vdict)
1264 1264
1265 1265 # And configure interactive visibility
1266 1266 user_ns_hidden = self.user_ns_hidden
1267 1267 if interactive:
1268 1268 user_ns_hidden.difference_update(vdict)
1269 1269 else:
1270 1270 user_ns_hidden.update(vdict)
1271 1271
1272 1272 def drop_by_id(self, variables):
1273 1273 """Remove a dict of variables from the user namespace, if they are the
1274 1274 same as the values in the dictionary.
1275 1275
1276 1276 This is intended for use by extensions: variables that they've added can
1277 1277 be taken back out if they are unloaded, without removing any that the
1278 1278 user has overwritten.
1279 1279
1280 1280 Parameters
1281 1281 ----------
1282 1282 variables : dict
1283 1283 A dictionary mapping object names (as strings) to the objects.
1284 1284 """
1285 1285 for name, obj in variables.iteritems():
1286 1286 if name in self.user_ns and self.user_ns[name] is obj:
1287 1287 del self.user_ns[name]
1288 1288 self.user_ns_hidden.discard(name)
1289 1289
1290 1290 #-------------------------------------------------------------------------
1291 1291 # Things related to object introspection
1292 1292 #-------------------------------------------------------------------------
1293 1293
1294 1294 def _ofind(self, oname, namespaces=None):
1295 1295 """Find an object in the available namespaces.
1296 1296
1297 1297 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1298 1298
1299 1299 Has special code to detect magic functions.
1300 1300 """
1301 1301 oname = oname.strip()
1302 1302 #print '1- oname: <%r>' % oname # dbg
1303 1303 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1304 1304 return dict(found=False)
1305 1305
1306 1306 alias_ns = None
1307 1307 if namespaces is None:
1308 1308 # Namespaces to search in:
1309 1309 # Put them in a list. The order is important so that we
1310 1310 # find things in the same order that Python finds them.
1311 1311 namespaces = [ ('Interactive', self.user_ns),
1312 1312 ('Interactive (global)', self.user_global_ns),
1313 1313 ('Python builtin', builtin_mod.__dict__),
1314 1314 ('Alias', self.alias_manager.alias_table),
1315 1315 ]
1316 1316 alias_ns = self.alias_manager.alias_table
1317 1317
1318 1318 # initialize results to 'null'
1319 1319 found = False; obj = None; ospace = None; ds = None;
1320 1320 ismagic = False; isalias = False; parent = None
1321 1321
1322 1322 # We need to special-case 'print', which as of python2.6 registers as a
1323 1323 # function but should only be treated as one if print_function was
1324 1324 # loaded with a future import. In this case, just bail.
1325 1325 if (oname == 'print' and not py3compat.PY3 and not \
1326 1326 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1327 1327 return {'found':found, 'obj':obj, 'namespace':ospace,
1328 1328 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1329 1329
1330 1330 # Look for the given name by splitting it in parts. If the head is
1331 1331 # found, then we look for all the remaining parts as members, and only
1332 1332 # declare success if we can find them all.
1333 1333 oname_parts = oname.split('.')
1334 1334 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1335 1335 for nsname,ns in namespaces:
1336 1336 try:
1337 1337 obj = ns[oname_head]
1338 1338 except KeyError:
1339 1339 continue
1340 1340 else:
1341 1341 #print 'oname_rest:', oname_rest # dbg
1342 1342 for part in oname_rest:
1343 1343 try:
1344 1344 parent = obj
1345 1345 obj = getattr(obj,part)
1346 1346 except:
1347 1347 # Blanket except b/c some badly implemented objects
1348 1348 # allow __getattr__ to raise exceptions other than
1349 1349 # AttributeError, which then crashes IPython.
1350 1350 break
1351 1351 else:
1352 1352 # If we finish the for loop (no break), we got all members
1353 1353 found = True
1354 1354 ospace = nsname
1355 1355 if ns == alias_ns:
1356 1356 isalias = True
1357 1357 break # namespace loop
1358 1358
1359 1359 # Try to see if it's magic
1360 1360 if not found:
1361 1361 if oname.startswith(ESC_MAGIC):
1362 1362 oname = oname[1:]
1363 1363 obj = getattr(self,'magic_'+oname,None)
1364 1364 if obj is not None:
1365 1365 found = True
1366 1366 ospace = 'IPython internal'
1367 1367 ismagic = True
1368 1368
1369 1369 # Last try: special-case some literals like '', [], {}, etc:
1370 1370 if not found and oname_head in ["''",'""','[]','{}','()']:
1371 1371 obj = eval(oname_head)
1372 1372 found = True
1373 1373 ospace = 'Interactive'
1374 1374
1375 1375 return {'found':found, 'obj':obj, 'namespace':ospace,
1376 1376 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1377 1377
1378 1378 def _ofind_property(self, oname, info):
1379 1379 """Second part of object finding, to look for property details."""
1380 1380 if info.found:
1381 1381 # Get the docstring of the class property if it exists.
1382 1382 path = oname.split('.')
1383 1383 root = '.'.join(path[:-1])
1384 1384 if info.parent is not None:
1385 1385 try:
1386 1386 target = getattr(info.parent, '__class__')
1387 1387 # The object belongs to a class instance.
1388 1388 try:
1389 1389 target = getattr(target, path[-1])
1390 1390 # The class defines the object.
1391 1391 if isinstance(target, property):
1392 1392 oname = root + '.__class__.' + path[-1]
1393 1393 info = Struct(self._ofind(oname))
1394 1394 except AttributeError: pass
1395 1395 except AttributeError: pass
1396 1396
1397 1397 # We return either the new info or the unmodified input if the object
1398 1398 # hadn't been found
1399 1399 return info
1400 1400
1401 1401 def _object_find(self, oname, namespaces=None):
1402 1402 """Find an object and return a struct with info about it."""
1403 1403 inf = Struct(self._ofind(oname, namespaces))
1404 1404 return Struct(self._ofind_property(oname, inf))
1405 1405
1406 1406 def _inspect(self, meth, oname, namespaces=None, **kw):
1407 1407 """Generic interface to the inspector system.
1408 1408
1409 1409 This function is meant to be called by pdef, pdoc & friends."""
1410 1410 info = self._object_find(oname)
1411 1411 if info.found:
1412 1412 pmethod = getattr(self.inspector, meth)
1413 1413 formatter = format_screen if info.ismagic else None
1414 1414 if meth == 'pdoc':
1415 1415 pmethod(info.obj, oname, formatter)
1416 1416 elif meth == 'pinfo':
1417 1417 pmethod(info.obj, oname, formatter, info, **kw)
1418 1418 else:
1419 1419 pmethod(info.obj, oname)
1420 1420 else:
1421 1421 print 'Object `%s` not found.' % oname
1422 1422 return 'not found' # so callers can take other action
1423 1423
1424 1424 def object_inspect(self, oname):
1425 1425 with self.builtin_trap:
1426 1426 info = self._object_find(oname)
1427 1427 if info.found:
1428 1428 return self.inspector.info(info.obj, oname, info=info)
1429 1429 else:
1430 1430 return oinspect.object_info(name=oname, found=False)
1431 1431
1432 1432 #-------------------------------------------------------------------------
1433 1433 # Things related to history management
1434 1434 #-------------------------------------------------------------------------
1435 1435
1436 1436 def init_history(self):
1437 1437 """Sets up the command history, and starts regular autosaves."""
1438 1438 self.history_manager = HistoryManager(shell=self, config=self.config)
1439 1439 self.configurables.append(self.history_manager)
1440 1440
1441 1441 #-------------------------------------------------------------------------
1442 1442 # Things related to exception handling and tracebacks (not debugging)
1443 1443 #-------------------------------------------------------------------------
1444 1444
1445 1445 def init_traceback_handlers(self, custom_exceptions):
1446 1446 # Syntax error handler.
1447 1447 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1448 1448
1449 1449 # The interactive one is initialized with an offset, meaning we always
1450 1450 # want to remove the topmost item in the traceback, which is our own
1451 1451 # internal code. Valid modes: ['Plain','Context','Verbose']
1452 1452 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1453 1453 color_scheme='NoColor',
1454 1454 tb_offset = 1,
1455 1455 check_cache=self.compile.check_cache)
1456 1456
1457 1457 # The instance will store a pointer to the system-wide exception hook,
1458 1458 # so that runtime code (such as magics) can access it. This is because
1459 1459 # during the read-eval loop, it may get temporarily overwritten.
1460 1460 self.sys_excepthook = sys.excepthook
1461 1461
1462 1462 # and add any custom exception handlers the user may have specified
1463 1463 self.set_custom_exc(*custom_exceptions)
1464 1464
1465 1465 # Set the exception mode
1466 1466 self.InteractiveTB.set_mode(mode=self.xmode)
1467 1467
1468 1468 def set_custom_exc(self, exc_tuple, handler):
1469 1469 """set_custom_exc(exc_tuple,handler)
1470 1470
1471 1471 Set a custom exception handler, which will be called if any of the
1472 1472 exceptions in exc_tuple occur in the mainloop (specifically, in the
1473 1473 run_code() method).
1474 1474
1475 1475 Parameters
1476 1476 ----------
1477 1477
1478 1478 exc_tuple : tuple of exception classes
1479 1479 A *tuple* of exception classes, for which to call the defined
1480 1480 handler. It is very important that you use a tuple, and NOT A
1481 1481 LIST here, because of the way Python's except statement works. If
1482 1482 you only want to trap a single exception, use a singleton tuple::
1483 1483
1484 1484 exc_tuple == (MyCustomException,)
1485 1485
1486 1486 handler : callable
1487 1487 handler must have the following signature::
1488 1488
1489 1489 def my_handler(self, etype, value, tb, tb_offset=None):
1490 1490 ...
1491 1491 return structured_traceback
1492 1492
1493 1493 Your handler must return a structured traceback (a list of strings),
1494 1494 or None.
1495 1495
1496 1496 This will be made into an instance method (via types.MethodType)
1497 1497 of IPython itself, and it will be called if any of the exceptions
1498 1498 listed in the exc_tuple are caught. If the handler is None, an
1499 1499 internal basic one is used, which just prints basic info.
1500 1500
1501 1501 To protect IPython from crashes, if your handler ever raises an
1502 1502 exception or returns an invalid result, it will be immediately
1503 1503 disabled.
1504 1504
1505 1505 WARNING: by putting in your own exception handler into IPython's main
1506 1506 execution loop, you run a very good chance of nasty crashes. This
1507 1507 facility should only be used if you really know what you are doing."""
1508 1508
1509 1509 assert type(exc_tuple)==type(()) , \
1510 1510 "The custom exceptions must be given AS A TUPLE."
1511 1511
1512 1512 def dummy_handler(self,etype,value,tb,tb_offset=None):
1513 1513 print '*** Simple custom exception handler ***'
1514 1514 print 'Exception type :',etype
1515 1515 print 'Exception value:',value
1516 1516 print 'Traceback :',tb
1517 1517 #print 'Source code :','\n'.join(self.buffer)
1518 1518
1519 1519 def validate_stb(stb):
1520 1520 """validate structured traceback return type
1521 1521
1522 1522 return type of CustomTB *should* be a list of strings, but allow
1523 1523 single strings or None, which are harmless.
1524 1524
1525 1525 This function will *always* return a list of strings,
1526 1526 and will raise a TypeError if stb is inappropriate.
1527 1527 """
1528 1528 msg = "CustomTB must return list of strings, not %r" % stb
1529 1529 if stb is None:
1530 1530 return []
1531 1531 elif isinstance(stb, basestring):
1532 1532 return [stb]
1533 1533 elif not isinstance(stb, list):
1534 1534 raise TypeError(msg)
1535 1535 # it's a list
1536 1536 for line in stb:
1537 1537 # check every element
1538 1538 if not isinstance(line, basestring):
1539 1539 raise TypeError(msg)
1540 1540 return stb
1541 1541
1542 1542 if handler is None:
1543 1543 wrapped = dummy_handler
1544 1544 else:
1545 1545 def wrapped(self,etype,value,tb,tb_offset=None):
1546 1546 """wrap CustomTB handler, to protect IPython from user code
1547 1547
1548 1548 This makes it harder (but not impossible) for custom exception
1549 1549 handlers to crash IPython.
1550 1550 """
1551 1551 try:
1552 1552 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1553 1553 return validate_stb(stb)
1554 1554 except:
1555 1555 # clear custom handler immediately
1556 1556 self.set_custom_exc((), None)
1557 1557 print >> io.stderr, "Custom TB Handler failed, unregistering"
1558 1558 # show the exception in handler first
1559 1559 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1560 1560 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1561 1561 print >> io.stdout, "The original exception:"
1562 1562 stb = self.InteractiveTB.structured_traceback(
1563 1563 (etype,value,tb), tb_offset=tb_offset
1564 1564 )
1565 1565 return stb
1566 1566
1567 1567 self.CustomTB = types.MethodType(wrapped,self)
1568 1568 self.custom_exceptions = exc_tuple
1569 1569
1570 1570 def excepthook(self, etype, value, tb):
1571 1571 """One more defense for GUI apps that call sys.excepthook.
1572 1572
1573 1573 GUI frameworks like wxPython trap exceptions and call
1574 1574 sys.excepthook themselves. I guess this is a feature that
1575 1575 enables them to keep running after exceptions that would
1576 1576 otherwise kill their mainloop. This is a bother for IPython
1577 1577 which excepts to catch all of the program exceptions with a try:
1578 1578 except: statement.
1579 1579
1580 1580 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1581 1581 any app directly invokes sys.excepthook, it will look to the user like
1582 1582 IPython crashed. In order to work around this, we can disable the
1583 1583 CrashHandler and replace it with this excepthook instead, which prints a
1584 1584 regular traceback using our InteractiveTB. In this fashion, apps which
1585 1585 call sys.excepthook will generate a regular-looking exception from
1586 1586 IPython, and the CrashHandler will only be triggered by real IPython
1587 1587 crashes.
1588 1588
1589 1589 This hook should be used sparingly, only in places which are not likely
1590 1590 to be true IPython errors.
1591 1591 """
1592 1592 self.showtraceback((etype,value,tb),tb_offset=0)
1593 1593
1594 1594 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1595 1595 exception_only=False):
1596 1596 """Display the exception that just occurred.
1597 1597
1598 1598 If nothing is known about the exception, this is the method which
1599 1599 should be used throughout the code for presenting user tracebacks,
1600 1600 rather than directly invoking the InteractiveTB object.
1601 1601
1602 1602 A specific showsyntaxerror() also exists, but this method can take
1603 1603 care of calling it if needed, so unless you are explicitly catching a
1604 1604 SyntaxError exception, don't try to analyze the stack manually and
1605 1605 simply call this method."""
1606 1606
1607 1607 try:
1608 1608 if exc_tuple is None:
1609 1609 etype, value, tb = sys.exc_info()
1610 1610 else:
1611 1611 etype, value, tb = exc_tuple
1612 1612
1613 1613 if etype is None:
1614 1614 if hasattr(sys, 'last_type'):
1615 1615 etype, value, tb = sys.last_type, sys.last_value, \
1616 1616 sys.last_traceback
1617 1617 else:
1618 1618 self.write_err('No traceback available to show.\n')
1619 1619 return
1620 1620
1621 1621 if etype is SyntaxError:
1622 1622 # Though this won't be called by syntax errors in the input
1623 1623 # line, there may be SyntaxError cases with imported code.
1624 1624 self.showsyntaxerror(filename)
1625 1625 elif etype is UsageError:
1626 1626 self.write_err("UsageError: %s" % value)
1627 1627 else:
1628 1628 # WARNING: these variables are somewhat deprecated and not
1629 1629 # necessarily safe to use in a threaded environment, but tools
1630 1630 # like pdb depend on their existence, so let's set them. If we
1631 1631 # find problems in the field, we'll need to revisit their use.
1632 1632 sys.last_type = etype
1633 1633 sys.last_value = value
1634 1634 sys.last_traceback = tb
1635 1635 if etype in self.custom_exceptions:
1636 1636 stb = self.CustomTB(etype, value, tb, tb_offset)
1637 1637 else:
1638 1638 if exception_only:
1639 1639 stb = ['An exception has occurred, use %tb to see '
1640 1640 'the full traceback.\n']
1641 1641 stb.extend(self.InteractiveTB.get_exception_only(etype,
1642 1642 value))
1643 1643 else:
1644 1644 stb = self.InteractiveTB.structured_traceback(etype,
1645 1645 value, tb, tb_offset=tb_offset)
1646 1646
1647 1647 self._showtraceback(etype, value, stb)
1648 1648 if self.call_pdb:
1649 1649 # drop into debugger
1650 1650 self.debugger(force=True)
1651 1651 return
1652 1652
1653 1653 # Actually show the traceback
1654 1654 self._showtraceback(etype, value, stb)
1655 1655
1656 1656 except KeyboardInterrupt:
1657 1657 self.write_err("\nKeyboardInterrupt\n")
1658 1658
1659 1659 def _showtraceback(self, etype, evalue, stb):
1660 1660 """Actually show a traceback.
1661 1661
1662 1662 Subclasses may override this method to put the traceback on a different
1663 1663 place, like a side channel.
1664 1664 """
1665 1665 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1666 1666
1667 1667 def showsyntaxerror(self, filename=None):
1668 1668 """Display the syntax error that just occurred.
1669 1669
1670 1670 This doesn't display a stack trace because there isn't one.
1671 1671
1672 1672 If a filename is given, it is stuffed in the exception instead
1673 1673 of what was there before (because Python's parser always uses
1674 1674 "<string>" when reading from a string).
1675 1675 """
1676 1676 etype, value, last_traceback = sys.exc_info()
1677 1677
1678 1678 # See note about these variables in showtraceback() above
1679 1679 sys.last_type = etype
1680 1680 sys.last_value = value
1681 1681 sys.last_traceback = last_traceback
1682 1682
1683 1683 if filename and etype is SyntaxError:
1684 # Work hard to stuff the correct filename in the exception
1685 1684 try:
1686 msg, (dummy_filename, lineno, offset, line) = value
1685 value.filename = filename
1687 1686 except:
1688 1687 # Not the format we expect; leave it alone
1689 1688 pass
1690 else:
1691 # Stuff in the right filename
1692 try:
1693 # Assume SyntaxError is a class exception
1694 value = SyntaxError(msg, (filename, lineno, offset, line))
1695 except:
1696 # If that failed, assume SyntaxError is a string
1697 value = msg, (filename, lineno, offset, line)
1689
1698 1690 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1699 1691 self._showtraceback(etype, value, stb)
1700 1692
1701 1693 # This is overridden in TerminalInteractiveShell to show a message about
1702 1694 # the %paste magic.
1703 1695 def showindentationerror(self):
1704 1696 """Called by run_cell when there's an IndentationError in code entered
1705 1697 at the prompt.
1706 1698
1707 1699 This is overridden in TerminalInteractiveShell to show a message about
1708 1700 the %paste magic."""
1709 1701 self.showsyntaxerror()
1710 1702
1711 1703 #-------------------------------------------------------------------------
1712 1704 # Things related to readline
1713 1705 #-------------------------------------------------------------------------
1714 1706
1715 1707 def init_readline(self):
1716 1708 """Command history completion/saving/reloading."""
1717 1709
1718 1710 if self.readline_use:
1719 1711 import IPython.utils.rlineimpl as readline
1720 1712
1721 1713 self.rl_next_input = None
1722 1714 self.rl_do_indent = False
1723 1715
1724 1716 if not self.readline_use or not readline.have_readline:
1725 1717 self.has_readline = False
1726 1718 self.readline = None
1727 1719 # Set a number of methods that depend on readline to be no-op
1728 1720 self.readline_no_record = no_op_context
1729 1721 self.set_readline_completer = no_op
1730 1722 self.set_custom_completer = no_op
1731 1723 self.set_completer_frame = no_op
1732 1724 if self.readline_use:
1733 1725 warn('Readline services not available or not loaded.')
1734 1726 else:
1735 1727 self.has_readline = True
1736 1728 self.readline = readline
1737 1729 sys.modules['readline'] = readline
1738 1730
1739 1731 # Platform-specific configuration
1740 1732 if os.name == 'nt':
1741 1733 # FIXME - check with Frederick to see if we can harmonize
1742 1734 # naming conventions with pyreadline to avoid this
1743 1735 # platform-dependent check
1744 1736 self.readline_startup_hook = readline.set_pre_input_hook
1745 1737 else:
1746 1738 self.readline_startup_hook = readline.set_startup_hook
1747 1739
1748 1740 # Load user's initrc file (readline config)
1749 1741 # Or if libedit is used, load editrc.
1750 1742 inputrc_name = os.environ.get('INPUTRC')
1751 1743 if inputrc_name is None:
1752 1744 inputrc_name = '.inputrc'
1753 1745 if readline.uses_libedit:
1754 1746 inputrc_name = '.editrc'
1755 1747 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1756 1748 if os.path.isfile(inputrc_name):
1757 1749 try:
1758 1750 readline.read_init_file(inputrc_name)
1759 1751 except:
1760 1752 warn('Problems reading readline initialization file <%s>'
1761 1753 % inputrc_name)
1762 1754
1763 1755 # Configure readline according to user's prefs
1764 1756 # This is only done if GNU readline is being used. If libedit
1765 1757 # is being used (as on Leopard) the readline config is
1766 1758 # not run as the syntax for libedit is different.
1767 1759 if not readline.uses_libedit:
1768 1760 for rlcommand in self.readline_parse_and_bind:
1769 1761 #print "loading rl:",rlcommand # dbg
1770 1762 readline.parse_and_bind(rlcommand)
1771 1763
1772 1764 # Remove some chars from the delimiters list. If we encounter
1773 1765 # unicode chars, discard them.
1774 1766 delims = readline.get_completer_delims()
1775 1767 if not py3compat.PY3:
1776 1768 delims = delims.encode("ascii", "ignore")
1777 1769 for d in self.readline_remove_delims:
1778 1770 delims = delims.replace(d, "")
1779 1771 delims = delims.replace(ESC_MAGIC, '')
1780 1772 readline.set_completer_delims(delims)
1781 1773 # otherwise we end up with a monster history after a while:
1782 1774 readline.set_history_length(self.history_length)
1783 1775
1784 1776 self.refill_readline_hist()
1785 1777 self.readline_no_record = ReadlineNoRecord(self)
1786 1778
1787 1779 # Configure auto-indent for all platforms
1788 1780 self.set_autoindent(self.autoindent)
1789 1781
1790 1782 def refill_readline_hist(self):
1791 1783 # Load the last 1000 lines from history
1792 1784 self.readline.clear_history()
1793 1785 stdin_encoding = sys.stdin.encoding or "utf-8"
1794 1786 last_cell = u""
1795 1787 for _, _, cell in self.history_manager.get_tail(1000,
1796 1788 include_latest=True):
1797 1789 # Ignore blank lines and consecutive duplicates
1798 1790 cell = cell.rstrip()
1799 1791 if cell and (cell != last_cell):
1800 1792 if self.multiline_history:
1801 1793 self.readline.add_history(py3compat.unicode_to_str(cell,
1802 1794 stdin_encoding))
1803 1795 else:
1804 1796 for line in cell.splitlines():
1805 1797 self.readline.add_history(py3compat.unicode_to_str(line,
1806 1798 stdin_encoding))
1807 1799 last_cell = cell
1808 1800
1809 1801 def set_next_input(self, s):
1810 1802 """ Sets the 'default' input string for the next command line.
1811 1803
1812 1804 Requires readline.
1813 1805
1814 1806 Example:
1815 1807
1816 1808 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1817 1809 [D:\ipython]|2> Hello Word_ # cursor is here
1818 1810 """
1819 1811 self.rl_next_input = py3compat.cast_bytes_py2(s)
1820 1812
1821 1813 # Maybe move this to the terminal subclass?
1822 1814 def pre_readline(self):
1823 1815 """readline hook to be used at the start of each line.
1824 1816
1825 1817 Currently it handles auto-indent only."""
1826 1818
1827 1819 if self.rl_do_indent:
1828 1820 self.readline.insert_text(self._indent_current_str())
1829 1821 if self.rl_next_input is not None:
1830 1822 self.readline.insert_text(self.rl_next_input)
1831 1823 self.rl_next_input = None
1832 1824
1833 1825 def _indent_current_str(self):
1834 1826 """return the current level of indentation as a string"""
1835 1827 return self.input_splitter.indent_spaces * ' '
1836 1828
1837 1829 #-------------------------------------------------------------------------
1838 1830 # Things related to text completion
1839 1831 #-------------------------------------------------------------------------
1840 1832
1841 1833 def init_completer(self):
1842 1834 """Initialize the completion machinery.
1843 1835
1844 1836 This creates completion machinery that can be used by client code,
1845 1837 either interactively in-process (typically triggered by the readline
1846 1838 library), programatically (such as in test suites) or out-of-prcess
1847 1839 (typically over the network by remote frontends).
1848 1840 """
1849 1841 from IPython.core.completer import IPCompleter
1850 1842 from IPython.core.completerlib import (module_completer,
1851 1843 magic_run_completer, cd_completer)
1852 1844
1853 1845 self.Completer = IPCompleter(shell=self,
1854 1846 namespace=self.user_ns,
1855 1847 global_namespace=self.user_global_ns,
1856 1848 alias_table=self.alias_manager.alias_table,
1857 1849 use_readline=self.has_readline,
1858 1850 config=self.config,
1859 1851 )
1860 1852 self.configurables.append(self.Completer)
1861 1853
1862 1854 # Add custom completers to the basic ones built into IPCompleter
1863 1855 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1864 1856 self.strdispatchers['complete_command'] = sdisp
1865 1857 self.Completer.custom_completers = sdisp
1866 1858
1867 1859 self.set_hook('complete_command', module_completer, str_key = 'import')
1868 1860 self.set_hook('complete_command', module_completer, str_key = 'from')
1869 1861 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1870 1862 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1871 1863
1872 1864 # Only configure readline if we truly are using readline. IPython can
1873 1865 # do tab-completion over the network, in GUIs, etc, where readline
1874 1866 # itself may be absent
1875 1867 if self.has_readline:
1876 1868 self.set_readline_completer()
1877 1869
1878 1870 def complete(self, text, line=None, cursor_pos=None):
1879 1871 """Return the completed text and a list of completions.
1880 1872
1881 1873 Parameters
1882 1874 ----------
1883 1875
1884 1876 text : string
1885 1877 A string of text to be completed on. It can be given as empty and
1886 1878 instead a line/position pair are given. In this case, the
1887 1879 completer itself will split the line like readline does.
1888 1880
1889 1881 line : string, optional
1890 1882 The complete line that text is part of.
1891 1883
1892 1884 cursor_pos : int, optional
1893 1885 The position of the cursor on the input line.
1894 1886
1895 1887 Returns
1896 1888 -------
1897 1889 text : string
1898 1890 The actual text that was completed.
1899 1891
1900 1892 matches : list
1901 1893 A sorted list with all possible completions.
1902 1894
1903 1895 The optional arguments allow the completion to take more context into
1904 1896 account, and are part of the low-level completion API.
1905 1897
1906 1898 This is a wrapper around the completion mechanism, similar to what
1907 1899 readline does at the command line when the TAB key is hit. By
1908 1900 exposing it as a method, it can be used by other non-readline
1909 1901 environments (such as GUIs) for text completion.
1910 1902
1911 1903 Simple usage example:
1912 1904
1913 1905 In [1]: x = 'hello'
1914 1906
1915 1907 In [2]: _ip.complete('x.l')
1916 1908 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1917 1909 """
1918 1910
1919 1911 # Inject names into __builtin__ so we can complete on the added names.
1920 1912 with self.builtin_trap:
1921 1913 return self.Completer.complete(text, line, cursor_pos)
1922 1914
1923 1915 def set_custom_completer(self, completer, pos=0):
1924 1916 """Adds a new custom completer function.
1925 1917
1926 1918 The position argument (defaults to 0) is the index in the completers
1927 1919 list where you want the completer to be inserted."""
1928 1920
1929 1921 newcomp = types.MethodType(completer,self.Completer)
1930 1922 self.Completer.matchers.insert(pos,newcomp)
1931 1923
1932 1924 def set_readline_completer(self):
1933 1925 """Reset readline's completer to be our own."""
1934 1926 self.readline.set_completer(self.Completer.rlcomplete)
1935 1927
1936 1928 def set_completer_frame(self, frame=None):
1937 1929 """Set the frame of the completer."""
1938 1930 if frame:
1939 1931 self.Completer.namespace = frame.f_locals
1940 1932 self.Completer.global_namespace = frame.f_globals
1941 1933 else:
1942 1934 self.Completer.namespace = self.user_ns
1943 1935 self.Completer.global_namespace = self.user_global_ns
1944 1936
1945 1937 #-------------------------------------------------------------------------
1946 1938 # Things related to magics
1947 1939 #-------------------------------------------------------------------------
1948 1940
1949 1941 def init_magics(self):
1950 1942 # FIXME: Move the color initialization to the DisplayHook, which
1951 1943 # should be split into a prompt manager and displayhook. We probably
1952 1944 # even need a centralize colors management object.
1953 1945 self.magic_colors(self.colors)
1954 1946 # History was moved to a separate module
1955 1947 from IPython.core import history
1956 1948 history.init_ipython(self)
1957 1949
1958 1950 def magic(self, arg_s, next_input=None):
1959 1951 """Call a magic function by name.
1960 1952
1961 1953 Input: a string containing the name of the magic function to call and
1962 1954 any additional arguments to be passed to the magic.
1963 1955
1964 1956 magic('name -opt foo bar') is equivalent to typing at the ipython
1965 1957 prompt:
1966 1958
1967 1959 In[1]: %name -opt foo bar
1968 1960
1969 1961 To call a magic without arguments, simply use magic('name').
1970 1962
1971 1963 This provides a proper Python function to call IPython's magics in any
1972 1964 valid Python code you can type at the interpreter, including loops and
1973 1965 compound statements.
1974 1966 """
1975 1967 # Allow setting the next input - this is used if the user does `a=abs?`.
1976 1968 # We do this first so that magic functions can override it.
1977 1969 if next_input:
1978 1970 self.set_next_input(next_input)
1979 1971
1980 1972 args = arg_s.split(' ',1)
1981 1973 magic_name = args[0]
1982 1974 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1983 1975
1984 1976 try:
1985 1977 magic_args = args[1]
1986 1978 except IndexError:
1987 1979 magic_args = ''
1988 1980 fn = getattr(self,'magic_'+magic_name,None)
1989 1981 if fn is None:
1990 1982 error("Magic function `%s` not found." % magic_name)
1991 1983 else:
1992 1984 magic_args = self.var_expand(magic_args,1)
1993 1985 # Grab local namespace if we need it:
1994 1986 if getattr(fn, "needs_local_scope", False):
1995 1987 self._magic_locals = sys._getframe(1).f_locals
1996 1988 with self.builtin_trap:
1997 1989 result = fn(magic_args)
1998 1990 # Ensure we're not keeping object references around:
1999 1991 self._magic_locals = {}
2000 1992 return result
2001 1993
2002 1994 def define_magic(self, magicname, func):
2003 1995 """Expose own function as magic function for ipython
2004 1996
2005 1997 Example::
2006 1998
2007 1999 def foo_impl(self,parameter_s=''):
2008 2000 'My very own magic!. (Use docstrings, IPython reads them).'
2009 2001 print 'Magic function. Passed parameter is between < >:'
2010 2002 print '<%s>' % parameter_s
2011 2003 print 'The self object is:', self
2012 2004
2013 2005 ip.define_magic('foo',foo_impl)
2014 2006 """
2015 2007 im = types.MethodType(func,self)
2016 2008 old = getattr(self, "magic_" + magicname, None)
2017 2009 setattr(self, "magic_" + magicname, im)
2018 2010 return old
2019 2011
2020 2012 #-------------------------------------------------------------------------
2021 2013 # Things related to macros
2022 2014 #-------------------------------------------------------------------------
2023 2015
2024 2016 def define_macro(self, name, themacro):
2025 2017 """Define a new macro
2026 2018
2027 2019 Parameters
2028 2020 ----------
2029 2021 name : str
2030 2022 The name of the macro.
2031 2023 themacro : str or Macro
2032 2024 The action to do upon invoking the macro. If a string, a new
2033 2025 Macro object is created by passing the string to it.
2034 2026 """
2035 2027
2036 2028 from IPython.core import macro
2037 2029
2038 2030 if isinstance(themacro, basestring):
2039 2031 themacro = macro.Macro(themacro)
2040 2032 if not isinstance(themacro, macro.Macro):
2041 2033 raise ValueError('A macro must be a string or a Macro instance.')
2042 2034 self.user_ns[name] = themacro
2043 2035
2044 2036 #-------------------------------------------------------------------------
2045 2037 # Things related to the running of system commands
2046 2038 #-------------------------------------------------------------------------
2047 2039
2048 2040 def system_piped(self, cmd):
2049 2041 """Call the given cmd in a subprocess, piping stdout/err
2050 2042
2051 2043 Parameters
2052 2044 ----------
2053 2045 cmd : str
2054 2046 Command to execute (can not end in '&', as background processes are
2055 2047 not supported. Should not be a command that expects input
2056 2048 other than simple text.
2057 2049 """
2058 2050 if cmd.rstrip().endswith('&'):
2059 2051 # this is *far* from a rigorous test
2060 2052 # We do not support backgrounding processes because we either use
2061 2053 # pexpect or pipes to read from. Users can always just call
2062 2054 # os.system() or use ip.system=ip.system_raw
2063 2055 # if they really want a background process.
2064 2056 raise OSError("Background processes not supported.")
2065 2057
2066 2058 # we explicitly do NOT return the subprocess status code, because
2067 2059 # a non-None value would trigger :func:`sys.displayhook` calls.
2068 2060 # Instead, we store the exit_code in user_ns.
2069 2061 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2070 2062
2071 2063 def system_raw(self, cmd):
2072 2064 """Call the given cmd in a subprocess using os.system
2073 2065
2074 2066 Parameters
2075 2067 ----------
2076 2068 cmd : str
2077 2069 Command to execute.
2078 2070 """
2079 2071 cmd = self.var_expand(cmd, depth=2)
2080 2072 # protect os.system from UNC paths on Windows, which it can't handle:
2081 2073 if sys.platform == 'win32':
2082 2074 from IPython.utils._process_win32 import AvoidUNCPath
2083 2075 with AvoidUNCPath() as path:
2084 2076 if path is not None:
2085 2077 cmd = '"pushd %s &&"%s' % (path, cmd)
2086 2078 cmd = py3compat.unicode_to_str(cmd)
2087 2079 ec = os.system(cmd)
2088 2080 else:
2089 2081 cmd = py3compat.unicode_to_str(cmd)
2090 2082 ec = os.system(cmd)
2091 2083
2092 2084 # We explicitly do NOT return the subprocess status code, because
2093 2085 # a non-None value would trigger :func:`sys.displayhook` calls.
2094 2086 # Instead, we store the exit_code in user_ns.
2095 2087 self.user_ns['_exit_code'] = ec
2096 2088
2097 2089 # use piped system by default, because it is better behaved
2098 2090 system = system_piped
2099 2091
2100 2092 def getoutput(self, cmd, split=True):
2101 2093 """Get output (possibly including stderr) from a subprocess.
2102 2094
2103 2095 Parameters
2104 2096 ----------
2105 2097 cmd : str
2106 2098 Command to execute (can not end in '&', as background processes are
2107 2099 not supported.
2108 2100 split : bool, optional
2109 2101
2110 2102 If True, split the output into an IPython SList. Otherwise, an
2111 2103 IPython LSString is returned. These are objects similar to normal
2112 2104 lists and strings, with a few convenience attributes for easier
2113 2105 manipulation of line-based output. You can use '?' on them for
2114 2106 details.
2115 2107 """
2116 2108 if cmd.rstrip().endswith('&'):
2117 2109 # this is *far* from a rigorous test
2118 2110 raise OSError("Background processes not supported.")
2119 2111 out = getoutput(self.var_expand(cmd, depth=2))
2120 2112 if split:
2121 2113 out = SList(out.splitlines())
2122 2114 else:
2123 2115 out = LSString(out)
2124 2116 return out
2125 2117
2126 2118 #-------------------------------------------------------------------------
2127 2119 # Things related to aliases
2128 2120 #-------------------------------------------------------------------------
2129 2121
2130 2122 def init_alias(self):
2131 2123 self.alias_manager = AliasManager(shell=self, config=self.config)
2132 2124 self.configurables.append(self.alias_manager)
2133 2125 self.ns_table['alias'] = self.alias_manager.alias_table,
2134 2126
2135 2127 #-------------------------------------------------------------------------
2136 2128 # Things related to extensions and plugins
2137 2129 #-------------------------------------------------------------------------
2138 2130
2139 2131 def init_extension_manager(self):
2140 2132 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2141 2133 self.configurables.append(self.extension_manager)
2142 2134
2143 2135 def init_plugin_manager(self):
2144 2136 self.plugin_manager = PluginManager(config=self.config)
2145 2137 self.configurables.append(self.plugin_manager)
2146 2138
2147 2139
2148 2140 #-------------------------------------------------------------------------
2149 2141 # Things related to payloads
2150 2142 #-------------------------------------------------------------------------
2151 2143
2152 2144 def init_payload(self):
2153 2145 self.payload_manager = PayloadManager(config=self.config)
2154 2146 self.configurables.append(self.payload_manager)
2155 2147
2156 2148 #-------------------------------------------------------------------------
2157 2149 # Things related to the prefilter
2158 2150 #-------------------------------------------------------------------------
2159 2151
2160 2152 def init_prefilter(self):
2161 2153 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2162 2154 self.configurables.append(self.prefilter_manager)
2163 2155 # Ultimately this will be refactored in the new interpreter code, but
2164 2156 # for now, we should expose the main prefilter method (there's legacy
2165 2157 # code out there that may rely on this).
2166 2158 self.prefilter = self.prefilter_manager.prefilter_lines
2167 2159
2168 2160 def auto_rewrite_input(self, cmd):
2169 2161 """Print to the screen the rewritten form of the user's command.
2170 2162
2171 2163 This shows visual feedback by rewriting input lines that cause
2172 2164 automatic calling to kick in, like::
2173 2165
2174 2166 /f x
2175 2167
2176 2168 into::
2177 2169
2178 2170 ------> f(x)
2179 2171
2180 2172 after the user's input prompt. This helps the user understand that the
2181 2173 input line was transformed automatically by IPython.
2182 2174 """
2183 2175 if not self.show_rewritten_input:
2184 2176 return
2185 2177
2186 2178 rw = self.prompt_manager.render('rewrite') + cmd
2187 2179
2188 2180 try:
2189 2181 # plain ascii works better w/ pyreadline, on some machines, so
2190 2182 # we use it and only print uncolored rewrite if we have unicode
2191 2183 rw = str(rw)
2192 2184 print >> io.stdout, rw
2193 2185 except UnicodeEncodeError:
2194 2186 print "------> " + cmd
2195 2187
2196 2188 #-------------------------------------------------------------------------
2197 2189 # Things related to extracting values/expressions from kernel and user_ns
2198 2190 #-------------------------------------------------------------------------
2199 2191
2200 2192 def _simple_error(self):
2201 2193 etype, value = sys.exc_info()[:2]
2202 2194 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2203 2195
2204 2196 def user_variables(self, names):
2205 2197 """Get a list of variable names from the user's namespace.
2206 2198
2207 2199 Parameters
2208 2200 ----------
2209 2201 names : list of strings
2210 2202 A list of names of variables to be read from the user namespace.
2211 2203
2212 2204 Returns
2213 2205 -------
2214 2206 A dict, keyed by the input names and with the repr() of each value.
2215 2207 """
2216 2208 out = {}
2217 2209 user_ns = self.user_ns
2218 2210 for varname in names:
2219 2211 try:
2220 2212 value = repr(user_ns[varname])
2221 2213 except:
2222 2214 value = self._simple_error()
2223 2215 out[varname] = value
2224 2216 return out
2225 2217
2226 2218 def user_expressions(self, expressions):
2227 2219 """Evaluate a dict of expressions in the user's namespace.
2228 2220
2229 2221 Parameters
2230 2222 ----------
2231 2223 expressions : dict
2232 2224 A dict with string keys and string values. The expression values
2233 2225 should be valid Python expressions, each of which will be evaluated
2234 2226 in the user namespace.
2235 2227
2236 2228 Returns
2237 2229 -------
2238 2230 A dict, keyed like the input expressions dict, with the repr() of each
2239 2231 value.
2240 2232 """
2241 2233 out = {}
2242 2234 user_ns = self.user_ns
2243 2235 global_ns = self.user_global_ns
2244 2236 for key, expr in expressions.iteritems():
2245 2237 try:
2246 2238 value = repr(eval(expr, global_ns, user_ns))
2247 2239 except:
2248 2240 value = self._simple_error()
2249 2241 out[key] = value
2250 2242 return out
2251 2243
2252 2244 #-------------------------------------------------------------------------
2253 2245 # Things related to the running of code
2254 2246 #-------------------------------------------------------------------------
2255 2247
2256 2248 def ex(self, cmd):
2257 2249 """Execute a normal python statement in user namespace."""
2258 2250 with self.builtin_trap:
2259 2251 exec cmd in self.user_global_ns, self.user_ns
2260 2252
2261 2253 def ev(self, expr):
2262 2254 """Evaluate python expression expr in user namespace.
2263 2255
2264 2256 Returns the result of evaluation
2265 2257 """
2266 2258 with self.builtin_trap:
2267 2259 return eval(expr, self.user_global_ns, self.user_ns)
2268 2260
2269 2261 def safe_execfile(self, fname, *where, **kw):
2270 2262 """A safe version of the builtin execfile().
2271 2263
2272 2264 This version will never throw an exception, but instead print
2273 2265 helpful error messages to the screen. This only works on pure
2274 2266 Python files with the .py extension.
2275 2267
2276 2268 Parameters
2277 2269 ----------
2278 2270 fname : string
2279 2271 The name of the file to be executed.
2280 2272 where : tuple
2281 2273 One or two namespaces, passed to execfile() as (globals,locals).
2282 2274 If only one is given, it is passed as both.
2283 2275 exit_ignore : bool (False)
2284 2276 If True, then silence SystemExit for non-zero status (it is always
2285 2277 silenced for zero status, as it is so common).
2286 2278 raise_exceptions : bool (False)
2287 2279 If True raise exceptions everywhere. Meant for testing.
2288 2280
2289 2281 """
2290 2282 kw.setdefault('exit_ignore', False)
2291 2283 kw.setdefault('raise_exceptions', False)
2292 2284
2293 2285 fname = os.path.abspath(os.path.expanduser(fname))
2294 2286
2295 2287 # Make sure we can open the file
2296 2288 try:
2297 2289 with open(fname) as thefile:
2298 2290 pass
2299 2291 except:
2300 2292 warn('Could not open file <%s> for safe execution.' % fname)
2301 2293 return
2302 2294
2303 2295 # Find things also in current directory. This is needed to mimic the
2304 2296 # behavior of running a script from the system command line, where
2305 2297 # Python inserts the script's directory into sys.path
2306 2298 dname = os.path.dirname(fname)
2307 2299
2308 2300 with prepended_to_syspath(dname):
2309 2301 try:
2310 2302 py3compat.execfile(fname,*where)
2311 2303 except SystemExit, status:
2312 2304 # If the call was made with 0 or None exit status (sys.exit(0)
2313 2305 # or sys.exit() ), don't bother showing a traceback, as both of
2314 2306 # these are considered normal by the OS:
2315 2307 # > python -c'import sys;sys.exit(0)'; echo $?
2316 2308 # 0
2317 2309 # > python -c'import sys;sys.exit()'; echo $?
2318 2310 # 0
2319 2311 # For other exit status, we show the exception unless
2320 2312 # explicitly silenced, but only in short form.
2321 2313 if kw['raise_exceptions']:
2322 2314 raise
2323 2315 if status.code not in (0, None) and not kw['exit_ignore']:
2324 2316 self.showtraceback(exception_only=True)
2325 2317 except:
2326 2318 if kw['raise_exceptions']:
2327 2319 raise
2328 2320 self.showtraceback()
2329 2321
2330 2322 def safe_execfile_ipy(self, fname):
2331 2323 """Like safe_execfile, but for .ipy files with IPython syntax.
2332 2324
2333 2325 Parameters
2334 2326 ----------
2335 2327 fname : str
2336 2328 The name of the file to execute. The filename must have a
2337 2329 .ipy extension.
2338 2330 """
2339 2331 fname = os.path.abspath(os.path.expanduser(fname))
2340 2332
2341 2333 # Make sure we can open the file
2342 2334 try:
2343 2335 with open(fname) as thefile:
2344 2336 pass
2345 2337 except:
2346 2338 warn('Could not open file <%s> for safe execution.' % fname)
2347 2339 return
2348 2340
2349 2341 # Find things also in current directory. This is needed to mimic the
2350 2342 # behavior of running a script from the system command line, where
2351 2343 # Python inserts the script's directory into sys.path
2352 2344 dname = os.path.dirname(fname)
2353 2345
2354 2346 with prepended_to_syspath(dname):
2355 2347 try:
2356 2348 with open(fname) as thefile:
2357 2349 # self.run_cell currently captures all exceptions
2358 2350 # raised in user code. It would be nice if there were
2359 2351 # versions of runlines, execfile that did raise, so
2360 2352 # we could catch the errors.
2361 2353 self.run_cell(thefile.read(), store_history=False)
2362 2354 except:
2363 2355 self.showtraceback()
2364 2356 warn('Unknown failure executing file: <%s>' % fname)
2365 2357
2366 2358 def run_cell(self, raw_cell, store_history=False):
2367 2359 """Run a complete IPython cell.
2368 2360
2369 2361 Parameters
2370 2362 ----------
2371 2363 raw_cell : str
2372 2364 The code (including IPython code such as %magic functions) to run.
2373 2365 store_history : bool
2374 2366 If True, the raw and translated cell will be stored in IPython's
2375 2367 history. For user code calling back into IPython's machinery, this
2376 2368 should be set to False.
2377 2369 """
2378 2370 if (not raw_cell) or raw_cell.isspace():
2379 2371 return
2380 2372
2381 2373 for line in raw_cell.splitlines():
2382 2374 self.input_splitter.push(line)
2383 2375 cell = self.input_splitter.source_reset()
2384 2376
2385 2377 with self.builtin_trap:
2386 2378 prefilter_failed = False
2387 2379 if len(cell.splitlines()) == 1:
2388 2380 try:
2389 2381 # use prefilter_lines to handle trailing newlines
2390 2382 # restore trailing newline for ast.parse
2391 2383 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2392 2384 except AliasError as e:
2393 2385 error(e)
2394 2386 prefilter_failed = True
2395 2387 except Exception:
2396 2388 # don't allow prefilter errors to crash IPython
2397 2389 self.showtraceback()
2398 2390 prefilter_failed = True
2399 2391
2400 2392 # Store raw and processed history
2401 2393 if store_history:
2402 2394 self.history_manager.store_inputs(self.execution_count,
2403 2395 cell, raw_cell)
2404 2396
2405 2397 self.logger.log(cell, raw_cell)
2406 2398
2407 2399 if not prefilter_failed:
2408 2400 # don't run if prefilter failed
2409 2401 cell_name = self.compile.cache(cell, self.execution_count)
2410 2402
2411 2403 with self.display_trap:
2412 2404 try:
2413 2405 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2414 2406 except IndentationError:
2415 2407 self.showindentationerror()
2416 2408 if store_history:
2417 2409 self.execution_count += 1
2418 2410 return None
2419 2411 except (OverflowError, SyntaxError, ValueError, TypeError,
2420 2412 MemoryError):
2421 2413 self.showsyntaxerror()
2422 2414 if store_history:
2423 2415 self.execution_count += 1
2424 2416 return None
2425 2417
2426 2418 self.run_ast_nodes(code_ast.body, cell_name,
2427 2419 interactivity="last_expr")
2428 2420
2429 2421 # Execute any registered post-execution functions.
2430 2422 for func, status in self._post_execute.iteritems():
2431 2423 if self.disable_failing_post_execute and not status:
2432 2424 continue
2433 2425 try:
2434 2426 func()
2435 2427 except KeyboardInterrupt:
2436 2428 print >> io.stderr, "\nKeyboardInterrupt"
2437 2429 except Exception:
2438 2430 # register as failing:
2439 2431 self._post_execute[func] = False
2440 2432 self.showtraceback()
2441 2433 print >> io.stderr, '\n'.join([
2442 2434 "post-execution function %r produced an error." % func,
2443 2435 "If this problem persists, you can disable failing post-exec functions with:",
2444 2436 "",
2445 2437 " get_ipython().disable_failing_post_execute = True"
2446 2438 ])
2447 2439
2448 2440 if store_history:
2449 2441 # Write output to the database. Does nothing unless
2450 2442 # history output logging is enabled.
2451 2443 self.history_manager.store_output(self.execution_count)
2452 2444 # Each cell is a *single* input, regardless of how many lines it has
2453 2445 self.execution_count += 1
2454 2446
2455 2447 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2456 2448 """Run a sequence of AST nodes. The execution mode depends on the
2457 2449 interactivity parameter.
2458 2450
2459 2451 Parameters
2460 2452 ----------
2461 2453 nodelist : list
2462 2454 A sequence of AST nodes to run.
2463 2455 cell_name : str
2464 2456 Will be passed to the compiler as the filename of the cell. Typically
2465 2457 the value returned by ip.compile.cache(cell).
2466 2458 interactivity : str
2467 2459 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2468 2460 run interactively (displaying output from expressions). 'last_expr'
2469 2461 will run the last node interactively only if it is an expression (i.e.
2470 2462 expressions in loops or other blocks are not displayed. Other values
2471 2463 for this parameter will raise a ValueError.
2472 2464 """
2473 2465 if not nodelist:
2474 2466 return
2475 2467
2476 2468 if interactivity == 'last_expr':
2477 2469 if isinstance(nodelist[-1], ast.Expr):
2478 2470 interactivity = "last"
2479 2471 else:
2480 2472 interactivity = "none"
2481 2473
2482 2474 if interactivity == 'none':
2483 2475 to_run_exec, to_run_interactive = nodelist, []
2484 2476 elif interactivity == 'last':
2485 2477 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2486 2478 elif interactivity == 'all':
2487 2479 to_run_exec, to_run_interactive = [], nodelist
2488 2480 else:
2489 2481 raise ValueError("Interactivity was %r" % interactivity)
2490 2482
2491 2483 exec_count = self.execution_count
2492 2484
2493 2485 try:
2494 2486 for i, node in enumerate(to_run_exec):
2495 2487 mod = ast.Module([node])
2496 2488 code = self.compile(mod, cell_name, "exec")
2497 2489 if self.run_code(code):
2498 2490 return True
2499 2491
2500 2492 for i, node in enumerate(to_run_interactive):
2501 2493 mod = ast.Interactive([node])
2502 2494 code = self.compile(mod, cell_name, "single")
2503 2495 if self.run_code(code):
2504 2496 return True
2505 2497 except:
2506 2498 # It's possible to have exceptions raised here, typically by
2507 2499 # compilation of odd code (such as a naked 'return' outside a
2508 2500 # function) that did parse but isn't valid. Typically the exception
2509 2501 # is a SyntaxError, but it's safest just to catch anything and show
2510 2502 # the user a traceback.
2511 2503
2512 2504 # We do only one try/except outside the loop to minimize the impact
2513 2505 # on runtime, and also because if any node in the node list is
2514 2506 # broken, we should stop execution completely.
2515 2507 self.showtraceback()
2516 2508
2517 2509 return False
2518 2510
2519 2511 def run_code(self, code_obj):
2520 2512 """Execute a code object.
2521 2513
2522 2514 When an exception occurs, self.showtraceback() is called to display a
2523 2515 traceback.
2524 2516
2525 2517 Parameters
2526 2518 ----------
2527 2519 code_obj : code object
2528 2520 A compiled code object, to be executed
2529 2521 post_execute : bool [default: True]
2530 2522 whether to call post_execute hooks after this particular execution.
2531 2523
2532 2524 Returns
2533 2525 -------
2534 2526 False : successful execution.
2535 2527 True : an error occurred.
2536 2528 """
2537 2529
2538 2530 # Set our own excepthook in case the user code tries to call it
2539 2531 # directly, so that the IPython crash handler doesn't get triggered
2540 2532 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2541 2533
2542 2534 # we save the original sys.excepthook in the instance, in case config
2543 2535 # code (such as magics) needs access to it.
2544 2536 self.sys_excepthook = old_excepthook
2545 2537 outflag = 1 # happens in more places, so it's easier as default
2546 2538 try:
2547 2539 try:
2548 2540 self.hooks.pre_run_code_hook()
2549 2541 #rprint('Running code', repr(code_obj)) # dbg
2550 2542 exec code_obj in self.user_global_ns, self.user_ns
2551 2543 finally:
2552 2544 # Reset our crash handler in place
2553 2545 sys.excepthook = old_excepthook
2554 2546 except SystemExit:
2555 2547 self.showtraceback(exception_only=True)
2556 2548 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2557 2549 except self.custom_exceptions:
2558 2550 etype,value,tb = sys.exc_info()
2559 2551 self.CustomTB(etype,value,tb)
2560 2552 except:
2561 2553 self.showtraceback()
2562 2554 else:
2563 2555 outflag = 0
2564 2556 if softspace(sys.stdout, 0):
2565 2557 print
2566 2558
2567 2559 return outflag
2568 2560
2569 2561 # For backwards compatibility
2570 2562 runcode = run_code
2571 2563
2572 2564 #-------------------------------------------------------------------------
2573 2565 # Things related to GUI support and pylab
2574 2566 #-------------------------------------------------------------------------
2575 2567
2576 2568 def enable_gui(self, gui=None):
2577 2569 raise NotImplementedError('Implement enable_gui in a subclass')
2578 2570
2579 2571 def enable_pylab(self, gui=None, import_all=True):
2580 2572 """Activate pylab support at runtime.
2581 2573
2582 2574 This turns on support for matplotlib, preloads into the interactive
2583 2575 namespace all of numpy and pylab, and configures IPython to correctly
2584 2576 interact with the GUI event loop. The GUI backend to be used can be
2585 2577 optionally selected with the optional :param:`gui` argument.
2586 2578
2587 2579 Parameters
2588 2580 ----------
2589 2581 gui : optional, string
2590 2582
2591 2583 If given, dictates the choice of matplotlib GUI backend to use
2592 2584 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2593 2585 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2594 2586 matplotlib (as dictated by the matplotlib build-time options plus the
2595 2587 user's matplotlibrc configuration file). Note that not all backends
2596 2588 make sense in all contexts, for example a terminal ipython can't
2597 2589 display figures inline.
2598 2590 """
2599 2591
2600 2592 # We want to prevent the loading of pylab to pollute the user's
2601 2593 # namespace as shown by the %who* magics, so we execute the activation
2602 2594 # code in an empty namespace, and we update *both* user_ns and
2603 2595 # user_ns_hidden with this information.
2604 2596 ns = {}
2605 2597 try:
2606 2598 gui = pylab_activate(ns, gui, import_all, self)
2607 2599 except KeyError:
2608 2600 error("Backend %r not supported" % gui)
2609 2601 return
2610 2602 self.user_ns.update(ns)
2611 2603 self.user_ns_hidden.update(ns)
2612 2604 # Now we must activate the gui pylab wants to use, and fix %run to take
2613 2605 # plot updates into account
2614 2606 self.enable_gui(gui)
2615 2607 self.magic_run = self._pylab_magic_run
2616 2608
2617 2609 #-------------------------------------------------------------------------
2618 2610 # Utilities
2619 2611 #-------------------------------------------------------------------------
2620 2612
2621 2613 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2622 2614 """Expand python variables in a string.
2623 2615
2624 2616 The depth argument indicates how many frames above the caller should
2625 2617 be walked to look for the local namespace where to expand variables.
2626 2618
2627 2619 The global namespace for expansion is always the user's interactive
2628 2620 namespace.
2629 2621 """
2630 2622 ns = self.user_ns.copy()
2631 2623 ns.update(sys._getframe(depth+1).f_locals)
2632 2624 ns.pop('self', None)
2633 2625 return formatter.format(cmd, **ns)
2634 2626
2635 2627 def mktempfile(self, data=None, prefix='ipython_edit_'):
2636 2628 """Make a new tempfile and return its filename.
2637 2629
2638 2630 This makes a call to tempfile.mktemp, but it registers the created
2639 2631 filename internally so ipython cleans it up at exit time.
2640 2632
2641 2633 Optional inputs:
2642 2634
2643 2635 - data(None): if data is given, it gets written out to the temp file
2644 2636 immediately, and the file is closed again."""
2645 2637
2646 2638 filename = tempfile.mktemp('.py', prefix)
2647 2639 self.tempfiles.append(filename)
2648 2640
2649 2641 if data:
2650 2642 tmp_file = open(filename,'w')
2651 2643 tmp_file.write(data)
2652 2644 tmp_file.close()
2653 2645 return filename
2654 2646
2655 2647 # TODO: This should be removed when Term is refactored.
2656 2648 def write(self,data):
2657 2649 """Write a string to the default output"""
2658 2650 io.stdout.write(data)
2659 2651
2660 2652 # TODO: This should be removed when Term is refactored.
2661 2653 def write_err(self,data):
2662 2654 """Write a string to the default error output"""
2663 2655 io.stderr.write(data)
2664 2656
2665 2657 def ask_yes_no(self, prompt, default=None):
2666 2658 if self.quiet:
2667 2659 return True
2668 2660 return ask_yes_no(prompt,default)
2669 2661
2670 2662 def show_usage(self):
2671 2663 """Show a usage message"""
2672 2664 page.page(IPython.core.usage.interactive_usage)
2673 2665
2674 2666 def find_user_code(self, target, raw=True):
2675 2667 """Get a code string from history, file, or a string or macro.
2676 2668
2677 2669 This is mainly used by magic functions.
2678 2670
2679 2671 Parameters
2680 2672 ----------
2681 2673 target : str
2682 2674 A string specifying code to retrieve. This will be tried respectively
2683 2675 as: ranges of input history (see %history for syntax), a filename, or
2684 2676 an expression evaluating to a string or Macro in the user namespace.
2685 2677 raw : bool
2686 2678 If true (default), retrieve raw history. Has no effect on the other
2687 2679 retrieval mechanisms.
2688 2680
2689 2681 Returns
2690 2682 -------
2691 2683 A string of code.
2692 2684
2693 2685 ValueError is raised if nothing is found, and TypeError if it evaluates
2694 2686 to an object of another type. In each case, .args[0] is a printable
2695 2687 message.
2696 2688 """
2697 2689 code = self.extract_input_lines(target, raw=raw) # Grab history
2698 2690 if code:
2699 2691 return code
2700 2692 if os.path.isfile(target): # Read file
2701 2693 return open(target, "r").read()
2702 2694
2703 2695 try: # User namespace
2704 2696 codeobj = eval(target, self.user_ns)
2705 2697 except Exception:
2706 2698 raise ValueError(("'%s' was not found in history, as a file, nor in"
2707 2699 " the user namespace.") % target)
2708 2700 if isinstance(codeobj, basestring):
2709 2701 return codeobj
2710 2702 elif isinstance(codeobj, Macro):
2711 2703 return codeobj.value
2712 2704
2713 2705 raise TypeError("%s is neither a string nor a macro." % target,
2714 2706 codeobj)
2715 2707
2716 2708 #-------------------------------------------------------------------------
2717 2709 # Things related to IPython exiting
2718 2710 #-------------------------------------------------------------------------
2719 2711 def atexit_operations(self):
2720 2712 """This will be executed at the time of exit.
2721 2713
2722 2714 Cleanup operations and saving of persistent data that is done
2723 2715 unconditionally by IPython should be performed here.
2724 2716
2725 2717 For things that may depend on startup flags or platform specifics (such
2726 2718 as having readline or not), register a separate atexit function in the
2727 2719 code that has the appropriate information, rather than trying to
2728 2720 clutter
2729 2721 """
2730 2722 # Close the history session (this stores the end time and line count)
2731 2723 # this must be *before* the tempfile cleanup, in case of temporary
2732 2724 # history db
2733 2725 self.history_manager.end_session()
2734 2726
2735 2727 # Cleanup all tempfiles left around
2736 2728 for tfile in self.tempfiles:
2737 2729 try:
2738 2730 os.unlink(tfile)
2739 2731 except OSError:
2740 2732 pass
2741 2733
2742 2734 # Clear all user namespaces to release all references cleanly.
2743 2735 self.reset(new_session=False)
2744 2736
2745 2737 # Run user hooks
2746 2738 self.hooks.shutdown_hook()
2747 2739
2748 2740 def cleanup(self):
2749 2741 self.restore_sys_module_state()
2750 2742
2751 2743
2752 2744 class InteractiveShellABC(object):
2753 2745 """An abstract base class for InteractiveShell."""
2754 2746 __metaclass__ = abc.ABCMeta
2755 2747
2756 2748 InteractiveShellABC.register(InteractiveShell)
@@ -1,1249 +1,1245 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 ultratb.py -- Spice up your tracebacks!
4 4
5 5 * ColorTB
6 6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 7 ColorTB class is a solution to that problem. It colors the different parts of a
8 8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 9 text editor.
10 10
11 11 Installation instructions for ColorTB:
12 12 import sys,ultratb
13 13 sys.excepthook = ultratb.ColorTB()
14 14
15 15 * VerboseTB
16 16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 18 and intended it for CGI programmers, but why should they have all the fun? I
19 19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 20 but kind of neat, and maybe useful for long-running programs that you believe
21 21 are bug-free. If a crash *does* occur in that type of program you want details.
22 22 Give it a shot--you'll love it or you'll hate it.
23 23
24 24 Note:
25 25
26 26 The Verbose mode prints the variables currently visible where the exception
27 27 happened (shortening their strings if too long). This can potentially be
28 28 very slow, if you happen to have a huge data structure whose string
29 29 representation is complex to compute. Your computer may appear to freeze for
30 30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 31 with Ctrl-C (maybe hitting it more than once).
32 32
33 33 If you encounter this kind of situation often, you may want to use the
34 34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 35 variables (but otherwise includes the information and context given by
36 36 Verbose).
37 37
38 38
39 39 Installation instructions for ColorTB:
40 40 import sys,ultratb
41 41 sys.excepthook = ultratb.VerboseTB()
42 42
43 43 Note: Much of the code in this module was lifted verbatim from the standard
44 44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45 45
46 46 * Color schemes
47 47 The colors are defined in the class TBTools through the use of the
48 48 ColorSchemeTable class. Currently the following exist:
49 49
50 50 - NoColor: allows all of this module to be used in any terminal (the color
51 51 escapes are just dummy blank strings).
52 52
53 53 - Linux: is meant to look good in a terminal like the Linux console (black
54 54 or very dark background).
55 55
56 56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 57 in light background terminals.
58 58
59 59 You can implement other color schemes easily, the syntax is fairly
60 60 self-explanatory. Please send back new schemes you develop to the author for
61 61 possible inclusion in future releases.
62 62 """
63 63
64 64 #*****************************************************************************
65 65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 67 #
68 68 # Distributed under the terms of the BSD License. The full license is in
69 69 # the file COPYING, distributed as part of this software.
70 70 #*****************************************************************************
71 71
72 72 from __future__ import with_statement
73 73
74 74 import inspect
75 75 import keyword
76 76 import linecache
77 77 import os
78 78 import pydoc
79 79 import re
80 80 import sys
81 81 import time
82 82 import tokenize
83 83 import traceback
84 84 import types
85 85
86 86 try: # Python 2
87 87 generate_tokens = tokenize.generate_tokens
88 88 except AttributeError: # Python 3
89 89 generate_tokens = tokenize.tokenize
90 90
91 91 # For purposes of monkeypatching inspect to fix a bug in it.
92 92 from inspect import getsourcefile, getfile, getmodule,\
93 93 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
94 94
95 95 # IPython's own modules
96 96 # Modified pdb which doesn't damage IPython's readline handling
97 97 from IPython.core import debugger, ipapi
98 98 from IPython.core.display_trap import DisplayTrap
99 99 from IPython.core.excolors import exception_colors
100 100 from IPython.utils import PyColorize
101 101 from IPython.utils import io
102 102 from IPython.utils import py3compat
103 103 from IPython.utils.data import uniq_stable
104 104 from IPython.utils.warn import info, error
105 105
106 106 # Globals
107 107 # amount of space to put line numbers before verbose tracebacks
108 108 INDENT_SIZE = 8
109 109
110 110 # Default color scheme. This is used, for example, by the traceback
111 111 # formatter. When running in an actual IPython instance, the user's rc.colors
112 112 # value is used, but havinga module global makes this functionality available
113 113 # to users of ultratb who are NOT running inside ipython.
114 114 DEFAULT_SCHEME = 'NoColor'
115 115
116 116 #---------------------------------------------------------------------------
117 117 # Code begins
118 118
119 119 # Utility functions
120 120 def inspect_error():
121 121 """Print a message about internal inspect errors.
122 122
123 123 These are unfortunately quite common."""
124 124
125 125 error('Internal Python error in the inspect module.\n'
126 126 'Below is the traceback from this internal error.\n')
127 127
128 128
129 129 def findsource(object):
130 130 """Return the entire source file and starting line number for an object.
131 131
132 132 The argument may be a module, class, method, function, traceback, frame,
133 133 or code object. The source code is returned as a list of all the lines
134 134 in the file and the line number indexes a line in that list. An IOError
135 135 is raised if the source code cannot be retrieved.
136 136
137 137 FIXED version with which we monkeypatch the stdlib to work around a bug."""
138 138
139 139 file = getsourcefile(object) or getfile(object)
140 140 # If the object is a frame, then trying to get the globals dict from its
141 141 # module won't work. Instead, the frame object itself has the globals
142 142 # dictionary.
143 143 globals_dict = None
144 144 if inspect.isframe(object):
145 145 # XXX: can this ever be false?
146 146 globals_dict = object.f_globals
147 147 else:
148 148 module = getmodule(object, file)
149 149 if module:
150 150 globals_dict = module.__dict__
151 151 lines = linecache.getlines(file, globals_dict)
152 152 if not lines:
153 153 raise IOError('could not get source code')
154 154
155 155 if ismodule(object):
156 156 return lines, 0
157 157
158 158 if isclass(object):
159 159 name = object.__name__
160 160 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
161 161 # make some effort to find the best matching class definition:
162 162 # use the one with the least indentation, which is the one
163 163 # that's most probably not inside a function definition.
164 164 candidates = []
165 165 for i in range(len(lines)):
166 166 match = pat.match(lines[i])
167 167 if match:
168 168 # if it's at toplevel, it's already the best one
169 169 if lines[i][0] == 'c':
170 170 return lines, i
171 171 # else add whitespace to candidate list
172 172 candidates.append((match.group(1), i))
173 173 if candidates:
174 174 # this will sort by whitespace, and by line number,
175 175 # less whitespace first
176 176 candidates.sort()
177 177 return lines, candidates[0][1]
178 178 else:
179 179 raise IOError('could not find class definition')
180 180
181 181 if ismethod(object):
182 182 object = object.im_func
183 183 if isfunction(object):
184 184 object = object.func_code
185 185 if istraceback(object):
186 186 object = object.tb_frame
187 187 if isframe(object):
188 188 object = object.f_code
189 189 if iscode(object):
190 190 if not hasattr(object, 'co_firstlineno'):
191 191 raise IOError('could not find function definition')
192 192 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
193 193 pmatch = pat.match
194 194 # fperez - fix: sometimes, co_firstlineno can give a number larger than
195 195 # the length of lines, which causes an error. Safeguard against that.
196 196 lnum = min(object.co_firstlineno,len(lines))-1
197 197 while lnum > 0:
198 198 if pmatch(lines[lnum]): break
199 199 lnum -= 1
200 200
201 201 return lines, lnum
202 202 raise IOError('could not find code object')
203 203
204 204 # Monkeypatch inspect to apply our bugfix. This code only works with py25
205 205 if sys.version_info[:2] >= (2,5):
206 206 inspect.findsource = findsource
207 207
208 208 def fix_frame_records_filenames(records):
209 209 """Try to fix the filenames in each record from inspect.getinnerframes().
210 210
211 211 Particularly, modules loaded from within zip files have useless filenames
212 212 attached to their code object, and inspect.getinnerframes() just uses it.
213 213 """
214 214 fixed_records = []
215 215 for frame, filename, line_no, func_name, lines, index in records:
216 216 # Look inside the frame's globals dictionary for __file__, which should
217 217 # be better.
218 218 better_fn = frame.f_globals.get('__file__', None)
219 219 if isinstance(better_fn, str):
220 220 # Check the type just in case someone did something weird with
221 221 # __file__. It might also be None if the error occurred during
222 222 # import.
223 223 filename = better_fn
224 224 fixed_records.append((frame, filename, line_no, func_name, lines, index))
225 225 return fixed_records
226 226
227 227
228 228 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
229 229 import linecache
230 230 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
231 231
232 232 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
233 233
234 234 # If the error is at the console, don't build any context, since it would
235 235 # otherwise produce 5 blank lines printed out (there is no file at the
236 236 # console)
237 237 rec_check = records[tb_offset:]
238 238 try:
239 239 rname = rec_check[0][1]
240 240 if rname == '<ipython console>' or rname.endswith('<string>'):
241 241 return rec_check
242 242 except IndexError:
243 243 pass
244 244
245 245 aux = traceback.extract_tb(etb)
246 246 assert len(records) == len(aux)
247 247 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
248 248 maybeStart = lnum-1 - context//2
249 249 start = max(maybeStart, 0)
250 250 end = start + context
251 251 lines = linecache.getlines(file)[start:end]
252 252 buf = list(records[i])
253 253 buf[LNUM_POS] = lnum
254 254 buf[INDEX_POS] = lnum - 1 - start
255 255 buf[LINES_POS] = lines
256 256 records[i] = tuple(buf)
257 257 return records[tb_offset:]
258 258
259 259 # Helper function -- largely belongs to VerboseTB, but we need the same
260 260 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
261 261 # can be recognized properly by ipython.el's py-traceback-line-re
262 262 # (SyntaxErrors have to be treated specially because they have no traceback)
263 263
264 264 _parser = PyColorize.Parser()
265 265
266 266 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
267 267 numbers_width = INDENT_SIZE - 1
268 268 res = []
269 269 i = lnum - index
270 270
271 271 # This lets us get fully syntax-highlighted tracebacks.
272 272 if scheme is None:
273 273 ipinst = ipapi.get()
274 274 if ipinst is not None:
275 275 scheme = ipinst.colors
276 276 else:
277 277 scheme = DEFAULT_SCHEME
278 278
279 279 _line_format = _parser.format2
280 280
281 281 for line in lines:
282 282 # FIXME: we need to ensure the source is a pure string at this point,
283 283 # else the coloring code makes a royal mess. This is in need of a
284 284 # serious refactoring, so that all of the ultratb and PyColorize code
285 285 # is unicode-safe. So for now this is rather an ugly hack, but
286 286 # necessary to at least have readable tracebacks. Improvements welcome!
287 287 line = py3compat.cast_bytes_py2(line, 'utf-8')
288 288
289 289 new_line, err = _line_format(line, 'str', scheme)
290 290 if not err: line = new_line
291 291
292 292 if i == lnum:
293 293 # This is the line with the error
294 294 pad = numbers_width - len(str(i))
295 295 if pad >= 3:
296 296 marker = '-'*(pad-3) + '-> '
297 297 elif pad == 2:
298 298 marker = '> '
299 299 elif pad == 1:
300 300 marker = '>'
301 301 else:
302 302 marker = ''
303 303 num = marker + str(i)
304 304 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
305 305 Colors.line, line, Colors.Normal)
306 306 else:
307 307 num = '%*s' % (numbers_width,i)
308 308 line = '%s%s%s %s' %(Colors.lineno, num,
309 309 Colors.Normal, line)
310 310
311 311 res.append(line)
312 312 if lvals and i == lnum:
313 313 res.append(lvals + '\n')
314 314 i = i + 1
315 315 return res
316 316
317 317
318 318 #---------------------------------------------------------------------------
319 319 # Module classes
320 320 class TBTools(object):
321 321 """Basic tools used by all traceback printer classes."""
322 322
323 323 # Number of frames to skip when reporting tracebacks
324 324 tb_offset = 0
325 325
326 326 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
327 327 # Whether to call the interactive pdb debugger after printing
328 328 # tracebacks or not
329 329 self.call_pdb = call_pdb
330 330
331 331 # Output stream to write to. Note that we store the original value in
332 332 # a private attribute and then make the public ostream a property, so
333 333 # that we can delay accessing io.stdout until runtime. The way
334 334 # things are written now, the io.stdout object is dynamically managed
335 335 # so a reference to it should NEVER be stored statically. This
336 336 # property approach confines this detail to a single location, and all
337 337 # subclasses can simply access self.ostream for writing.
338 338 self._ostream = ostream
339 339
340 340 # Create color table
341 341 self.color_scheme_table = exception_colors()
342 342
343 343 self.set_colors(color_scheme)
344 344 self.old_scheme = color_scheme # save initial value for toggles
345 345
346 346 if call_pdb:
347 347 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
348 348 else:
349 349 self.pdb = None
350 350
351 351 def _get_ostream(self):
352 352 """Output stream that exceptions are written to.
353 353
354 354 Valid values are:
355 355
356 356 - None: the default, which means that IPython will dynamically resolve
357 357 to io.stdout. This ensures compatibility with most tools, including
358 358 Windows (where plain stdout doesn't recognize ANSI escapes).
359 359
360 360 - Any object with 'write' and 'flush' attributes.
361 361 """
362 362 return io.stdout if self._ostream is None else self._ostream
363 363
364 364 def _set_ostream(self, val):
365 365 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
366 366 self._ostream = val
367 367
368 368 ostream = property(_get_ostream, _set_ostream)
369 369
370 370 def set_colors(self,*args,**kw):
371 371 """Shorthand access to the color table scheme selector method."""
372 372
373 373 # Set own color table
374 374 self.color_scheme_table.set_active_scheme(*args,**kw)
375 375 # for convenience, set Colors to the active scheme
376 376 self.Colors = self.color_scheme_table.active_colors
377 377 # Also set colors of debugger
378 378 if hasattr(self,'pdb') and self.pdb is not None:
379 379 self.pdb.set_colors(*args,**kw)
380 380
381 381 def color_toggle(self):
382 382 """Toggle between the currently active color scheme and NoColor."""
383 383
384 384 if self.color_scheme_table.active_scheme_name == 'NoColor':
385 385 self.color_scheme_table.set_active_scheme(self.old_scheme)
386 386 self.Colors = self.color_scheme_table.active_colors
387 387 else:
388 388 self.old_scheme = self.color_scheme_table.active_scheme_name
389 389 self.color_scheme_table.set_active_scheme('NoColor')
390 390 self.Colors = self.color_scheme_table.active_colors
391 391
392 392 def stb2text(self, stb):
393 393 """Convert a structured traceback (a list) to a string."""
394 394 return '\n'.join(stb)
395 395
396 396 def text(self, etype, value, tb, tb_offset=None, context=5):
397 397 """Return formatted traceback.
398 398
399 399 Subclasses may override this if they add extra arguments.
400 400 """
401 401 tb_list = self.structured_traceback(etype, value, tb,
402 402 tb_offset, context)
403 403 return self.stb2text(tb_list)
404 404
405 405 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
406 406 context=5, mode=None):
407 407 """Return a list of traceback frames.
408 408
409 409 Must be implemented by each class.
410 410 """
411 411 raise NotImplementedError()
412 412
413 413
414 414 #---------------------------------------------------------------------------
415 415 class ListTB(TBTools):
416 416 """Print traceback information from a traceback list, with optional color.
417 417
418 418 Calling: requires 3 arguments:
419 419 (etype, evalue, elist)
420 420 as would be obtained by:
421 421 etype, evalue, tb = sys.exc_info()
422 422 if tb:
423 423 elist = traceback.extract_tb(tb)
424 424 else:
425 425 elist = None
426 426
427 427 It can thus be used by programs which need to process the traceback before
428 428 printing (such as console replacements based on the code module from the
429 429 standard library).
430 430
431 431 Because they are meant to be called without a full traceback (only a
432 432 list), instances of this class can't call the interactive pdb debugger."""
433 433
434 434 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
435 435 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
436 436 ostream=ostream)
437 437
438 438 def __call__(self, etype, value, elist):
439 439 self.ostream.flush()
440 440 self.ostream.write(self.text(etype, value, elist))
441 441 self.ostream.write('\n')
442 442
443 443 def structured_traceback(self, etype, value, elist, tb_offset=None,
444 444 context=5):
445 445 """Return a color formatted string with the traceback info.
446 446
447 447 Parameters
448 448 ----------
449 449 etype : exception type
450 450 Type of the exception raised.
451 451
452 452 value : object
453 453 Data stored in the exception
454 454
455 455 elist : list
456 456 List of frames, see class docstring for details.
457 457
458 458 tb_offset : int, optional
459 459 Number of frames in the traceback to skip. If not given, the
460 460 instance value is used (set in constructor).
461 461
462 462 context : int, optional
463 463 Number of lines of context information to print.
464 464
465 465 Returns
466 466 -------
467 467 String with formatted exception.
468 468 """
469 469 tb_offset = self.tb_offset if tb_offset is None else tb_offset
470 470 Colors = self.Colors
471 471 out_list = []
472 472 if elist:
473 473
474 474 if tb_offset and len(elist) > tb_offset:
475 475 elist = elist[tb_offset:]
476 476
477 477 out_list.append('Traceback %s(most recent call last)%s:' %
478 478 (Colors.normalEm, Colors.Normal) + '\n')
479 479 out_list.extend(self._format_list(elist))
480 480 # The exception info should be a single entry in the list.
481 481 lines = ''.join(self._format_exception_only(etype, value))
482 482 out_list.append(lines)
483 483
484 484 # Note: this code originally read:
485 485
486 486 ## for line in lines[:-1]:
487 487 ## out_list.append(" "+line)
488 488 ## out_list.append(lines[-1])
489 489
490 490 # This means it was indenting everything but the last line by a little
491 491 # bit. I've disabled this for now, but if we see ugliness somewhre we
492 492 # can restore it.
493 493
494 494 return out_list
495 495
496 496 def _format_list(self, extracted_list):
497 497 """Format a list of traceback entry tuples for printing.
498 498
499 499 Given a list of tuples as returned by extract_tb() or
500 500 extract_stack(), return a list of strings ready for printing.
501 501 Each string in the resulting list corresponds to the item with the
502 502 same index in the argument list. Each string ends in a newline;
503 503 the strings may contain internal newlines as well, for those items
504 504 whose source text line is not None.
505 505
506 506 Lifted almost verbatim from traceback.py
507 507 """
508 508
509 509 Colors = self.Colors
510 510 list = []
511 511 for filename, lineno, name, line in extracted_list[:-1]:
512 512 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
513 513 (Colors.filename, filename, Colors.Normal,
514 514 Colors.lineno, lineno, Colors.Normal,
515 515 Colors.name, name, Colors.Normal)
516 516 if line:
517 517 item = item + ' %s\n' % line.strip()
518 518 list.append(item)
519 519 # Emphasize the last entry
520 520 filename, lineno, name, line = extracted_list[-1]
521 521 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
522 522 (Colors.normalEm,
523 523 Colors.filenameEm, filename, Colors.normalEm,
524 524 Colors.linenoEm, lineno, Colors.normalEm,
525 525 Colors.nameEm, name, Colors.normalEm,
526 526 Colors.Normal)
527 527 if line:
528 528 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
529 529 Colors.Normal)
530 530 list.append(item)
531 531 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
532 532 return list
533 533
534 534 def _format_exception_only(self, etype, value):
535 535 """Format the exception part of a traceback.
536 536
537 537 The arguments are the exception type and value such as given by
538 538 sys.exc_info()[:2]. The return value is a list of strings, each ending
539 539 in a newline. Normally, the list contains a single string; however,
540 540 for SyntaxError exceptions, it contains several lines that (when
541 541 printed) display detailed information about where the syntax error
542 542 occurred. The message indicating which exception occurred is the
543 543 always last string in the list.
544 544
545 545 Also lifted nearly verbatim from traceback.py
546 546 """
547 547
548 548 have_filedata = False
549 549 Colors = self.Colors
550 550 list = []
551 try:
552 stype = Colors.excName + etype.__name__ + Colors.Normal
553 except AttributeError:
554 stype = etype # String exceptions don't get special coloring
551 stype = Colors.excName + etype.__name__ + Colors.Normal
555 552 if value is None:
553 # Not sure if this can still happen in Python 2.6 and above
556 554 list.append( str(stype) + '\n')
557 555 else:
558 556 if etype is SyntaxError:
559 try:
560 msg, (filename, lineno, offset, line) = value
561 except:
562 have_filedata = False
563 else:
564 have_filedata = True
565 #print 'filename is',filename # dbg
566 if not filename: filename = "<string>"
567 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
568 (Colors.normalEm,
569 Colors.filenameEm, filename, Colors.normalEm,
570 Colors.linenoEm, lineno, Colors.Normal ))
571 if line is not None:
572 i = 0
573 while i < len(line) and line[i].isspace():
574 i = i+1
575 list.append('%s %s%s\n' % (Colors.line,
576 line.strip(),
577 Colors.Normal))
578 if offset is not None:
579 s = ' '
580 for c in line[i:offset-1]:
581 if c.isspace():
582 s = s + c
583 else:
584 s = s + ' '
585 list.append('%s%s^%s\n' % (Colors.caret, s,
586 Colors.Normal) )
587 value = msg
588 s = self._some_str(value)
557 have_filedata = True
558 #print 'filename is',filename # dbg
559 if not value.filename: value.filename = "<string>"
560 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
561 (Colors.normalEm,
562 Colors.filenameEm, value.filename, Colors.normalEm,
563 Colors.linenoEm, value.lineno, Colors.Normal ))
564 if value.text is not None:
565 i = 0
566 while i < len(value.text) and value.text[i].isspace():
567 i = i+1
568 list.append('%s %s%s\n' % (Colors.line,
569 value.text.strip(),
570 Colors.Normal))
571 if value.offset is not None:
572 s = ' '
573 for c in value.text[i:value.offset-1]:
574 if c.isspace():
575 s = s + c
576 else:
577 s = s + ' '
578 list.append('%s%s^%s\n' % (Colors.caret, s,
579 Colors.Normal) )
580
581 try:
582 s = value.msg
583 except Exception:
584 s = self._some_str(value)
589 585 if s:
590 586 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
591 587 Colors.Normal, s))
592 588 else:
593 589 list.append('%s\n' % str(stype))
594 590
595 591 # sync with user hooks
596 592 if have_filedata:
597 593 ipinst = ipapi.get()
598 594 if ipinst is not None:
599 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
595 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
600 596
601 597 return list
602 598
603 599 def get_exception_only(self, etype, value):
604 600 """Only print the exception type and message, without a traceback.
605 601
606 602 Parameters
607 603 ----------
608 604 etype : exception type
609 605 value : exception value
610 606 """
611 607 return ListTB.structured_traceback(self, etype, value, [])
612 608
613 609
614 610 def show_exception_only(self, etype, evalue):
615 611 """Only print the exception type and message, without a traceback.
616 612
617 613 Parameters
618 614 ----------
619 615 etype : exception type
620 616 value : exception value
621 617 """
622 618 # This method needs to use __call__ from *this* class, not the one from
623 619 # a subclass whose signature or behavior may be different
624 620 ostream = self.ostream
625 621 ostream.flush()
626 622 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
627 623 ostream.flush()
628 624
629 625 def _some_str(self, value):
630 626 # Lifted from traceback.py
631 627 try:
632 628 return str(value)
633 629 except:
634 630 return '<unprintable %s object>' % type(value).__name__
635 631
636 632 #----------------------------------------------------------------------------
637 633 class VerboseTB(TBTools):
638 634 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
639 635 of HTML. Requires inspect and pydoc. Crazy, man.
640 636
641 637 Modified version which optionally strips the topmost entries from the
642 638 traceback, to be used with alternate interpreters (because their own code
643 639 would appear in the traceback)."""
644 640
645 641 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
646 642 tb_offset=0, long_header=False, include_vars=True,
647 643 check_cache=None):
648 644 """Specify traceback offset, headers and color scheme.
649 645
650 646 Define how many frames to drop from the tracebacks. Calling it with
651 647 tb_offset=1 allows use of this handler in interpreters which will have
652 648 their own code at the top of the traceback (VerboseTB will first
653 649 remove that frame before printing the traceback info)."""
654 650 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
655 651 ostream=ostream)
656 652 self.tb_offset = tb_offset
657 653 self.long_header = long_header
658 654 self.include_vars = include_vars
659 655 # By default we use linecache.checkcache, but the user can provide a
660 656 # different check_cache implementation. This is used by the IPython
661 657 # kernel to provide tracebacks for interactive code that is cached,
662 658 # by a compiler instance that flushes the linecache but preserves its
663 659 # own code cache.
664 660 if check_cache is None:
665 661 check_cache = linecache.checkcache
666 662 self.check_cache = check_cache
667 663
668 664 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
669 665 context=5):
670 666 """Return a nice text document describing the traceback."""
671 667
672 668 tb_offset = self.tb_offset if tb_offset is None else tb_offset
673 669
674 670 # some locals
675 671 try:
676 672 etype = etype.__name__
677 673 except AttributeError:
678 674 pass
679 675 Colors = self.Colors # just a shorthand + quicker name lookup
680 676 ColorsNormal = Colors.Normal # used a lot
681 677 col_scheme = self.color_scheme_table.active_scheme_name
682 678 indent = ' '*INDENT_SIZE
683 679 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
684 680 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
685 681 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
686 682
687 683 # some internal-use functions
688 684 def text_repr(value):
689 685 """Hopefully pretty robust repr equivalent."""
690 686 # this is pretty horrible but should always return *something*
691 687 try:
692 688 return pydoc.text.repr(value)
693 689 except KeyboardInterrupt:
694 690 raise
695 691 except:
696 692 try:
697 693 return repr(value)
698 694 except KeyboardInterrupt:
699 695 raise
700 696 except:
701 697 try:
702 698 # all still in an except block so we catch
703 699 # getattr raising
704 700 name = getattr(value, '__name__', None)
705 701 if name:
706 702 # ick, recursion
707 703 return text_repr(name)
708 704 klass = getattr(value, '__class__', None)
709 705 if klass:
710 706 return '%s instance' % text_repr(klass)
711 707 except KeyboardInterrupt:
712 708 raise
713 709 except:
714 710 return 'UNRECOVERABLE REPR FAILURE'
715 711 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
716 712 def nullrepr(value, repr=text_repr): return ''
717 713
718 714 # meat of the code begins
719 715 try:
720 716 etype = etype.__name__
721 717 except AttributeError:
722 718 pass
723 719
724 720 if self.long_header:
725 721 # Header with the exception type, python version, and date
726 722 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
727 723 date = time.ctime(time.time())
728 724
729 725 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
730 726 exc, ' '*(75-len(str(etype))-len(pyver)),
731 727 pyver, date.rjust(75) )
732 728 head += "\nA problem occured executing Python code. Here is the sequence of function"\
733 729 "\ncalls leading up to the error, with the most recent (innermost) call last."
734 730 else:
735 731 # Simplified header
736 732 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
737 733 'Traceback (most recent call last)'.\
738 734 rjust(75 - len(str(etype)) ) )
739 735 frames = []
740 736 # Flush cache before calling inspect. This helps alleviate some of the
741 737 # problems with python 2.3's inspect.py.
742 738 ##self.check_cache()
743 739 # Drop topmost frames if requested
744 740 try:
745 741 # Try the default getinnerframes and Alex's: Alex's fixes some
746 742 # problems, but it generates empty tracebacks for console errors
747 743 # (5 blanks lines) where none should be returned.
748 744 #records = inspect.getinnerframes(etb, context)[tb_offset:]
749 745 #print 'python records:', records # dbg
750 746 records = _fixed_getinnerframes(etb, context, tb_offset)
751 747 #print 'alex records:', records # dbg
752 748 except:
753 749
754 750 # FIXME: I've been getting many crash reports from python 2.3
755 751 # users, traceable to inspect.py. If I can find a small test-case
756 752 # to reproduce this, I should either write a better workaround or
757 753 # file a bug report against inspect (if that's the real problem).
758 754 # So far, I haven't been able to find an isolated example to
759 755 # reproduce the problem.
760 756 inspect_error()
761 757 traceback.print_exc(file=self.ostream)
762 758 info('\nUnfortunately, your original traceback can not be constructed.\n')
763 759 return ''
764 760
765 761 # build some color string templates outside these nested loops
766 762 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
767 763 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
768 764 ColorsNormal)
769 765 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
770 766 (Colors.vName, Colors.valEm, ColorsNormal)
771 767 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
772 768 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
773 769 Colors.vName, ColorsNormal)
774 770 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
775 771 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
776 772 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
777 773 ColorsNormal)
778 774
779 775 # now, loop over all records printing context and info
780 776 abspath = os.path.abspath
781 777 for frame, file, lnum, func, lines, index in records:
782 778 #print '*** record:',file,lnum,func,lines,index # dbg
783 779 try:
784 780 file = file and abspath(file) or '?'
785 781 except OSError:
786 782 # if file is '<console>' or something not in the filesystem,
787 783 # the abspath call will throw an OSError. Just ignore it and
788 784 # keep the original file string.
789 785 pass
790 786 link = tpl_link % file
791 787 try:
792 788 args, varargs, varkw, locals = inspect.getargvalues(frame)
793 789 except:
794 790 # This can happen due to a bug in python2.3. We should be
795 791 # able to remove this try/except when 2.4 becomes a
796 792 # requirement. Bug details at http://python.org/sf/1005466
797 793 inspect_error()
798 794 traceback.print_exc(file=self.ostream)
799 795 info("\nIPython's exception reporting continues...\n")
800 796
801 797 if func == '?':
802 798 call = ''
803 799 else:
804 800 # Decide whether to include variable details or not
805 801 var_repr = self.include_vars and eqrepr or nullrepr
806 802 try:
807 803 call = tpl_call % (func,inspect.formatargvalues(args,
808 804 varargs, varkw,
809 805 locals,formatvalue=var_repr))
810 806 except KeyError:
811 807 # This happens in situations like errors inside generator
812 808 # expressions, where local variables are listed in the
813 809 # line, but can't be extracted from the frame. I'm not
814 810 # 100% sure this isn't actually a bug in inspect itself,
815 811 # but since there's no info for us to compute with, the
816 812 # best we can do is report the failure and move on. Here
817 813 # we must *not* call any traceback construction again,
818 814 # because that would mess up use of %debug later on. So we
819 815 # simply report the failure and move on. The only
820 816 # limitation will be that this frame won't have locals
821 817 # listed in the call signature. Quite subtle problem...
822 818 # I can't think of a good way to validate this in a unit
823 819 # test, but running a script consisting of:
824 820 # dict( (k,v.strip()) for (k,v) in range(10) )
825 821 # will illustrate the error, if this exception catch is
826 822 # disabled.
827 823 call = tpl_call_fail % func
828 824
829 825 # Initialize a list of names on the current line, which the
830 826 # tokenizer below will populate.
831 827 names = []
832 828
833 829 def tokeneater(token_type, token, start, end, line):
834 830 """Stateful tokeneater which builds dotted names.
835 831
836 832 The list of names it appends to (from the enclosing scope) can
837 833 contain repeated composite names. This is unavoidable, since
838 834 there is no way to disambguate partial dotted structures until
839 835 the full list is known. The caller is responsible for pruning
840 836 the final list of duplicates before using it."""
841 837
842 838 # build composite names
843 839 if token == '.':
844 840 try:
845 841 names[-1] += '.'
846 842 # store state so the next token is added for x.y.z names
847 843 tokeneater.name_cont = True
848 844 return
849 845 except IndexError:
850 846 pass
851 847 if token_type == tokenize.NAME and token not in keyword.kwlist:
852 848 if tokeneater.name_cont:
853 849 # Dotted names
854 850 names[-1] += token
855 851 tokeneater.name_cont = False
856 852 else:
857 853 # Regular new names. We append everything, the caller
858 854 # will be responsible for pruning the list later. It's
859 855 # very tricky to try to prune as we go, b/c composite
860 856 # names can fool us. The pruning at the end is easy
861 857 # to do (or the caller can print a list with repeated
862 858 # names if so desired.
863 859 names.append(token)
864 860 elif token_type == tokenize.NEWLINE:
865 861 raise IndexError
866 862 # we need to store a bit of state in the tokenizer to build
867 863 # dotted names
868 864 tokeneater.name_cont = False
869 865
870 866 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
871 867 line = getline(file, lnum[0])
872 868 lnum[0] += 1
873 869 return line
874 870
875 871 # Build the list of names on this line of code where the exception
876 872 # occurred.
877 873 try:
878 874 # This builds the names list in-place by capturing it from the
879 875 # enclosing scope.
880 876 for token in generate_tokens(linereader):
881 877 tokeneater(*token)
882 878 except (IndexError, UnicodeDecodeError):
883 879 # signals exit of tokenizer
884 880 pass
885 881 except tokenize.TokenError,msg:
886 882 _m = ("An unexpected error occurred while tokenizing input\n"
887 883 "The following traceback may be corrupted or invalid\n"
888 884 "The error message is: %s\n" % msg)
889 885 error(_m)
890 886
891 887 # prune names list of duplicates, but keep the right order
892 888 unique_names = uniq_stable(names)
893 889
894 890 # Start loop over vars
895 891 lvals = []
896 892 if self.include_vars:
897 893 for name_full in unique_names:
898 894 name_base = name_full.split('.',1)[0]
899 895 if name_base in frame.f_code.co_varnames:
900 896 if locals.has_key(name_base):
901 897 try:
902 898 value = repr(eval(name_full,locals))
903 899 except:
904 900 value = undefined
905 901 else:
906 902 value = undefined
907 903 name = tpl_local_var % name_full
908 904 else:
909 905 if frame.f_globals.has_key(name_base):
910 906 try:
911 907 value = repr(eval(name_full,frame.f_globals))
912 908 except:
913 909 value = undefined
914 910 else:
915 911 value = undefined
916 912 name = tpl_global_var % name_full
917 913 lvals.append(tpl_name_val % (name,value))
918 914 if lvals:
919 915 lvals = '%s%s' % (indent,em_normal.join(lvals))
920 916 else:
921 917 lvals = ''
922 918
923 919 level = '%s %s\n' % (link,call)
924 920
925 921 if index is None:
926 922 frames.append(level)
927 923 else:
928 924 frames.append('%s%s' % (level,''.join(
929 925 _format_traceback_lines(lnum,index,lines,Colors,lvals,
930 926 col_scheme))))
931 927
932 928 # Get (safely) a string form of the exception info
933 929 try:
934 930 etype_str,evalue_str = map(str,(etype,evalue))
935 931 except:
936 932 # User exception is improperly defined.
937 933 etype,evalue = str,sys.exc_info()[:2]
938 934 etype_str,evalue_str = map(str,(etype,evalue))
939 935 # ... and format it
940 936 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
941 937 ColorsNormal, evalue_str)]
942 938 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
943 939 try:
944 940 names = [w for w in dir(evalue) if isinstance(w, basestring)]
945 941 except:
946 942 # Every now and then, an object with funny inernals blows up
947 943 # when dir() is called on it. We do the best we can to report
948 944 # the problem and continue
949 945 _m = '%sException reporting error (object with broken dir())%s:'
950 946 exception.append(_m % (Colors.excName,ColorsNormal))
951 947 etype_str,evalue_str = map(str,sys.exc_info()[:2])
952 948 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
953 949 ColorsNormal, evalue_str))
954 950 names = []
955 951 for name in names:
956 952 value = text_repr(getattr(evalue, name))
957 953 exception.append('\n%s%s = %s' % (indent, name, value))
958 954
959 955 # vds: >>
960 956 if records:
961 957 filepath, lnum = records[-1][1:3]
962 958 #print "file:", str(file), "linenb", str(lnum) # dbg
963 959 filepath = os.path.abspath(filepath)
964 960 ipinst = ipapi.get()
965 961 if ipinst is not None:
966 962 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
967 963 # vds: <<
968 964
969 965 # return all our info assembled as a single string
970 966 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
971 967 return [head] + frames + [''.join(exception[0])]
972 968
973 969 def debugger(self,force=False):
974 970 """Call up the pdb debugger if desired, always clean up the tb
975 971 reference.
976 972
977 973 Keywords:
978 974
979 975 - force(False): by default, this routine checks the instance call_pdb
980 976 flag and does not actually invoke the debugger if the flag is false.
981 977 The 'force' option forces the debugger to activate even if the flag
982 978 is false.
983 979
984 980 If the call_pdb flag is set, the pdb interactive debugger is
985 981 invoked. In all cases, the self.tb reference to the current traceback
986 982 is deleted to prevent lingering references which hamper memory
987 983 management.
988 984
989 985 Note that each call to pdb() does an 'import readline', so if your app
990 986 requires a special setup for the readline completers, you'll have to
991 987 fix that by hand after invoking the exception handler."""
992 988
993 989 if force or self.call_pdb:
994 990 if self.pdb is None:
995 991 self.pdb = debugger.Pdb(
996 992 self.color_scheme_table.active_scheme_name)
997 993 # the system displayhook may have changed, restore the original
998 994 # for pdb
999 995 display_trap = DisplayTrap(hook=sys.__displayhook__)
1000 996 with display_trap:
1001 997 self.pdb.reset()
1002 998 # Find the right frame so we don't pop up inside ipython itself
1003 999 if hasattr(self,'tb') and self.tb is not None:
1004 1000 etb = self.tb
1005 1001 else:
1006 1002 etb = self.tb = sys.last_traceback
1007 1003 while self.tb is not None and self.tb.tb_next is not None:
1008 1004 self.tb = self.tb.tb_next
1009 1005 if etb and etb.tb_next:
1010 1006 etb = etb.tb_next
1011 1007 self.pdb.botframe = etb.tb_frame
1012 1008 self.pdb.interaction(self.tb.tb_frame, self.tb)
1013 1009
1014 1010 if hasattr(self,'tb'):
1015 1011 del self.tb
1016 1012
1017 1013 def handler(self, info=None):
1018 1014 (etype, evalue, etb) = info or sys.exc_info()
1019 1015 self.tb = etb
1020 1016 ostream = self.ostream
1021 1017 ostream.flush()
1022 1018 ostream.write(self.text(etype, evalue, etb))
1023 1019 ostream.write('\n')
1024 1020 ostream.flush()
1025 1021
1026 1022 # Changed so an instance can just be called as VerboseTB_inst() and print
1027 1023 # out the right info on its own.
1028 1024 def __call__(self, etype=None, evalue=None, etb=None):
1029 1025 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1030 1026 if etb is None:
1031 1027 self.handler()
1032 1028 else:
1033 1029 self.handler((etype, evalue, etb))
1034 1030 try:
1035 1031 self.debugger()
1036 1032 except KeyboardInterrupt:
1037 1033 print "\nKeyboardInterrupt"
1038 1034
1039 1035 #----------------------------------------------------------------------------
1040 1036 class FormattedTB(VerboseTB, ListTB):
1041 1037 """Subclass ListTB but allow calling with a traceback.
1042 1038
1043 1039 It can thus be used as a sys.excepthook for Python > 2.1.
1044 1040
1045 1041 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1046 1042
1047 1043 Allows a tb_offset to be specified. This is useful for situations where
1048 1044 one needs to remove a number of topmost frames from the traceback (such as
1049 1045 occurs with python programs that themselves execute other python code,
1050 1046 like Python shells). """
1051 1047
1052 1048 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1053 1049 ostream=None,
1054 1050 tb_offset=0, long_header=False, include_vars=False,
1055 1051 check_cache=None):
1056 1052
1057 1053 # NEVER change the order of this list. Put new modes at the end:
1058 1054 self.valid_modes = ['Plain','Context','Verbose']
1059 1055 self.verbose_modes = self.valid_modes[1:3]
1060 1056
1061 1057 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1062 1058 ostream=ostream, tb_offset=tb_offset,
1063 1059 long_header=long_header, include_vars=include_vars,
1064 1060 check_cache=check_cache)
1065 1061
1066 1062 # Different types of tracebacks are joined with different separators to
1067 1063 # form a single string. They are taken from this dict
1068 1064 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1069 1065 # set_mode also sets the tb_join_char attribute
1070 1066 self.set_mode(mode)
1071 1067
1072 1068 def _extract_tb(self,tb):
1073 1069 if tb:
1074 1070 return traceback.extract_tb(tb)
1075 1071 else:
1076 1072 return None
1077 1073
1078 1074 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1079 1075 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1080 1076 mode = self.mode
1081 1077 if mode in self.verbose_modes:
1082 1078 # Verbose modes need a full traceback
1083 1079 return VerboseTB.structured_traceback(
1084 1080 self, etype, value, tb, tb_offset, context
1085 1081 )
1086 1082 else:
1087 1083 # We must check the source cache because otherwise we can print
1088 1084 # out-of-date source code.
1089 1085 self.check_cache()
1090 1086 # Now we can extract and format the exception
1091 1087 elist = self._extract_tb(tb)
1092 1088 return ListTB.structured_traceback(
1093 1089 self, etype, value, elist, tb_offset, context
1094 1090 )
1095 1091
1096 1092 def stb2text(self, stb):
1097 1093 """Convert a structured traceback (a list) to a string."""
1098 1094 return self.tb_join_char.join(stb)
1099 1095
1100 1096
1101 1097 def set_mode(self,mode=None):
1102 1098 """Switch to the desired mode.
1103 1099
1104 1100 If mode is not specified, cycles through the available modes."""
1105 1101
1106 1102 if not mode:
1107 1103 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1108 1104 len(self.valid_modes)
1109 1105 self.mode = self.valid_modes[new_idx]
1110 1106 elif mode not in self.valid_modes:
1111 1107 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1112 1108 'Valid modes: '+str(self.valid_modes)
1113 1109 else:
1114 1110 self.mode = mode
1115 1111 # include variable details only in 'Verbose' mode
1116 1112 self.include_vars = (self.mode == self.valid_modes[2])
1117 1113 # Set the join character for generating text tracebacks
1118 1114 self.tb_join_char = self._join_chars[self.mode]
1119 1115
1120 1116 # some convenient shorcuts
1121 1117 def plain(self):
1122 1118 self.set_mode(self.valid_modes[0])
1123 1119
1124 1120 def context(self):
1125 1121 self.set_mode(self.valid_modes[1])
1126 1122
1127 1123 def verbose(self):
1128 1124 self.set_mode(self.valid_modes[2])
1129 1125
1130 1126 #----------------------------------------------------------------------------
1131 1127 class AutoFormattedTB(FormattedTB):
1132 1128 """A traceback printer which can be called on the fly.
1133 1129
1134 1130 It will find out about exceptions by itself.
1135 1131
1136 1132 A brief example:
1137 1133
1138 1134 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1139 1135 try:
1140 1136 ...
1141 1137 except:
1142 1138 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1143 1139 """
1144 1140
1145 1141 def __call__(self,etype=None,evalue=None,etb=None,
1146 1142 out=None,tb_offset=None):
1147 1143 """Print out a formatted exception traceback.
1148 1144
1149 1145 Optional arguments:
1150 1146 - out: an open file-like object to direct output to.
1151 1147
1152 1148 - tb_offset: the number of frames to skip over in the stack, on a
1153 1149 per-call basis (this overrides temporarily the instance's tb_offset
1154 1150 given at initialization time. """
1155 1151
1156 1152
1157 1153 if out is None:
1158 1154 out = self.ostream
1159 1155 out.flush()
1160 1156 out.write(self.text(etype, evalue, etb, tb_offset))
1161 1157 out.write('\n')
1162 1158 out.flush()
1163 1159 # FIXME: we should remove the auto pdb behavior from here and leave
1164 1160 # that to the clients.
1165 1161 try:
1166 1162 self.debugger()
1167 1163 except KeyboardInterrupt:
1168 1164 print "\nKeyboardInterrupt"
1169 1165
1170 1166 def structured_traceback(self, etype=None, value=None, tb=None,
1171 1167 tb_offset=None, context=5):
1172 1168 if etype is None:
1173 1169 etype,value,tb = sys.exc_info()
1174 1170 self.tb = tb
1175 1171 return FormattedTB.structured_traceback(
1176 1172 self, etype, value, tb, tb_offset, context)
1177 1173
1178 1174 #---------------------------------------------------------------------------
1179 1175
1180 1176 # A simple class to preserve Nathan's original functionality.
1181 1177 class ColorTB(FormattedTB):
1182 1178 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1183 1179 def __init__(self,color_scheme='Linux',call_pdb=0):
1184 1180 FormattedTB.__init__(self,color_scheme=color_scheme,
1185 1181 call_pdb=call_pdb)
1186 1182
1187 1183
1188 1184 class SyntaxTB(ListTB):
1189 1185 """Extension which holds some state: the last exception value"""
1190 1186
1191 1187 def __init__(self,color_scheme = 'NoColor'):
1192 1188 ListTB.__init__(self,color_scheme)
1193 1189 self.last_syntax_error = None
1194 1190
1195 1191 def __call__(self, etype, value, elist):
1196 1192 self.last_syntax_error = value
1197 1193 ListTB.__call__(self,etype,value,elist)
1198 1194
1199 1195 def clear_err_state(self):
1200 1196 """Return the current error state and clear it"""
1201 1197 e = self.last_syntax_error
1202 1198 self.last_syntax_error = None
1203 1199 return e
1204 1200
1205 1201 def stb2text(self, stb):
1206 1202 """Convert a structured traceback (a list) to a string."""
1207 1203 return ''.join(stb)
1208 1204
1209 1205
1210 1206 #----------------------------------------------------------------------------
1211 1207 # module testing (minimal)
1212 1208 if __name__ == "__main__":
1213 1209 def spam(c, (d, e)):
1214 1210 x = c + d
1215 1211 y = c * d
1216 1212 foo(x, y)
1217 1213
1218 1214 def foo(a, b, bar=1):
1219 1215 eggs(a, b + bar)
1220 1216
1221 1217 def eggs(f, g, z=globals()):
1222 1218 h = f + g
1223 1219 i = f - g
1224 1220 return h / i
1225 1221
1226 1222 print ''
1227 1223 print '*** Before ***'
1228 1224 try:
1229 1225 print spam(1, (2, 3))
1230 1226 except:
1231 1227 traceback.print_exc()
1232 1228 print ''
1233 1229
1234 1230 handler = ColorTB()
1235 1231 print '*** ColorTB ***'
1236 1232 try:
1237 1233 print spam(1, (2, 3))
1238 1234 except:
1239 1235 apply(handler, sys.exc_info() )
1240 1236 print ''
1241 1237
1242 1238 handler = VerboseTB()
1243 1239 print '*** VerboseTB ***'
1244 1240 try:
1245 1241 print spam(1, (2, 3))
1246 1242 except:
1247 1243 apply(handler, sys.exc_info() )
1248 1244 print ''
1249 1245
@@ -1,182 +1,179 b''
1 1 """Test suite for the irunner module.
2 2
3 3 Not the most elegant or fine-grained, but it does cover at least the bulk
4 4 functionality."""
5 5
6 6 # Global to make tests extra verbose and help debugging
7 7 VERBOSE = True
8 8
9 9 # stdlib imports
10 10 import StringIO
11 11 import sys
12 12 import unittest
13 13
14 14 # IPython imports
15 15 from IPython.lib import irunner
16 from IPython.testing.decorators import known_failure_py3
17 16 from IPython.utils.py3compat import doctest_refactor_print
18 17
19 18 # Testing code begins
20 19 class RunnerTestCase(unittest.TestCase):
21 20
22 21 def setUp(self):
23 22 self.out = StringIO.StringIO()
24 23 #self.out = sys.stdout
25 24
26 25 def _test_runner(self,runner,source,output):
27 26 """Test that a given runner's input/output match."""
28 27
29 28 runner.run_source(source)
30 29 out = self.out.getvalue()
31 30 #out = ''
32 31 # this output contains nasty \r\n lineends, and the initial ipython
33 32 # banner. clean it up for comparison, removing lines of whitespace
34 33 output_l = [l for l in output.splitlines() if l and not l.isspace()]
35 34 out_l = [l for l in out.splitlines() if l and not l.isspace()]
36 35 mismatch = 0
37 36 if len(output_l) != len(out_l):
38 37 message = ("Mismatch in number of lines\n\n"
39 38 "Expected:\n"
40 39 "~~~~~~~~~\n"
41 40 "%s\n\n"
42 41 "Got:\n"
43 42 "~~~~~~~~~\n"
44 43 "%s"
45 44 ) % ("\n".join(output_l), "\n".join(out_l))
46 45 self.fail(message)
47 46 for n in range(len(output_l)):
48 47 # Do a line-by-line comparison
49 48 ol1 = output_l[n].strip()
50 49 ol2 = out_l[n].strip()
51 50 if ol1 != ol2:
52 51 mismatch += 1
53 52 if VERBOSE:
54 53 print '<<< line %s does not match:' % n
55 54 print repr(ol1)
56 55 print repr(ol2)
57 56 print '>>>'
58 57 self.assert_(mismatch==0,'Number of mismatched lines: %s' %
59 58 mismatch)
60 59
61 # The SyntaxError appears differently in Python 3, for some reason.
62 @known_failure_py3
63 60 def testIPython(self):
64 61 """Test the IPython runner."""
65 62 source = doctest_refactor_print("""
66 63 print 'hello, this is python'
67 64 # some more code
68 65 x=1;y=2
69 66 x+y**2
70 67
71 68 # An example of autocall functionality
72 69 from math import *
73 70 autocall 1
74 71 cos pi
75 72 autocall 0
76 73 cos pi
77 74 cos(pi)
78 75
79 76 for i in range(5):
80 77 print i
81 78
82 79 print "that's all folks!"
83 80
84 81 exit
85 82 """)
86 83 output = doctest_refactor_print("""\
87 84 In [1]: print 'hello, this is python'
88 85 hello, this is python
89 86
90 87
91 88 # some more code
92 89 In [2]: x=1;y=2
93 90
94 91 In [3]: x+y**2
95 92 Out[3]: 5
96 93
97 94
98 95 # An example of autocall functionality
99 96 In [4]: from math import *
100 97
101 98 In [5]: autocall 1
102 99 Automatic calling is: Smart
103 100
104 101 In [6]: cos pi
105 102 ------> cos(pi)
106 103 Out[6]: -1.0
107 104
108 105 In [7]: autocall 0
109 106 Automatic calling is: OFF
110 107
111 108 In [8]: cos pi
112 109 File "<ipython-input-8-6bd7313dd9a9>", line 1
113 110 cos pi
114 111 ^
115 112 SyntaxError: invalid syntax
116 113
117 114
118 115 In [9]: cos(pi)
119 116 Out[9]: -1.0
120 117
121 118
122 119 In [10]: for i in range(5):
123 120 ....: print i
124 121 ....:
125 122 0
126 123 1
127 124 2
128 125 3
129 126 4
130 127
131 128 In [11]: print "that's all folks!"
132 129 that's all folks!
133 130
134 131
135 132 In [12]: exit
136 133 """)
137 134 runner = irunner.IPythonRunner(out=self.out)
138 135 self._test_runner(runner,source,output)
139 136
140 137 def testPython(self):
141 138 """Test the Python runner."""
142 139 runner = irunner.PythonRunner(out=self.out)
143 140 source = doctest_refactor_print("""
144 141 print 'hello, this is python'
145 142
146 143 # some more code
147 144 x=1;y=2
148 145 x+y**2
149 146
150 147 from math import *
151 148 cos(pi)
152 149
153 150 for i in range(5):
154 151 print i
155 152
156 153 print "that's all folks!"
157 154 """)
158 155 output = doctest_refactor_print("""\
159 156 >>> print 'hello, this is python'
160 157 hello, this is python
161 158
162 159 # some more code
163 160 >>> x=1;y=2
164 161 >>> x+y**2
165 162 5
166 163
167 164 >>> from math import *
168 165 >>> cos(pi)
169 166 -1.0
170 167
171 168 >>> for i in range(5):
172 169 ... print i
173 170 ...
174 171 0
175 172 1
176 173 2
177 174 3
178 175 4
179 176 >>> print "that's all folks!"
180 177 that's all folks!
181 178 """)
182 179 self._test_runner(runner,source,output)
General Comments 0
You need to be logged in to leave comments. Login now