##// END OF EJS Templates
Lots of work on exception handling, including tests for traceback printing....
Fernando Perez -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -0,0 +1,32 b''
1 """Error script. DO NOT EDIT FURTHER! It will break exception doctests!!!"""
2 import sys
3
4 def div0():
5 "foo"
6 x = 1
7 y = 0
8 x/y
9
10 def sysexit(stat, mode):
11 raise SystemExit(stat, 'Mode = %s' % mode)
12
13 def bar(mode):
14 "bar"
15 if mode=='div':
16 div0()
17 elif mode=='exit':
18 try:
19 stat = int(sys.argv[2])
20 except:
21 stat = 1
22 sysexit(stat, mode)
23 else:
24 raise ValueError('Unknown mode')
25
26 if __name__ == '__main__':
27 try:
28 mode = sys.argv[1]
29 except IndexError:
30 mode = 'div'
31
32 bar(mode)
@@ -1,2529 +1,2528 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Main IPython Component
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 9 # Copyright (C) 2008-2009 The IPython Development Team
10 10 #
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-----------------------------------------------------------------------------
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Imports
17 17 #-----------------------------------------------------------------------------
18 18
19 19 from __future__ import with_statement
20 20 from __future__ import absolute_import
21 21
22 22 import __builtin__
23 23 import StringIO
24 24 import bdb
25 25 import codeop
26 26 import exceptions
27 27 import new
28 28 import os
29 29 import re
30 30 import string
31 31 import sys
32 32 import tempfile
33 33 from contextlib import nested
34 34
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import prefilter
38 38 from IPython.core import shadowns
39 39 from IPython.core import ultratb
40 40 from IPython.core.alias import AliasManager
41 41 from IPython.core.builtin_trap import BuiltinTrap
42 42 from IPython.core.component import Component
43 43 from IPython.core.display_trap import DisplayTrap
44 44 from IPython.core.error import TryNext, UsageError
45 45 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
46 46 from IPython.core.logger import Logger
47 47 from IPython.core.magic import Magic
48 48 from IPython.core.prefilter import PrefilterManager
49 49 from IPython.core.prompts import CachedOutput
50 50 from IPython.core.pylabtools import pylab_activate
51 51 from IPython.core.usage import interactive_usage, default_banner
52 52 from IPython.external.Itpl import ItplNS
53 53 from IPython.lib.inputhook import enable_gui
54 54 from IPython.lib.backgroundjobs import BackgroundJobManager
55 55 from IPython.utils import PyColorize
56 56 from IPython.utils import pickleshare
57 57 from IPython.utils.genutils import get_ipython_dir
58 58 from IPython.utils.ipstruct import Struct
59 59 from IPython.utils.platutils import toggle_set_term_title, set_term_title
60 60 from IPython.utils.strdispatch import StrDispatch
61 61 from IPython.utils.syspathcontext import prepended_to_syspath
62 62
63 63 # XXX - need to clean up this import * line
64 64 from IPython.utils.genutils import *
65 65
66 66 # from IPython.utils import growl
67 67 # growl.start("IPython")
68 68
69 69 from IPython.utils.traitlets import (
70 70 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
71 71 )
72 72
73 73 #-----------------------------------------------------------------------------
74 74 # Globals
75 75 #-----------------------------------------------------------------------------
76 76
77 77 # store the builtin raw_input globally, and use this always, in case user code
78 78 # overwrites it (like wx.py.PyShell does)
79 79 raw_input_original = raw_input
80 80
81 81 # compiled regexps for autoindent management
82 82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83 83
84 84 #-----------------------------------------------------------------------------
85 85 # Utilities
86 86 #-----------------------------------------------------------------------------
87 87
88 88 ini_spaces_re = re.compile(r'^(\s+)')
89 89
90 90
91 91 def num_ini_spaces(strng):
92 92 """Return the number of initial spaces in a string"""
93 93
94 94 ini_spaces = ini_spaces_re.match(strng)
95 95 if ini_spaces:
96 96 return ini_spaces.end()
97 97 else:
98 98 return 0
99 99
100 100
101 101 def softspace(file, newvalue):
102 102 """Copied from code.py, to remove the dependency"""
103 103
104 104 oldvalue = 0
105 105 try:
106 106 oldvalue = file.softspace
107 107 except AttributeError:
108 108 pass
109 109 try:
110 110 file.softspace = newvalue
111 111 except (AttributeError, TypeError):
112 112 # "attribute-less object" or "read-only attributes"
113 113 pass
114 114 return oldvalue
115 115
116 116
117 117 def no_op(*a, **kw): pass
118 118
119 119 class SpaceInInput(exceptions.Exception): pass
120 120
121 121 class Bunch: pass
122 122
123 123 class InputList(list):
124 124 """Class to store user input.
125 125
126 126 It's basically a list, but slices return a string instead of a list, thus
127 127 allowing things like (assuming 'In' is an instance):
128 128
129 129 exec In[4:7]
130 130
131 131 or
132 132
133 133 exec In[5:9] + In[14] + In[21:25]"""
134 134
135 135 def __getslice__(self,i,j):
136 136 return ''.join(list.__getslice__(self,i,j))
137 137
138 138
139 139 class SyntaxTB(ultratb.ListTB):
140 140 """Extension which holds some state: the last exception value"""
141 141
142 142 def __init__(self,color_scheme = 'NoColor'):
143 143 ultratb.ListTB.__init__(self,color_scheme)
144 144 self.last_syntax_error = None
145 145
146 146 def __call__(self, etype, value, elist):
147 147 self.last_syntax_error = value
148 148 ultratb.ListTB.__call__(self,etype,value,elist)
149 149
150 150 def clear_err_state(self):
151 151 """Return the current error state and clear it"""
152 152 e = self.last_syntax_error
153 153 self.last_syntax_error = None
154 154 return e
155 155
156 156
157 157 def get_default_editor():
158 158 try:
159 159 ed = os.environ['EDITOR']
160 160 except KeyError:
161 161 if os.name == 'posix':
162 162 ed = 'vi' # the only one guaranteed to be there!
163 163 else:
164 164 ed = 'notepad' # same in Windows!
165 165 return ed
166 166
167 167
168 168 def get_default_colors():
169 169 if sys.platform=='darwin':
170 170 return "LightBG"
171 171 elif os.name=='nt':
172 172 return 'Linux'
173 173 else:
174 174 return 'Linux'
175 175
176 176
177 177 class SeparateStr(Str):
178 178 """A Str subclass to validate separate_in, separate_out, etc.
179 179
180 180 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
181 181 """
182 182
183 183 def validate(self, obj, value):
184 184 if value == '0': value = ''
185 185 value = value.replace('\\n','\n')
186 186 return super(SeparateStr, self).validate(obj, value)
187 187
188 188
189 189 def make_user_namespaces(user_ns=None, user_global_ns=None):
190 190 """Return a valid local and global user interactive namespaces.
191 191
192 192 This builds a dict with the minimal information needed to operate as a
193 193 valid IPython user namespace, which you can pass to the various
194 194 embedding classes in ipython. The default implementation returns the
195 195 same dict for both the locals and the globals to allow functions to
196 196 refer to variables in the namespace. Customized implementations can
197 197 return different dicts. The locals dictionary can actually be anything
198 198 following the basic mapping protocol of a dict, but the globals dict
199 199 must be a true dict, not even a subclass. It is recommended that any
200 200 custom object for the locals namespace synchronize with the globals
201 201 dict somehow.
202 202
203 203 Raises TypeError if the provided globals namespace is not a true dict.
204 204
205 205 Parameters
206 206 ----------
207 207 user_ns : dict-like, optional
208 208 The current user namespace. The items in this namespace should
209 209 be included in the output. If None, an appropriate blank
210 210 namespace should be created.
211 211 user_global_ns : dict, optional
212 212 The current user global namespace. The items in this namespace
213 213 should be included in the output. If None, an appropriate
214 214 blank namespace should be created.
215 215
216 216 Returns
217 217 -------
218 218 A pair of dictionary-like object to be used as the local namespace
219 219 of the interpreter and a dict to be used as the global namespace.
220 220 """
221 221
222 222 if user_ns is None:
223 223 # Set __name__ to __main__ to better match the behavior of the
224 224 # normal interpreter.
225 225 user_ns = {'__name__' :'__main__',
226 226 '__builtins__' : __builtin__,
227 227 }
228 228 else:
229 229 user_ns.setdefault('__name__','__main__')
230 230 user_ns.setdefault('__builtins__',__builtin__)
231 231
232 232 if user_global_ns is None:
233 233 user_global_ns = user_ns
234 234 if type(user_global_ns) is not dict:
235 235 raise TypeError("user_global_ns must be a true dict; got %r"
236 236 % type(user_global_ns))
237 237
238 238 return user_ns, user_global_ns
239 239
240 240 #-----------------------------------------------------------------------------
241 241 # Main IPython class
242 242 #-----------------------------------------------------------------------------
243 243
244 244
245 245 class InteractiveShell(Component, Magic):
246 246 """An enhanced, interactive shell for Python."""
247 247
248 248 autocall = Enum((0,1,2), default_value=1, config=True)
249 249 autoedit_syntax = CBool(False, config=True)
250 250 autoindent = CBool(True, config=True)
251 251 automagic = CBool(True, config=True)
252 252 banner = Str('')
253 253 banner1 = Str(default_banner, config=True)
254 254 banner2 = Str('', config=True)
255 255 cache_size = Int(1000, config=True)
256 256 color_info = CBool(True, config=True)
257 257 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
258 258 default_value=get_default_colors(), config=True)
259 259 confirm_exit = CBool(True, config=True)
260 260 debug = CBool(False, config=True)
261 261 deep_reload = CBool(False, config=True)
262 262 # This display_banner only controls whether or not self.show_banner()
263 263 # is called when mainloop/interact are called. The default is False
264 264 # because for the terminal based application, the banner behavior
265 265 # is controlled by Global.display_banner, which IPythonApp looks at
266 266 # to determine if *it* should call show_banner() by hand or not.
267 267 display_banner = CBool(False) # This isn't configurable!
268 268 embedded = CBool(False)
269 269 embedded_active = CBool(False)
270 270 editor = Str(get_default_editor(), config=True)
271 271 filename = Str("<ipython console>")
272 272 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
273 273 logstart = CBool(False, config=True)
274 274 logfile = Str('', config=True)
275 275 logappend = Str('', config=True)
276 276 object_info_string_level = Enum((0,1,2), default_value=0,
277 277 config=True)
278 278 pager = Str('less', config=True)
279 279 pdb = CBool(False, config=True)
280 280 pprint = CBool(True, config=True)
281 281 profile = Str('', config=True)
282 282 prompt_in1 = Str('In [\\#]: ', config=True)
283 283 prompt_in2 = Str(' .\\D.: ', config=True)
284 284 prompt_out = Str('Out[\\#]: ', config=True)
285 285 prompts_pad_left = CBool(True, config=True)
286 286 quiet = CBool(False, config=True)
287 287
288 288 readline_use = CBool(True, config=True)
289 289 readline_merge_completions = CBool(True, config=True)
290 290 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
291 291 readline_remove_delims = Str('-/~', config=True)
292 292 readline_parse_and_bind = List([
293 293 'tab: complete',
294 294 '"\C-l": possible-completions',
295 295 'set show-all-if-ambiguous on',
296 296 '"\C-o": tab-insert',
297 297 '"\M-i": " "',
298 298 '"\M-o": "\d\d\d\d"',
299 299 '"\M-I": "\d\d\d\d"',
300 300 '"\C-r": reverse-search-history',
301 301 '"\C-s": forward-search-history',
302 302 '"\C-p": history-search-backward',
303 303 '"\C-n": history-search-forward',
304 304 '"\e[A": history-search-backward',
305 305 '"\e[B": history-search-forward',
306 306 '"\C-k": kill-line',
307 307 '"\C-u": unix-line-discard',
308 308 ], allow_none=False, config=True)
309 309
310 310 screen_length = Int(0, config=True)
311 311
312 312 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
313 313 separate_in = SeparateStr('\n', config=True)
314 314 separate_out = SeparateStr('', config=True)
315 315 separate_out2 = SeparateStr('', config=True)
316 316
317 317 system_header = Str('IPython system call: ', config=True)
318 318 system_verbose = CBool(False, config=True)
319 319 term_title = CBool(False, config=True)
320 320 wildcards_case_sensitive = CBool(True, config=True)
321 321 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
322 322 default_value='Context', config=True)
323 323
324 324 autoexec = List(allow_none=False)
325 325
326 326 # class attribute to indicate whether the class supports threads or not.
327 327 # Subclasses with thread support should override this as needed.
328 328 isthreaded = False
329 329
330 330 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
331 331 user_ns=None, user_global_ns=None,
332 332 banner1=None, banner2=None, display_banner=None,
333 333 custom_exceptions=((),None)):
334 334
335 335 # This is where traitlets with a config_key argument are updated
336 336 # from the values on config.
337 337 super(InteractiveShell, self).__init__(parent, config=config)
338 338
339 339 # These are relatively independent and stateless
340 340 self.init_ipython_dir(ipython_dir)
341 341 self.init_instance_attrs()
342 342 self.init_term_title()
343 343 self.init_usage(usage)
344 344 self.init_banner(banner1, banner2, display_banner)
345 345
346 346 # Create namespaces (user_ns, user_global_ns, etc.)
347 347 self.init_create_namespaces(user_ns, user_global_ns)
348 348 # This has to be done after init_create_namespaces because it uses
349 349 # something in self.user_ns, but before init_sys_modules, which
350 350 # is the first thing to modify sys.
351 351 self.save_sys_module_state()
352 352 self.init_sys_modules()
353 353
354 354 self.init_history()
355 355 self.init_encoding()
356 356 self.init_prefilter()
357 357
358 358 Magic.__init__(self, self)
359 359
360 360 self.init_syntax_highlighting()
361 361 self.init_hooks()
362 362 self.init_pushd_popd_magic()
363 363 self.init_traceback_handlers(custom_exceptions)
364 364 self.init_user_ns()
365 365 self.init_logger()
366 366 self.init_alias()
367 367 self.init_builtins()
368 368
369 369 # pre_config_initialization
370 370 self.init_shadow_hist()
371 371
372 372 # The next section should contain averything that was in ipmaker.
373 373 self.init_logstart()
374 374
375 375 # The following was in post_config_initialization
376 376 self.init_inspector()
377 377 self.init_readline()
378 378 self.init_prompts()
379 379 self.init_displayhook()
380 380 self.init_reload_doctest()
381 381 self.init_magics()
382 382 self.init_pdb()
383 383 self.hooks.late_startup_hook()
384 384
385 385 def get_ipython(self):
386 386 """Return the currently running IPython instance."""
387 387 return self
388 388
389 389 #-------------------------------------------------------------------------
390 390 # Traitlet changed handlers
391 391 #-------------------------------------------------------------------------
392 392
393 393 def _banner1_changed(self):
394 394 self.compute_banner()
395 395
396 396 def _banner2_changed(self):
397 397 self.compute_banner()
398 398
399 399 def _ipython_dir_changed(self, name, new):
400 400 if not os.path.isdir(new):
401 401 os.makedirs(new, mode = 0777)
402 402 if not os.path.isdir(self.ipython_extension_dir):
403 403 os.makedirs(self.ipython_extension_dir, mode = 0777)
404 404
405 405 @property
406 406 def ipython_extension_dir(self):
407 407 return os.path.join(self.ipython_dir, 'extensions')
408 408
409 409 @property
410 410 def usable_screen_length(self):
411 411 if self.screen_length == 0:
412 412 return 0
413 413 else:
414 414 num_lines_bot = self.separate_in.count('\n')+1
415 415 return self.screen_length - num_lines_bot
416 416
417 417 def _term_title_changed(self, name, new_value):
418 418 self.init_term_title()
419 419
420 420 def set_autoindent(self,value=None):
421 421 """Set the autoindent flag, checking for readline support.
422 422
423 423 If called with no arguments, it acts as a toggle."""
424 424
425 425 if not self.has_readline:
426 426 if os.name == 'posix':
427 427 warn("The auto-indent feature requires the readline library")
428 428 self.autoindent = 0
429 429 return
430 430 if value is None:
431 431 self.autoindent = not self.autoindent
432 432 else:
433 433 self.autoindent = value
434 434
435 435 #-------------------------------------------------------------------------
436 436 # init_* methods called by __init__
437 437 #-------------------------------------------------------------------------
438 438
439 439 def init_ipython_dir(self, ipython_dir):
440 440 if ipython_dir is not None:
441 441 self.ipython_dir = ipython_dir
442 442 self.config.Global.ipython_dir = self.ipython_dir
443 443 return
444 444
445 445 if hasattr(self.config.Global, 'ipython_dir'):
446 446 self.ipython_dir = self.config.Global.ipython_dir
447 447 else:
448 448 self.ipython_dir = get_ipython_dir()
449 449
450 450 # All children can just read this
451 451 self.config.Global.ipython_dir = self.ipython_dir
452 452
453 453 def init_instance_attrs(self):
454 454 self.jobs = BackgroundJobManager()
455 455 self.more = False
456 456
457 457 # command compiler
458 458 self.compile = codeop.CommandCompiler()
459 459
460 460 # User input buffer
461 461 self.buffer = []
462 462
463 463 # Make an empty namespace, which extension writers can rely on both
464 464 # existing and NEVER being used by ipython itself. This gives them a
465 465 # convenient location for storing additional information and state
466 466 # their extensions may require, without fear of collisions with other
467 467 # ipython names that may develop later.
468 468 self.meta = Struct()
469 469
470 470 # Object variable to store code object waiting execution. This is
471 471 # used mainly by the multithreaded shells, but it can come in handy in
472 472 # other situations. No need to use a Queue here, since it's a single
473 473 # item which gets cleared once run.
474 474 self.code_to_run = None
475 475
476 476 # Flag to mark unconditional exit
477 477 self.exit_now = False
478 478
479 479 # Temporary files used for various purposes. Deleted at exit.
480 480 self.tempfiles = []
481 481
482 482 # Keep track of readline usage (later set by init_readline)
483 483 self.has_readline = False
484 484
485 485 # keep track of where we started running (mainly for crash post-mortem)
486 486 # This is not being used anywhere currently.
487 487 self.starting_dir = os.getcwd()
488 488
489 489 # Indentation management
490 490 self.indent_current_nsp = 0
491 491
492 492 def init_term_title(self):
493 493 # Enable or disable the terminal title.
494 494 if self.term_title:
495 495 toggle_set_term_title(True)
496 496 set_term_title('IPython: ' + abbrev_cwd())
497 497 else:
498 498 toggle_set_term_title(False)
499 499
500 500 def init_usage(self, usage=None):
501 501 if usage is None:
502 502 self.usage = interactive_usage
503 503 else:
504 504 self.usage = usage
505 505
506 506 def init_encoding(self):
507 507 # Get system encoding at startup time. Certain terminals (like Emacs
508 508 # under Win32 have it set to None, and we need to have a known valid
509 509 # encoding to use in the raw_input() method
510 510 try:
511 511 self.stdin_encoding = sys.stdin.encoding or 'ascii'
512 512 except AttributeError:
513 513 self.stdin_encoding = 'ascii'
514 514
515 515 def init_syntax_highlighting(self):
516 516 # Python source parser/formatter for syntax highlighting
517 517 pyformat = PyColorize.Parser().format
518 518 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
519 519
520 520 def init_pushd_popd_magic(self):
521 521 # for pushd/popd management
522 522 try:
523 523 self.home_dir = get_home_dir()
524 524 except HomeDirError, msg:
525 525 fatal(msg)
526 526
527 527 self.dir_stack = []
528 528
529 529 def init_logger(self):
530 530 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
531 531 # local shortcut, this is used a LOT
532 532 self.log = self.logger.log
533 533
534 534 def init_logstart(self):
535 535 if self.logappend:
536 536 self.magic_logstart(self.logappend + ' append')
537 537 elif self.logfile:
538 538 self.magic_logstart(self.logfile)
539 539 elif self.logstart:
540 540 self.magic_logstart()
541 541
542 542 def init_builtins(self):
543 543 self.builtin_trap = BuiltinTrap(self)
544 544
545 545 def init_inspector(self):
546 546 # Object inspector
547 547 self.inspector = oinspect.Inspector(oinspect.InspectColors,
548 548 PyColorize.ANSICodeColors,
549 549 'NoColor',
550 550 self.object_info_string_level)
551 551
552 552 def init_prompts(self):
553 553 # Initialize cache, set in/out prompts and printing system
554 554 self.outputcache = CachedOutput(self,
555 555 self.cache_size,
556 556 self.pprint,
557 557 input_sep = self.separate_in,
558 558 output_sep = self.separate_out,
559 559 output_sep2 = self.separate_out2,
560 560 ps1 = self.prompt_in1,
561 561 ps2 = self.prompt_in2,
562 562 ps_out = self.prompt_out,
563 563 pad_left = self.prompts_pad_left)
564 564
565 565 # user may have over-ridden the default print hook:
566 566 try:
567 567 self.outputcache.__class__.display = self.hooks.display
568 568 except AttributeError:
569 569 pass
570 570
571 571 def init_displayhook(self):
572 572 self.display_trap = DisplayTrap(self, self.outputcache)
573 573
574 574 def init_reload_doctest(self):
575 575 # Do a proper resetting of doctest, including the necessary displayhook
576 576 # monkeypatching
577 577 try:
578 578 doctest_reload()
579 579 except ImportError:
580 580 warn("doctest module does not exist.")
581 581
582 582 #-------------------------------------------------------------------------
583 583 # Things related to the banner
584 584 #-------------------------------------------------------------------------
585 585
586 586 def init_banner(self, banner1, banner2, display_banner):
587 587 if banner1 is not None:
588 588 self.banner1 = banner1
589 589 if banner2 is not None:
590 590 self.banner2 = banner2
591 591 if display_banner is not None:
592 592 self.display_banner = display_banner
593 593 self.compute_banner()
594 594
595 595 def show_banner(self, banner=None):
596 596 if banner is None:
597 597 banner = self.banner
598 598 self.write(banner)
599 599
600 600 def compute_banner(self):
601 601 self.banner = self.banner1 + '\n'
602 602 if self.profile:
603 603 self.banner += '\nIPython profile: %s\n' % self.profile
604 604 if self.banner2:
605 605 self.banner += '\n' + self.banner2 + '\n'
606 606
607 607 #-------------------------------------------------------------------------
608 608 # Things related to injections into the sys module
609 609 #-------------------------------------------------------------------------
610 610
611 611 def save_sys_module_state(self):
612 612 """Save the state of hooks in the sys module.
613 613
614 614 This has to be called after self.user_ns is created.
615 615 """
616 616 self._orig_sys_module_state = {}
617 617 self._orig_sys_module_state['stdin'] = sys.stdin
618 618 self._orig_sys_module_state['stdout'] = sys.stdout
619 619 self._orig_sys_module_state['stderr'] = sys.stderr
620 620 self._orig_sys_module_state['excepthook'] = sys.excepthook
621 621 try:
622 622 self._orig_sys_modules_main_name = self.user_ns['__name__']
623 623 except KeyError:
624 624 pass
625 625
626 626 def restore_sys_module_state(self):
627 627 """Restore the state of the sys module."""
628 628 try:
629 629 for k, v in self._orig_sys_module_state.items():
630 630 setattr(sys, k, v)
631 631 except AttributeError:
632 632 pass
633 633 try:
634 634 delattr(sys, 'ipcompleter')
635 635 except AttributeError:
636 636 pass
637 637 # Reset what what done in self.init_sys_modules
638 638 try:
639 639 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
640 640 except (AttributeError, KeyError):
641 641 pass
642 642
643 643 #-------------------------------------------------------------------------
644 644 # Things related to hooks
645 645 #-------------------------------------------------------------------------
646 646
647 647 def init_hooks(self):
648 648 # hooks holds pointers used for user-side customizations
649 649 self.hooks = Struct()
650 650
651 651 self.strdispatchers = {}
652 652
653 653 # Set all default hooks, defined in the IPython.hooks module.
654 654 import IPython.core.hooks
655 655 hooks = IPython.core.hooks
656 656 for hook_name in hooks.__all__:
657 657 # default hooks have priority 100, i.e. low; user hooks should have
658 658 # 0-100 priority
659 659 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
660 660
661 661 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
662 662 """set_hook(name,hook) -> sets an internal IPython hook.
663 663
664 664 IPython exposes some of its internal API as user-modifiable hooks. By
665 665 adding your function to one of these hooks, you can modify IPython's
666 666 behavior to call at runtime your own routines."""
667 667
668 668 # At some point in the future, this should validate the hook before it
669 669 # accepts it. Probably at least check that the hook takes the number
670 670 # of args it's supposed to.
671 671
672 672 f = new.instancemethod(hook,self,self.__class__)
673 673
674 674 # check if the hook is for strdispatcher first
675 675 if str_key is not None:
676 676 sdp = self.strdispatchers.get(name, StrDispatch())
677 677 sdp.add_s(str_key, f, priority )
678 678 self.strdispatchers[name] = sdp
679 679 return
680 680 if re_key is not None:
681 681 sdp = self.strdispatchers.get(name, StrDispatch())
682 682 sdp.add_re(re.compile(re_key), f, priority )
683 683 self.strdispatchers[name] = sdp
684 684 return
685 685
686 686 dp = getattr(self.hooks, name, None)
687 687 if name not in IPython.core.hooks.__all__:
688 688 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
689 689 if not dp:
690 690 dp = IPython.core.hooks.CommandChainDispatcher()
691 691
692 692 try:
693 693 dp.add(f,priority)
694 694 except AttributeError:
695 695 # it was not commandchain, plain old func - replace
696 696 dp = f
697 697
698 698 setattr(self.hooks,name, dp)
699 699
700 700 #-------------------------------------------------------------------------
701 701 # Things related to the "main" module
702 702 #-------------------------------------------------------------------------
703 703
704 704 def new_main_mod(self,ns=None):
705 705 """Return a new 'main' module object for user code execution.
706 706 """
707 707 main_mod = self._user_main_module
708 708 init_fakemod_dict(main_mod,ns)
709 709 return main_mod
710 710
711 711 def cache_main_mod(self,ns,fname):
712 712 """Cache a main module's namespace.
713 713
714 714 When scripts are executed via %run, we must keep a reference to the
715 715 namespace of their __main__ module (a FakeModule instance) around so
716 716 that Python doesn't clear it, rendering objects defined therein
717 717 useless.
718 718
719 719 This method keeps said reference in a private dict, keyed by the
720 720 absolute path of the module object (which corresponds to the script
721 721 path). This way, for multiple executions of the same script we only
722 722 keep one copy of the namespace (the last one), thus preventing memory
723 723 leaks from old references while allowing the objects from the last
724 724 execution to be accessible.
725 725
726 726 Note: we can not allow the actual FakeModule instances to be deleted,
727 727 because of how Python tears down modules (it hard-sets all their
728 728 references to None without regard for reference counts). This method
729 729 must therefore make a *copy* of the given namespace, to allow the
730 730 original module's __dict__ to be cleared and reused.
731 731
732 732
733 733 Parameters
734 734 ----------
735 735 ns : a namespace (a dict, typically)
736 736
737 737 fname : str
738 738 Filename associated with the namespace.
739 739
740 740 Examples
741 741 --------
742 742
743 743 In [10]: import IPython
744 744
745 745 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
746 746
747 747 In [12]: IPython.__file__ in _ip._main_ns_cache
748 748 Out[12]: True
749 749 """
750 750 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
751 751
752 752 def clear_main_mod_cache(self):
753 753 """Clear the cache of main modules.
754 754
755 755 Mainly for use by utilities like %reset.
756 756
757 757 Examples
758 758 --------
759 759
760 760 In [15]: import IPython
761 761
762 762 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
763 763
764 764 In [17]: len(_ip._main_ns_cache) > 0
765 765 Out[17]: True
766 766
767 767 In [18]: _ip.clear_main_mod_cache()
768 768
769 769 In [19]: len(_ip._main_ns_cache) == 0
770 770 Out[19]: True
771 771 """
772 772 self._main_ns_cache.clear()
773 773
774 774 #-------------------------------------------------------------------------
775 775 # Things related to debugging
776 776 #-------------------------------------------------------------------------
777 777
778 778 def init_pdb(self):
779 779 # Set calling of pdb on exceptions
780 780 # self.call_pdb is a property
781 781 self.call_pdb = self.pdb
782 782
783 783 def _get_call_pdb(self):
784 784 return self._call_pdb
785 785
786 786 def _set_call_pdb(self,val):
787 787
788 788 if val not in (0,1,False,True):
789 789 raise ValueError,'new call_pdb value must be boolean'
790 790
791 791 # store value in instance
792 792 self._call_pdb = val
793 793
794 794 # notify the actual exception handlers
795 795 self.InteractiveTB.call_pdb = val
796 796 if self.isthreaded:
797 797 try:
798 798 self.sys_excepthook.call_pdb = val
799 799 except:
800 800 warn('Failed to activate pdb for threaded exception handler')
801 801
802 802 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
803 803 'Control auto-activation of pdb at exceptions')
804 804
805 805 def debugger(self,force=False):
806 806 """Call the pydb/pdb debugger.
807 807
808 808 Keywords:
809 809
810 810 - force(False): by default, this routine checks the instance call_pdb
811 811 flag and does not actually invoke the debugger if the flag is false.
812 812 The 'force' option forces the debugger to activate even if the flag
813 813 is false.
814 814 """
815 815
816 816 if not (force or self.call_pdb):
817 817 return
818 818
819 819 if not hasattr(sys,'last_traceback'):
820 820 error('No traceback has been produced, nothing to debug.')
821 821 return
822 822
823 823 # use pydb if available
824 824 if debugger.has_pydb:
825 825 from pydb import pm
826 826 else:
827 827 # fallback to our internal debugger
828 828 pm = lambda : self.InteractiveTB.debugger(force=True)
829 829 self.history_saving_wrapper(pm)()
830 830
831 831 #-------------------------------------------------------------------------
832 832 # Things related to IPython's various namespaces
833 833 #-------------------------------------------------------------------------
834 834
835 835 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
836 836 # Create the namespace where the user will operate. user_ns is
837 837 # normally the only one used, and it is passed to the exec calls as
838 838 # the locals argument. But we do carry a user_global_ns namespace
839 839 # given as the exec 'globals' argument, This is useful in embedding
840 840 # situations where the ipython shell opens in a context where the
841 841 # distinction between locals and globals is meaningful. For
842 842 # non-embedded contexts, it is just the same object as the user_ns dict.
843 843
844 844 # FIXME. For some strange reason, __builtins__ is showing up at user
845 845 # level as a dict instead of a module. This is a manual fix, but I
846 846 # should really track down where the problem is coming from. Alex
847 847 # Schmolck reported this problem first.
848 848
849 849 # A useful post by Alex Martelli on this topic:
850 850 # Re: inconsistent value from __builtins__
851 851 # Von: Alex Martelli <aleaxit@yahoo.com>
852 852 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
853 853 # Gruppen: comp.lang.python
854 854
855 855 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
856 856 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
857 857 # > <type 'dict'>
858 858 # > >>> print type(__builtins__)
859 859 # > <type 'module'>
860 860 # > Is this difference in return value intentional?
861 861
862 862 # Well, it's documented that '__builtins__' can be either a dictionary
863 863 # or a module, and it's been that way for a long time. Whether it's
864 864 # intentional (or sensible), I don't know. In any case, the idea is
865 865 # that if you need to access the built-in namespace directly, you
866 866 # should start with "import __builtin__" (note, no 's') which will
867 867 # definitely give you a module. Yeah, it's somewhat confusing:-(.
868 868
869 869 # These routines return properly built dicts as needed by the rest of
870 870 # the code, and can also be used by extension writers to generate
871 871 # properly initialized namespaces.
872 872 user_ns, user_global_ns = make_user_namespaces(user_ns, user_global_ns)
873 873
874 874 # Assign namespaces
875 875 # This is the namespace where all normal user variables live
876 876 self.user_ns = user_ns
877 877 self.user_global_ns = user_global_ns
878 878
879 879 # An auxiliary namespace that checks what parts of the user_ns were
880 880 # loaded at startup, so we can list later only variables defined in
881 881 # actual interactive use. Since it is always a subset of user_ns, it
882 882 # doesn't need to be separately tracked in the ns_table.
883 883 self.user_config_ns = {}
884 884
885 885 # A namespace to keep track of internal data structures to prevent
886 886 # them from cluttering user-visible stuff. Will be updated later
887 887 self.internal_ns = {}
888 888
889 889 # Now that FakeModule produces a real module, we've run into a nasty
890 890 # problem: after script execution (via %run), the module where the user
891 891 # code ran is deleted. Now that this object is a true module (needed
892 892 # so docetst and other tools work correctly), the Python module
893 893 # teardown mechanism runs over it, and sets to None every variable
894 894 # present in that module. Top-level references to objects from the
895 895 # script survive, because the user_ns is updated with them. However,
896 896 # calling functions defined in the script that use other things from
897 897 # the script will fail, because the function's closure had references
898 898 # to the original objects, which are now all None. So we must protect
899 899 # these modules from deletion by keeping a cache.
900 900 #
901 901 # To avoid keeping stale modules around (we only need the one from the
902 902 # last run), we use a dict keyed with the full path to the script, so
903 903 # only the last version of the module is held in the cache. Note,
904 904 # however, that we must cache the module *namespace contents* (their
905 905 # __dict__). Because if we try to cache the actual modules, old ones
906 906 # (uncached) could be destroyed while still holding references (such as
907 907 # those held by GUI objects that tend to be long-lived)>
908 908 #
909 909 # The %reset command will flush this cache. See the cache_main_mod()
910 910 # and clear_main_mod_cache() methods for details on use.
911 911
912 912 # This is the cache used for 'main' namespaces
913 913 self._main_ns_cache = {}
914 914 # And this is the single instance of FakeModule whose __dict__ we keep
915 915 # copying and clearing for reuse on each %run
916 916 self._user_main_module = FakeModule()
917 917
918 918 # A table holding all the namespaces IPython deals with, so that
919 919 # introspection facilities can search easily.
920 920 self.ns_table = {'user':user_ns,
921 921 'user_global':user_global_ns,
922 922 'internal':self.internal_ns,
923 923 'builtin':__builtin__.__dict__
924 924 }
925 925
926 926 # Similarly, track all namespaces where references can be held and that
927 927 # we can safely clear (so it can NOT include builtin). This one can be
928 928 # a simple list.
929 929 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
930 930 self.internal_ns, self._main_ns_cache ]
931 931
932 932 def init_sys_modules(self):
933 933 # We need to insert into sys.modules something that looks like a
934 934 # module but which accesses the IPython namespace, for shelve and
935 935 # pickle to work interactively. Normally they rely on getting
936 936 # everything out of __main__, but for embedding purposes each IPython
937 937 # instance has its own private namespace, so we can't go shoving
938 938 # everything into __main__.
939 939
940 940 # note, however, that we should only do this for non-embedded
941 941 # ipythons, which really mimic the __main__.__dict__ with their own
942 942 # namespace. Embedded instances, on the other hand, should not do
943 943 # this because they need to manage the user local/global namespaces
944 944 # only, but they live within a 'normal' __main__ (meaning, they
945 945 # shouldn't overtake the execution environment of the script they're
946 946 # embedded in).
947 947
948 948 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
949 949
950 950 try:
951 951 main_name = self.user_ns['__name__']
952 952 except KeyError:
953 953 raise KeyError('user_ns dictionary MUST have a "__name__" key')
954 954 else:
955 955 sys.modules[main_name] = FakeModule(self.user_ns)
956 956
957 957 def init_user_ns(self):
958 958 """Initialize all user-visible namespaces to their minimum defaults.
959 959
960 960 Certain history lists are also initialized here, as they effectively
961 961 act as user namespaces.
962 962
963 963 Notes
964 964 -----
965 965 All data structures here are only filled in, they are NOT reset by this
966 966 method. If they were not empty before, data will simply be added to
967 967 therm.
968 968 """
969 969 # This function works in two parts: first we put a few things in
970 970 # user_ns, and we sync that contents into user_config_ns so that these
971 971 # initial variables aren't shown by %who. After the sync, we add the
972 972 # rest of what we *do* want the user to see with %who even on a new
973 973 # session.
974 974 ns = {}
975 975
976 976 # Put 'help' in the user namespace
977 977 try:
978 978 from site import _Helper
979 979 ns['help'] = _Helper()
980 980 except ImportError:
981 981 warn('help() not available - check site.py')
982 982
983 983 # make global variables for user access to the histories
984 984 ns['_ih'] = self.input_hist
985 985 ns['_oh'] = self.output_hist
986 986 ns['_dh'] = self.dir_hist
987 987
988 988 ns['_sh'] = shadowns
989 989
990 990 # Sync what we've added so far to user_config_ns so these aren't seen
991 991 # by %who
992 992 self.user_config_ns.update(ns)
993 993
994 994 # Now, continue adding more contents
995 995
996 996 # user aliases to input and output histories
997 997 ns['In'] = self.input_hist
998 998 ns['Out'] = self.output_hist
999 999
1000 1000 # Store myself as the public api!!!
1001 1001 ns['get_ipython'] = self.get_ipython
1002 1002
1003 1003 # And update the real user's namespace
1004 1004 self.user_ns.update(ns)
1005 1005
1006 1006
1007 1007 def reset(self):
1008 1008 """Clear all internal namespaces.
1009 1009
1010 1010 Note that this is much more aggressive than %reset, since it clears
1011 1011 fully all namespaces, as well as all input/output lists.
1012 1012 """
1013 1013 for ns in self.ns_refs_table:
1014 1014 ns.clear()
1015 1015
1016 1016 self.alias_manager.clear_aliases()
1017 1017
1018 1018 # Clear input and output histories
1019 1019 self.input_hist[:] = []
1020 1020 self.input_hist_raw[:] = []
1021 1021 self.output_hist.clear()
1022 1022
1023 1023 # Restore the user namespaces to minimal usability
1024 1024 self.init_user_ns()
1025 1025
1026 1026 # Restore the default and user aliases
1027 1027 self.alias_manager.init_aliases()
1028 1028
1029 1029 def push(self, variables, interactive=True):
1030 1030 """Inject a group of variables into the IPython user namespace.
1031 1031
1032 1032 Parameters
1033 1033 ----------
1034 1034 variables : dict, str or list/tuple of str
1035 1035 The variables to inject into the user's namespace. If a dict,
1036 1036 a simple update is done. If a str, the string is assumed to
1037 1037 have variable names separated by spaces. A list/tuple of str
1038 1038 can also be used to give the variable names. If just the variable
1039 1039 names are give (list/tuple/str) then the variable values looked
1040 1040 up in the callers frame.
1041 1041 interactive : bool
1042 1042 If True (default), the variables will be listed with the ``who``
1043 1043 magic.
1044 1044 """
1045 1045 vdict = None
1046 1046
1047 1047 # We need a dict of name/value pairs to do namespace updates.
1048 1048 if isinstance(variables, dict):
1049 1049 vdict = variables
1050 1050 elif isinstance(variables, (basestring, list, tuple)):
1051 1051 if isinstance(variables, basestring):
1052 1052 vlist = variables.split()
1053 1053 else:
1054 1054 vlist = variables
1055 1055 vdict = {}
1056 1056 cf = sys._getframe(1)
1057 1057 for name in vlist:
1058 1058 try:
1059 1059 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1060 1060 except:
1061 1061 print ('Could not get variable %s from %s' %
1062 1062 (name,cf.f_code.co_name))
1063 1063 else:
1064 1064 raise ValueError('variables must be a dict/str/list/tuple')
1065 1065
1066 1066 # Propagate variables to user namespace
1067 1067 self.user_ns.update(vdict)
1068 1068
1069 1069 # And configure interactive visibility
1070 1070 config_ns = self.user_config_ns
1071 1071 if interactive:
1072 1072 for name, val in vdict.iteritems():
1073 1073 config_ns.pop(name, None)
1074 1074 else:
1075 1075 for name,val in vdict.iteritems():
1076 1076 config_ns[name] = val
1077 1077
1078 1078 #-------------------------------------------------------------------------
1079 1079 # Things related to history management
1080 1080 #-------------------------------------------------------------------------
1081 1081
1082 1082 def init_history(self):
1083 1083 # List of input with multi-line handling.
1084 1084 self.input_hist = InputList()
1085 1085 # This one will hold the 'raw' input history, without any
1086 1086 # pre-processing. This will allow users to retrieve the input just as
1087 1087 # it was exactly typed in by the user, with %hist -r.
1088 1088 self.input_hist_raw = InputList()
1089 1089
1090 1090 # list of visited directories
1091 1091 try:
1092 1092 self.dir_hist = [os.getcwd()]
1093 1093 except OSError:
1094 1094 self.dir_hist = []
1095 1095
1096 1096 # dict of output history
1097 1097 self.output_hist = {}
1098 1098
1099 1099 # Now the history file
1100 1100 if self.profile:
1101 1101 histfname = 'history-%s' % self.profile
1102 1102 else:
1103 1103 histfname = 'history'
1104 1104 self.histfile = os.path.join(self.ipython_dir, histfname)
1105 1105
1106 1106 # Fill the history zero entry, user counter starts at 1
1107 1107 self.input_hist.append('\n')
1108 1108 self.input_hist_raw.append('\n')
1109 1109
1110 1110 def init_shadow_hist(self):
1111 1111 try:
1112 1112 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1113 1113 except exceptions.UnicodeDecodeError:
1114 1114 print "Your ipython_dir can't be decoded to unicode!"
1115 1115 print "Please set HOME environment variable to something that"
1116 1116 print r"only has ASCII characters, e.g. c:\home"
1117 1117 print "Now it is", self.ipython_dir
1118 1118 sys.exit()
1119 1119 self.shadowhist = ipcorehist.ShadowHist(self.db)
1120 1120
1121 1121 def savehist(self):
1122 1122 """Save input history to a file (via readline library)."""
1123 1123
1124 1124 try:
1125 1125 self.readline.write_history_file(self.histfile)
1126 1126 except:
1127 1127 print 'Unable to save IPython command history to file: ' + \
1128 1128 `self.histfile`
1129 1129
1130 1130 def reloadhist(self):
1131 1131 """Reload the input history from disk file."""
1132 1132
1133 1133 try:
1134 1134 self.readline.clear_history()
1135 1135 self.readline.read_history_file(self.shell.histfile)
1136 1136 except AttributeError:
1137 1137 pass
1138 1138
1139 1139 def history_saving_wrapper(self, func):
1140 1140 """ Wrap func for readline history saving
1141 1141
1142 1142 Convert func into callable that saves & restores
1143 1143 history around the call """
1144 1144
1145 1145 if not self.has_readline:
1146 1146 return func
1147 1147
1148 1148 def wrapper():
1149 1149 self.savehist()
1150 1150 try:
1151 1151 func()
1152 1152 finally:
1153 1153 readline.read_history_file(self.histfile)
1154 1154 return wrapper
1155 1155
1156 1156 #-------------------------------------------------------------------------
1157 1157 # Things related to exception handling and tracebacks (not debugging)
1158 1158 #-------------------------------------------------------------------------
1159 1159
1160 1160 def init_traceback_handlers(self, custom_exceptions):
1161 1161 # Syntax error handler.
1162 1162 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1163 1163
1164 1164 # The interactive one is initialized with an offset, meaning we always
1165 1165 # want to remove the topmost item in the traceback, which is our own
1166 1166 # internal code. Valid modes: ['Plain','Context','Verbose']
1167 1167 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1168 1168 color_scheme='NoColor',
1169 1169 tb_offset = 1)
1170 1170
1171 1171 # The instance will store a pointer to the system-wide exception hook,
1172 1172 # so that runtime code (such as magics) can access it. This is because
1173 1173 # during the read-eval loop, it may get temporarily overwritten.
1174 1174 self.sys_excepthook = sys.excepthook
1175 1175
1176 1176 # and add any custom exception handlers the user may have specified
1177 1177 self.set_custom_exc(*custom_exceptions)
1178 1178
1179 1179 def set_custom_exc(self,exc_tuple,handler):
1180 1180 """set_custom_exc(exc_tuple,handler)
1181 1181
1182 1182 Set a custom exception handler, which will be called if any of the
1183 1183 exceptions in exc_tuple occur in the mainloop (specifically, in the
1184 1184 runcode() method.
1185 1185
1186 1186 Inputs:
1187 1187
1188 1188 - exc_tuple: a *tuple* of valid exceptions to call the defined
1189 1189 handler for. It is very important that you use a tuple, and NOT A
1190 1190 LIST here, because of the way Python's except statement works. If
1191 1191 you only want to trap a single exception, use a singleton tuple:
1192 1192
1193 1193 exc_tuple == (MyCustomException,)
1194 1194
1195 1195 - handler: this must be defined as a function with the following
1196 1196 basic interface: def my_handler(self,etype,value,tb).
1197 1197
1198 1198 This will be made into an instance method (via new.instancemethod)
1199 1199 of IPython itself, and it will be called if any of the exceptions
1200 1200 listed in the exc_tuple are caught. If the handler is None, an
1201 1201 internal basic one is used, which just prints basic info.
1202 1202
1203 1203 WARNING: by putting in your own exception handler into IPython's main
1204 1204 execution loop, you run a very good chance of nasty crashes. This
1205 1205 facility should only be used if you really know what you are doing."""
1206 1206
1207 1207 assert type(exc_tuple)==type(()) , \
1208 1208 "The custom exceptions must be given AS A TUPLE."
1209 1209
1210 1210 def dummy_handler(self,etype,value,tb):
1211 1211 print '*** Simple custom exception handler ***'
1212 1212 print 'Exception type :',etype
1213 1213 print 'Exception value:',value
1214 1214 print 'Traceback :',tb
1215 1215 print 'Source code :','\n'.join(self.buffer)
1216 1216
1217 1217 if handler is None: handler = dummy_handler
1218 1218
1219 1219 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1220 1220 self.custom_exceptions = exc_tuple
1221 1221
1222 1222 def excepthook(self, etype, value, tb):
1223 1223 """One more defense for GUI apps that call sys.excepthook.
1224 1224
1225 1225 GUI frameworks like wxPython trap exceptions and call
1226 1226 sys.excepthook themselves. I guess this is a feature that
1227 1227 enables them to keep running after exceptions that would
1228 1228 otherwise kill their mainloop. This is a bother for IPython
1229 1229 which excepts to catch all of the program exceptions with a try:
1230 1230 except: statement.
1231 1231
1232 1232 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1233 1233 any app directly invokes sys.excepthook, it will look to the user like
1234 1234 IPython crashed. In order to work around this, we can disable the
1235 1235 CrashHandler and replace it with this excepthook instead, which prints a
1236 1236 regular traceback using our InteractiveTB. In this fashion, apps which
1237 1237 call sys.excepthook will generate a regular-looking exception from
1238 1238 IPython, and the CrashHandler will only be triggered by real IPython
1239 1239 crashes.
1240 1240
1241 1241 This hook should be used sparingly, only in places which are not likely
1242 1242 to be true IPython errors.
1243 1243 """
1244 1244 self.showtraceback((etype,value,tb),tb_offset=0)
1245 1245
1246 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1246 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1247 exception_only=False):
1247 1248 """Display the exception that just occurred.
1248 1249
1249 1250 If nothing is known about the exception, this is the method which
1250 1251 should be used throughout the code for presenting user tracebacks,
1251 1252 rather than directly invoking the InteractiveTB object.
1252 1253
1253 1254 A specific showsyntaxerror() also exists, but this method can take
1254 1255 care of calling it if needed, so unless you are explicitly catching a
1255 1256 SyntaxError exception, don't try to analyze the stack manually and
1256 1257 simply call this method."""
1257
1258
1259 # Though this won't be called by syntax errors in the input line,
1260 # there may be SyntaxError cases whith imported code.
1261 1258
1262 1259 try:
1263 1260 if exc_tuple is None:
1264 1261 etype, value, tb = sys.exc_info()
1265 1262 else:
1266 1263 etype, value, tb = exc_tuple
1264
1265 if etype is None:
1266 if hasattr(sys, 'last_type'):
1267 etype, value, tb = sys.last_type, sys.last_value, \
1268 sys.last_traceback
1269 else:
1270 self.write('No traceback available to show.\n')
1271 return
1267 1272
1268 1273 if etype is SyntaxError:
1274 # Though this won't be called by syntax errors in the input
1275 # line, there may be SyntaxError cases whith imported code.
1269 1276 self.showsyntaxerror(filename)
1270 1277 elif etype is UsageError:
1271 1278 print "UsageError:", value
1272 1279 else:
1273 1280 # WARNING: these variables are somewhat deprecated and not
1274 1281 # necessarily safe to use in a threaded environment, but tools
1275 1282 # like pdb depend on their existence, so let's set them. If we
1276 1283 # find problems in the field, we'll need to revisit their use.
1277 1284 sys.last_type = etype
1278 1285 sys.last_value = value
1279 1286 sys.last_traceback = tb
1280 1287
1281 1288 if etype in self.custom_exceptions:
1282 1289 self.CustomTB(etype,value,tb)
1283 1290 else:
1284 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1285 if self.InteractiveTB.call_pdb:
1286 # pdb mucks up readline, fix it back
1287 self.set_completer()
1291 if exception_only:
1292 m = ('An exception has occurred, use %tb to see the '
1293 'full traceback.')
1294 print m
1295 self.InteractiveTB.show_exception_only(etype, value)
1296 else:
1297 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1298 if self.InteractiveTB.call_pdb:
1299 # pdb mucks up readline, fix it back
1300 self.set_completer()
1301
1288 1302 except KeyboardInterrupt:
1289 self.write("\nKeyboardInterrupt\n")
1303 self.write("\nKeyboardInterrupt\n")
1304
1290 1305
1291 1306 def showsyntaxerror(self, filename=None):
1292 1307 """Display the syntax error that just occurred.
1293 1308
1294 1309 This doesn't display a stack trace because there isn't one.
1295 1310
1296 1311 If a filename is given, it is stuffed in the exception instead
1297 1312 of what was there before (because Python's parser always uses
1298 1313 "<string>" when reading from a string).
1299 1314 """
1300 1315 etype, value, last_traceback = sys.exc_info()
1301 1316
1302 # See note about these variables in showtraceback() below
1317 # See note about these variables in showtraceback() above
1303 1318 sys.last_type = etype
1304 1319 sys.last_value = value
1305 1320 sys.last_traceback = last_traceback
1306 1321
1307 1322 if filename and etype is SyntaxError:
1308 1323 # Work hard to stuff the correct filename in the exception
1309 1324 try:
1310 1325 msg, (dummy_filename, lineno, offset, line) = value
1311 1326 except:
1312 1327 # Not the format we expect; leave it alone
1313 1328 pass
1314 1329 else:
1315 1330 # Stuff in the right filename
1316 1331 try:
1317 1332 # Assume SyntaxError is a class exception
1318 1333 value = SyntaxError(msg, (filename, lineno, offset, line))
1319 1334 except:
1320 1335 # If that failed, assume SyntaxError is a string
1321 1336 value = msg, (filename, lineno, offset, line)
1322 1337 self.SyntaxTB(etype,value,[])
1323 1338
1324 1339 def edit_syntax_error(self):
1325 1340 """The bottom half of the syntax error handler called in the main loop.
1326 1341
1327 1342 Loop until syntax error is fixed or user cancels.
1328 1343 """
1329 1344
1330 1345 while self.SyntaxTB.last_syntax_error:
1331 1346 # copy and clear last_syntax_error
1332 1347 err = self.SyntaxTB.clear_err_state()
1333 1348 if not self._should_recompile(err):
1334 1349 return
1335 1350 try:
1336 1351 # may set last_syntax_error again if a SyntaxError is raised
1337 1352 self.safe_execfile(err.filename,self.user_ns)
1338 1353 except:
1339 1354 self.showtraceback()
1340 1355 else:
1341 1356 try:
1342 1357 f = file(err.filename)
1343 1358 try:
1344 1359 # This should be inside a display_trap block and I
1345 1360 # think it is.
1346 1361 sys.displayhook(f.read())
1347 1362 finally:
1348 1363 f.close()
1349 1364 except:
1350 1365 self.showtraceback()
1351 1366
1352 1367 def _should_recompile(self,e):
1353 1368 """Utility routine for edit_syntax_error"""
1354 1369
1355 1370 if e.filename in ('<ipython console>','<input>','<string>',
1356 1371 '<console>','<BackgroundJob compilation>',
1357 1372 None):
1358 1373
1359 1374 return False
1360 1375 try:
1361 1376 if (self.autoedit_syntax and
1362 1377 not self.ask_yes_no('Return to editor to correct syntax error? '
1363 1378 '[Y/n] ','y')):
1364 1379 return False
1365 1380 except EOFError:
1366 1381 return False
1367 1382
1368 1383 def int0(x):
1369 1384 try:
1370 1385 return int(x)
1371 1386 except TypeError:
1372 1387 return 0
1373 1388 # always pass integer line and offset values to editor hook
1374 1389 try:
1375 1390 self.hooks.fix_error_editor(e.filename,
1376 1391 int0(e.lineno),int0(e.offset),e.msg)
1377 1392 except TryNext:
1378 1393 warn('Could not open editor')
1379 1394 return False
1380 1395 return True
1381 1396
1382 1397 #-------------------------------------------------------------------------
1383 1398 # Things related to tab completion
1384 1399 #-------------------------------------------------------------------------
1385 1400
1386 1401 def complete(self, text):
1387 1402 """Return a sorted list of all possible completions on text.
1388 1403
1389 1404 Inputs:
1390 1405
1391 1406 - text: a string of text to be completed on.
1392 1407
1393 1408 This is a wrapper around the completion mechanism, similar to what
1394 1409 readline does at the command line when the TAB key is hit. By
1395 1410 exposing it as a method, it can be used by other non-readline
1396 1411 environments (such as GUIs) for text completion.
1397 1412
1398 1413 Simple usage example:
1399 1414
1400 1415 In [7]: x = 'hello'
1401 1416
1402 1417 In [8]: x
1403 1418 Out[8]: 'hello'
1404 1419
1405 1420 In [9]: print x
1406 1421 hello
1407 1422
1408 1423 In [10]: _ip.complete('x.l')
1409 1424 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1410 1425 """
1411 1426
1412 1427 # Inject names into __builtin__ so we can complete on the added names.
1413 1428 with self.builtin_trap:
1414 1429 complete = self.Completer.complete
1415 1430 state = 0
1416 1431 # use a dict so we get unique keys, since ipyhton's multiple
1417 1432 # completers can return duplicates. When we make 2.4 a requirement,
1418 1433 # start using sets instead, which are faster.
1419 1434 comps = {}
1420 1435 while True:
1421 1436 newcomp = complete(text,state,line_buffer=text)
1422 1437 if newcomp is None:
1423 1438 break
1424 1439 comps[newcomp] = 1
1425 1440 state += 1
1426 1441 outcomps = comps.keys()
1427 1442 outcomps.sort()
1428 1443 #print "T:",text,"OC:",outcomps # dbg
1429 1444 #print "vars:",self.user_ns.keys()
1430 1445 return outcomps
1431 1446
1432 1447 def set_custom_completer(self,completer,pos=0):
1433 1448 """Adds a new custom completer function.
1434 1449
1435 1450 The position argument (defaults to 0) is the index in the completers
1436 1451 list where you want the completer to be inserted."""
1437 1452
1438 1453 newcomp = new.instancemethod(completer,self.Completer,
1439 1454 self.Completer.__class__)
1440 1455 self.Completer.matchers.insert(pos,newcomp)
1441 1456
1442 1457 def set_completer(self):
1443 1458 """Reset readline's completer to be our own."""
1444 1459 self.readline.set_completer(self.Completer.complete)
1445 1460
1446 1461 def set_completer_frame(self, frame=None):
1447 1462 """Set the frame of the completer."""
1448 1463 if frame:
1449 1464 self.Completer.namespace = frame.f_locals
1450 1465 self.Completer.global_namespace = frame.f_globals
1451 1466 else:
1452 1467 self.Completer.namespace = self.user_ns
1453 1468 self.Completer.global_namespace = self.user_global_ns
1454 1469
1455 1470 #-------------------------------------------------------------------------
1456 1471 # Things related to readline
1457 1472 #-------------------------------------------------------------------------
1458 1473
1459 1474 def init_readline(self):
1460 1475 """Command history completion/saving/reloading."""
1461 1476
1462 1477 if self.readline_use:
1463 1478 import IPython.utils.rlineimpl as readline
1464 1479
1465 1480 self.rl_next_input = None
1466 1481 self.rl_do_indent = False
1467 1482
1468 1483 if not self.readline_use or not readline.have_readline:
1469 1484 self.has_readline = False
1470 1485 self.readline = None
1471 1486 # Set a number of methods that depend on readline to be no-op
1472 1487 self.savehist = no_op
1473 1488 self.reloadhist = no_op
1474 1489 self.set_completer = no_op
1475 1490 self.set_custom_completer = no_op
1476 1491 self.set_completer_frame = no_op
1477 1492 warn('Readline services not available or not loaded.')
1478 1493 else:
1479 1494 self.has_readline = True
1480 1495 self.readline = readline
1481 1496 sys.modules['readline'] = readline
1482 1497 import atexit
1483 1498 from IPython.core.completer import IPCompleter
1484 1499 self.Completer = IPCompleter(self,
1485 1500 self.user_ns,
1486 1501 self.user_global_ns,
1487 1502 self.readline_omit__names,
1488 1503 self.alias_manager.alias_table)
1489 1504 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1490 1505 self.strdispatchers['complete_command'] = sdisp
1491 1506 self.Completer.custom_completers = sdisp
1492 1507 # Platform-specific configuration
1493 1508 if os.name == 'nt':
1494 1509 self.readline_startup_hook = readline.set_pre_input_hook
1495 1510 else:
1496 1511 self.readline_startup_hook = readline.set_startup_hook
1497 1512
1498 1513 # Load user's initrc file (readline config)
1499 1514 # Or if libedit is used, load editrc.
1500 1515 inputrc_name = os.environ.get('INPUTRC')
1501 1516 if inputrc_name is None:
1502 1517 home_dir = get_home_dir()
1503 1518 if home_dir is not None:
1504 1519 inputrc_name = '.inputrc'
1505 1520 if readline.uses_libedit:
1506 1521 inputrc_name = '.editrc'
1507 1522 inputrc_name = os.path.join(home_dir, inputrc_name)
1508 1523 if os.path.isfile(inputrc_name):
1509 1524 try:
1510 1525 readline.read_init_file(inputrc_name)
1511 1526 except:
1512 1527 warn('Problems reading readline initialization file <%s>'
1513 1528 % inputrc_name)
1514 1529
1515 1530 # save this in sys so embedded copies can restore it properly
1516 1531 sys.ipcompleter = self.Completer.complete
1517 1532 self.set_completer()
1518 1533
1519 1534 # Configure readline according to user's prefs
1520 1535 # This is only done if GNU readline is being used. If libedit
1521 1536 # is being used (as on Leopard) the readline config is
1522 1537 # not run as the syntax for libedit is different.
1523 1538 if not readline.uses_libedit:
1524 1539 for rlcommand in self.readline_parse_and_bind:
1525 1540 #print "loading rl:",rlcommand # dbg
1526 1541 readline.parse_and_bind(rlcommand)
1527 1542
1528 1543 # Remove some chars from the delimiters list. If we encounter
1529 1544 # unicode chars, discard them.
1530 1545 delims = readline.get_completer_delims().encode("ascii", "ignore")
1531 1546 delims = delims.translate(string._idmap,
1532 1547 self.readline_remove_delims)
1533 1548 readline.set_completer_delims(delims)
1534 1549 # otherwise we end up with a monster history after a while:
1535 1550 readline.set_history_length(1000)
1536 1551 try:
1537 1552 #print '*** Reading readline history' # dbg
1538 1553 readline.read_history_file(self.histfile)
1539 1554 except IOError:
1540 1555 pass # It doesn't exist yet.
1541 1556
1542 1557 atexit.register(self.atexit_operations)
1543 1558 del atexit
1544 1559
1545 1560 # Configure auto-indent for all platforms
1546 1561 self.set_autoindent(self.autoindent)
1547 1562
1548 1563 def set_next_input(self, s):
1549 1564 """ Sets the 'default' input string for the next command line.
1550 1565
1551 1566 Requires readline.
1552 1567
1553 1568 Example:
1554 1569
1555 1570 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1556 1571 [D:\ipython]|2> Hello Word_ # cursor is here
1557 1572 """
1558 1573
1559 1574 self.rl_next_input = s
1560 1575
1561 1576 def pre_readline(self):
1562 1577 """readline hook to be used at the start of each line.
1563 1578
1564 1579 Currently it handles auto-indent only."""
1565 1580
1566 1581 #debugx('self.indent_current_nsp','pre_readline:')
1567 1582
1568 1583 if self.rl_do_indent:
1569 1584 self.readline.insert_text(self._indent_current_str())
1570 1585 if self.rl_next_input is not None:
1571 1586 self.readline.insert_text(self.rl_next_input)
1572 1587 self.rl_next_input = None
1573 1588
1574 1589 def _indent_current_str(self):
1575 1590 """return the current level of indentation as a string"""
1576 1591 return self.indent_current_nsp * ' '
1577 1592
1578 1593 #-------------------------------------------------------------------------
1579 1594 # Things related to magics
1580 1595 #-------------------------------------------------------------------------
1581 1596
1582 1597 def init_magics(self):
1583 1598 # Set user colors (don't do it in the constructor above so that it
1584 1599 # doesn't crash if colors option is invalid)
1585 1600 self.magic_colors(self.colors)
1586 1601 # History was moved to a separate module
1587 1602 from . import history
1588 1603 history.init_ipython(self)
1589 1604
1590 1605 def magic(self,arg_s):
1591 1606 """Call a magic function by name.
1592 1607
1593 1608 Input: a string containing the name of the magic function to call and any
1594 1609 additional arguments to be passed to the magic.
1595 1610
1596 1611 magic('name -opt foo bar') is equivalent to typing at the ipython
1597 1612 prompt:
1598 1613
1599 1614 In[1]: %name -opt foo bar
1600 1615
1601 1616 To call a magic without arguments, simply use magic('name').
1602 1617
1603 1618 This provides a proper Python function to call IPython's magics in any
1604 1619 valid Python code you can type at the interpreter, including loops and
1605 1620 compound statements.
1606 1621 """
1607 1622
1608 1623 args = arg_s.split(' ',1)
1609 1624 magic_name = args[0]
1610 1625 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1611 1626
1612 1627 try:
1613 1628 magic_args = args[1]
1614 1629 except IndexError:
1615 1630 magic_args = ''
1616 1631 fn = getattr(self,'magic_'+magic_name,None)
1617 1632 if fn is None:
1618 1633 error("Magic function `%s` not found." % magic_name)
1619 1634 else:
1620 1635 magic_args = self.var_expand(magic_args,1)
1621 1636 with nested(self.builtin_trap,):
1622 1637 result = fn(magic_args)
1623 1638 return result
1624 1639
1625 1640 def define_magic(self, magicname, func):
1626 1641 """Expose own function as magic function for ipython
1627 1642
1628 1643 def foo_impl(self,parameter_s=''):
1629 1644 'My very own magic!. (Use docstrings, IPython reads them).'
1630 1645 print 'Magic function. Passed parameter is between < >:'
1631 1646 print '<%s>' % parameter_s
1632 1647 print 'The self object is:',self
1633 1648
1634 1649 self.define_magic('foo',foo_impl)
1635 1650 """
1636 1651
1637 1652 import new
1638 1653 im = new.instancemethod(func,self, self.__class__)
1639 1654 old = getattr(self, "magic_" + magicname, None)
1640 1655 setattr(self, "magic_" + magicname, im)
1641 1656 return old
1642 1657
1643 1658 #-------------------------------------------------------------------------
1644 1659 # Things related to macros
1645 1660 #-------------------------------------------------------------------------
1646 1661
1647 1662 def define_macro(self, name, themacro):
1648 1663 """Define a new macro
1649 1664
1650 1665 Parameters
1651 1666 ----------
1652 1667 name : str
1653 1668 The name of the macro.
1654 1669 themacro : str or Macro
1655 1670 The action to do upon invoking the macro. If a string, a new
1656 1671 Macro object is created by passing the string to it.
1657 1672 """
1658 1673
1659 1674 from IPython.core import macro
1660 1675
1661 1676 if isinstance(themacro, basestring):
1662 1677 themacro = macro.Macro(themacro)
1663 1678 if not isinstance(themacro, macro.Macro):
1664 1679 raise ValueError('A macro must be a string or a Macro instance.')
1665 1680 self.user_ns[name] = themacro
1666 1681
1667 1682 #-------------------------------------------------------------------------
1668 1683 # Things related to the running of system commands
1669 1684 #-------------------------------------------------------------------------
1670 1685
1671 1686 def system(self, cmd):
1672 1687 """Make a system call, using IPython."""
1673 1688 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1674 1689
1675 1690 #-------------------------------------------------------------------------
1676 1691 # Things related to aliases
1677 1692 #-------------------------------------------------------------------------
1678 1693
1679 1694 def init_alias(self):
1680 1695 self.alias_manager = AliasManager(self, config=self.config)
1681 1696 self.ns_table['alias'] = self.alias_manager.alias_table,
1682 1697
1683 1698 #-------------------------------------------------------------------------
1684 1699 # Things related to the running of code
1685 1700 #-------------------------------------------------------------------------
1686 1701
1687 1702 def ex(self, cmd):
1688 1703 """Execute a normal python statement in user namespace."""
1689 1704 with nested(self.builtin_trap,):
1690 1705 exec cmd in self.user_global_ns, self.user_ns
1691 1706
1692 1707 def ev(self, expr):
1693 1708 """Evaluate python expression expr in user namespace.
1694 1709
1695 1710 Returns the result of evaluation
1696 1711 """
1697 1712 with nested(self.builtin_trap,):
1698 1713 return eval(expr, self.user_global_ns, self.user_ns)
1699 1714
1700 1715 def mainloop(self, display_banner=None):
1701 1716 """Start the mainloop.
1702 1717
1703 1718 If an optional banner argument is given, it will override the
1704 1719 internally created default banner.
1705 1720 """
1706 1721
1707 1722 with nested(self.builtin_trap, self.display_trap):
1708 1723
1709 1724 # if you run stuff with -c <cmd>, raw hist is not updated
1710 1725 # ensure that it's in sync
1711 1726 if len(self.input_hist) != len (self.input_hist_raw):
1712 1727 self.input_hist_raw = InputList(self.input_hist)
1713 1728
1714 1729 while 1:
1715 1730 try:
1716 1731 self.interact(display_banner=display_banner)
1717 1732 #self.interact_with_readline()
1718 1733 # XXX for testing of a readline-decoupled repl loop, call
1719 1734 # interact_with_readline above
1720 1735 break
1721 1736 except KeyboardInterrupt:
1722 1737 # this should not be necessary, but KeyboardInterrupt
1723 1738 # handling seems rather unpredictable...
1724 1739 self.write("\nKeyboardInterrupt in interact()\n")
1725 1740
1726 1741 def interact_prompt(self):
1727 1742 """ Print the prompt (in read-eval-print loop)
1728 1743
1729 1744 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1730 1745 used in standard IPython flow.
1731 1746 """
1732 1747 if self.more:
1733 1748 try:
1734 1749 prompt = self.hooks.generate_prompt(True)
1735 1750 except:
1736 1751 self.showtraceback()
1737 1752 if self.autoindent:
1738 1753 self.rl_do_indent = True
1739 1754
1740 1755 else:
1741 1756 try:
1742 1757 prompt = self.hooks.generate_prompt(False)
1743 1758 except:
1744 1759 self.showtraceback()
1745 1760 self.write(prompt)
1746 1761
1747 1762 def interact_handle_input(self,line):
1748 1763 """ Handle the input line (in read-eval-print loop)
1749 1764
1750 1765 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1751 1766 used in standard IPython flow.
1752 1767 """
1753 1768 if line.lstrip() == line:
1754 1769 self.shadowhist.add(line.strip())
1755 1770 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1756 1771
1757 1772 if line.strip():
1758 1773 if self.more:
1759 1774 self.input_hist_raw[-1] += '%s\n' % line
1760 1775 else:
1761 1776 self.input_hist_raw.append('%s\n' % line)
1762 1777
1763 1778
1764 1779 self.more = self.push_line(lineout)
1765 1780 if (self.SyntaxTB.last_syntax_error and
1766 1781 self.autoedit_syntax):
1767 1782 self.edit_syntax_error()
1768 1783
1769 1784 def interact_with_readline(self):
1770 1785 """ Demo of using interact_handle_input, interact_prompt
1771 1786
1772 1787 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1773 1788 it should work like this.
1774 1789 """
1775 1790 self.readline_startup_hook(self.pre_readline)
1776 1791 while not self.exit_now:
1777 1792 self.interact_prompt()
1778 1793 if self.more:
1779 1794 self.rl_do_indent = True
1780 1795 else:
1781 1796 self.rl_do_indent = False
1782 1797 line = raw_input_original().decode(self.stdin_encoding)
1783 1798 self.interact_handle_input(line)
1784 1799
1785 1800 def interact(self, display_banner=None):
1786 1801 """Closely emulate the interactive Python console."""
1787 1802
1788 1803 # batch run -> do not interact
1789 1804 if self.exit_now:
1790 1805 return
1791 1806
1792 1807 if display_banner is None:
1793 1808 display_banner = self.display_banner
1794 1809 if display_banner:
1795 1810 self.show_banner()
1796 1811
1797 1812 more = 0
1798 1813
1799 1814 # Mark activity in the builtins
1800 1815 __builtin__.__dict__['__IPYTHON__active'] += 1
1801 1816
1802 1817 if self.has_readline:
1803 1818 self.readline_startup_hook(self.pre_readline)
1804 1819 # exit_now is set by a call to %Exit or %Quit, through the
1805 1820 # ask_exit callback.
1806 1821
1807 1822 while not self.exit_now:
1808 1823 self.hooks.pre_prompt_hook()
1809 1824 if more:
1810 1825 try:
1811 1826 prompt = self.hooks.generate_prompt(True)
1812 1827 except:
1813 1828 self.showtraceback()
1814 1829 if self.autoindent:
1815 1830 self.rl_do_indent = True
1816 1831
1817 1832 else:
1818 1833 try:
1819 1834 prompt = self.hooks.generate_prompt(False)
1820 1835 except:
1821 1836 self.showtraceback()
1822 1837 try:
1823 1838 line = self.raw_input(prompt, more)
1824 1839 if self.exit_now:
1825 1840 # quick exit on sys.std[in|out] close
1826 1841 break
1827 1842 if self.autoindent:
1828 1843 self.rl_do_indent = False
1829 1844
1830 1845 except KeyboardInterrupt:
1831 1846 #double-guard against keyboardinterrupts during kbdint handling
1832 1847 try:
1833 1848 self.write('\nKeyboardInterrupt\n')
1834 1849 self.resetbuffer()
1835 1850 # keep cache in sync with the prompt counter:
1836 1851 self.outputcache.prompt_count -= 1
1837 1852
1838 1853 if self.autoindent:
1839 1854 self.indent_current_nsp = 0
1840 1855 more = 0
1841 1856 except KeyboardInterrupt:
1842 1857 pass
1843 1858 except EOFError:
1844 1859 if self.autoindent:
1845 1860 self.rl_do_indent = False
1846 1861 if self.has_readline:
1847 1862 self.readline_startup_hook(None)
1848 1863 self.write('\n')
1849 1864 self.exit()
1850 1865 except bdb.BdbQuit:
1851 1866 warn('The Python debugger has exited with a BdbQuit exception.\n'
1852 1867 'Because of how pdb handles the stack, it is impossible\n'
1853 1868 'for IPython to properly format this particular exception.\n'
1854 1869 'IPython will resume normal operation.')
1855 1870 except:
1856 1871 # exceptions here are VERY RARE, but they can be triggered
1857 1872 # asynchronously by signal handlers, for example.
1858 1873 self.showtraceback()
1859 1874 else:
1860 1875 more = self.push_line(line)
1861 1876 if (self.SyntaxTB.last_syntax_error and
1862 1877 self.autoedit_syntax):
1863 1878 self.edit_syntax_error()
1864 1879
1865 1880 # We are off again...
1866 1881 __builtin__.__dict__['__IPYTHON__active'] -= 1
1867 1882
1883 # Turn off the exit flag, so the mainloop can be restarted if desired
1884 self.exit_now = False
1885
1868 1886 def safe_execfile(self, fname, *where, **kw):
1869 1887 """A safe version of the builtin execfile().
1870 1888
1871 1889 This version will never throw an exception, but instead print
1872 1890 helpful error messages to the screen. This only works on pure
1873 1891 Python files with the .py extension.
1874 1892
1875 1893 Parameters
1876 1894 ----------
1877 1895 fname : string
1878 1896 The name of the file to be executed.
1879 1897 where : tuple
1880 1898 One or two namespaces, passed to execfile() as (globals,locals).
1881 1899 If only one is given, it is passed as both.
1882 1900 exit_ignore : bool (False)
1883 If True, then don't print errors for non-zero exit statuses.
1901 If True, then silence SystemExit for non-zero status (it is always
1902 silenced for zero status, as it is so common).
1884 1903 """
1885 1904 kw.setdefault('exit_ignore', False)
1886 1905
1887 1906 fname = os.path.abspath(os.path.expanduser(fname))
1888 1907
1889 1908 # Make sure we have a .py file
1890 1909 if not fname.endswith('.py'):
1891 1910 warn('File must end with .py to be run using execfile: <%s>' % fname)
1892 1911
1893 1912 # Make sure we can open the file
1894 1913 try:
1895 1914 with open(fname) as thefile:
1896 1915 pass
1897 1916 except:
1898 1917 warn('Could not open file <%s> for safe execution.' % fname)
1899 1918 return
1900 1919
1901 1920 # Find things also in current directory. This is needed to mimic the
1902 1921 # behavior of running a script from the system command line, where
1903 1922 # Python inserts the script's directory into sys.path
1904 1923 dname = os.path.dirname(fname)
1905 1924
1906 1925 with prepended_to_syspath(dname):
1907 1926 try:
1908 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1909 # Work around a bug in Python for Windows. The bug was
1910 # fixed in in Python 2.5 r54159 and 54158, but that's still
1911 # SVN Python as of March/07. For details, see:
1912 # http://projects.scipy.org/ipython/ipython/ticket/123
1913 try:
1914 globs,locs = where[0:2]
1915 except:
1916 try:
1917 globs = locs = where[0]
1918 except:
1919 globs = locs = globals()
1920 exec file(fname) in globs,locs
1921 else:
1922 execfile(fname,*where)
1923 except SyntaxError:
1924 self.showsyntaxerror()
1925 warn('Failure executing file: <%s>' % fname)
1927 execfile(fname,*where)
1926 1928 except SystemExit, status:
1927 # Code that correctly sets the exit status flag to success (0)
1928 # shouldn't be bothered with a traceback. Note that a plain
1929 # sys.exit() does NOT set the message to 0 (it's empty) so that
1930 # will still get a traceback. Note that the structure of the
1931 # SystemExit exception changed between Python 2.4 and 2.5, so
1932 # the checks must be done in a version-dependent way.
1933 show = False
1934 if status.args[0]==0 and not kw['exit_ignore']:
1935 show = True
1936 if show:
1937 self.showtraceback()
1938 warn('Failure executing file: <%s>' % fname)
1929 # If the call was made with 0 or None exit status (sys.exit(0)
1930 # or sys.exit() ), don't bother showing a traceback, as both of
1931 # these are considered normal by the OS:
1932 # > python -c'import sys;sys.exit(0)'; echo $?
1933 # 0
1934 # > python -c'import sys;sys.exit()'; echo $?
1935 # 0
1936 # For other exit status, we show the exception unless
1937 # explicitly silenced, but only in short form.
1938 if status.code not in (0, None) and not kw['exit_ignore']:
1939 self.showtraceback(exception_only=True)
1939 1940 except:
1940 1941 self.showtraceback()
1941 warn('Failure executing file: <%s>' % fname)
1942 1942
1943 1943 def safe_execfile_ipy(self, fname):
1944 1944 """Like safe_execfile, but for .ipy files with IPython syntax.
1945 1945
1946 1946 Parameters
1947 1947 ----------
1948 1948 fname : str
1949 1949 The name of the file to execute. The filename must have a
1950 1950 .ipy extension.
1951 1951 """
1952 1952 fname = os.path.abspath(os.path.expanduser(fname))
1953 1953
1954 1954 # Make sure we have a .py file
1955 1955 if not fname.endswith('.ipy'):
1956 1956 warn('File must end with .py to be run using execfile: <%s>' % fname)
1957 1957
1958 1958 # Make sure we can open the file
1959 1959 try:
1960 1960 with open(fname) as thefile:
1961 1961 pass
1962 1962 except:
1963 1963 warn('Could not open file <%s> for safe execution.' % fname)
1964 1964 return
1965 1965
1966 1966 # Find things also in current directory. This is needed to mimic the
1967 1967 # behavior of running a script from the system command line, where
1968 1968 # Python inserts the script's directory into sys.path
1969 1969 dname = os.path.dirname(fname)
1970 1970
1971 1971 with prepended_to_syspath(dname):
1972 1972 try:
1973 1973 with open(fname) as thefile:
1974 1974 script = thefile.read()
1975 1975 # self.runlines currently captures all exceptions
1976 1976 # raise in user code. It would be nice if there were
1977 1977 # versions of runlines, execfile that did raise, so
1978 1978 # we could catch the errors.
1979 1979 self.runlines(script, clean=True)
1980 1980 except:
1981 1981 self.showtraceback()
1982 1982 warn('Unknown failure executing file: <%s>' % fname)
1983 1983
1984 1984 def _is_secondary_block_start(self, s):
1985 1985 if not s.endswith(':'):
1986 1986 return False
1987 1987 if (s.startswith('elif') or
1988 1988 s.startswith('else') or
1989 1989 s.startswith('except') or
1990 1990 s.startswith('finally')):
1991 1991 return True
1992 1992
1993 1993 def cleanup_ipy_script(self, script):
1994 1994 """Make a script safe for self.runlines()
1995 1995
1996 1996 Currently, IPython is lines based, with blocks being detected by
1997 1997 empty lines. This is a problem for block based scripts that may
1998 1998 not have empty lines after blocks. This script adds those empty
1999 1999 lines to make scripts safe for running in the current line based
2000 2000 IPython.
2001 2001 """
2002 2002 res = []
2003 2003 lines = script.splitlines()
2004 2004 level = 0
2005 2005
2006 2006 for l in lines:
2007 2007 lstripped = l.lstrip()
2008 2008 stripped = l.strip()
2009 2009 if not stripped:
2010 2010 continue
2011 2011 newlevel = len(l) - len(lstripped)
2012 2012 if level > 0 and newlevel == 0 and \
2013 2013 not self._is_secondary_block_start(stripped):
2014 2014 # add empty line
2015 2015 res.append('')
2016 2016 res.append(l)
2017 2017 level = newlevel
2018 2018
2019 2019 return '\n'.join(res) + '\n'
2020 2020
2021 2021 def runlines(self, lines, clean=False):
2022 2022 """Run a string of one or more lines of source.
2023 2023
2024 2024 This method is capable of running a string containing multiple source
2025 2025 lines, as if they had been entered at the IPython prompt. Since it
2026 2026 exposes IPython's processing machinery, the given strings can contain
2027 2027 magic calls (%magic), special shell access (!cmd), etc.
2028 2028 """
2029 2029
2030 2030 if isinstance(lines, (list, tuple)):
2031 2031 lines = '\n'.join(lines)
2032 2032
2033 2033 if clean:
2034 2034 lines = self.cleanup_ipy_script(lines)
2035 2035
2036 2036 # We must start with a clean buffer, in case this is run from an
2037 2037 # interactive IPython session (via a magic, for example).
2038 2038 self.resetbuffer()
2039 2039 lines = lines.splitlines()
2040 2040 more = 0
2041 2041
2042 2042 with nested(self.builtin_trap, self.display_trap):
2043 2043 for line in lines:
2044 2044 # skip blank lines so we don't mess up the prompt counter, but do
2045 2045 # NOT skip even a blank line if we are in a code block (more is
2046 2046 # true)
2047 2047
2048 2048 if line or more:
2049 2049 # push to raw history, so hist line numbers stay in sync
2050 2050 self.input_hist_raw.append("# " + line + "\n")
2051 2051 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2052 2052 more = self.push_line(prefiltered)
2053 2053 # IPython's runsource returns None if there was an error
2054 2054 # compiling the code. This allows us to stop processing right
2055 2055 # away, so the user gets the error message at the right place.
2056 2056 if more is None:
2057 2057 break
2058 2058 else:
2059 2059 self.input_hist_raw.append("\n")
2060 2060 # final newline in case the input didn't have it, so that the code
2061 2061 # actually does get executed
2062 2062 if more:
2063 2063 self.push_line('\n')
2064 2064
2065 2065 def runsource(self, source, filename='<input>', symbol='single'):
2066 2066 """Compile and run some source in the interpreter.
2067 2067
2068 2068 Arguments are as for compile_command().
2069 2069
2070 2070 One several things can happen:
2071 2071
2072 2072 1) The input is incorrect; compile_command() raised an
2073 2073 exception (SyntaxError or OverflowError). A syntax traceback
2074 2074 will be printed by calling the showsyntaxerror() method.
2075 2075
2076 2076 2) The input is incomplete, and more input is required;
2077 2077 compile_command() returned None. Nothing happens.
2078 2078
2079 2079 3) The input is complete; compile_command() returned a code
2080 2080 object. The code is executed by calling self.runcode() (which
2081 2081 also handles run-time exceptions, except for SystemExit).
2082 2082
2083 2083 The return value is:
2084 2084
2085 2085 - True in case 2
2086 2086
2087 2087 - False in the other cases, unless an exception is raised, where
2088 2088 None is returned instead. This can be used by external callers to
2089 2089 know whether to continue feeding input or not.
2090 2090
2091 2091 The return value can be used to decide whether to use sys.ps1 or
2092 2092 sys.ps2 to prompt the next line."""
2093 2093
2094 2094 # if the source code has leading blanks, add 'if 1:\n' to it
2095 2095 # this allows execution of indented pasted code. It is tempting
2096 2096 # to add '\n' at the end of source to run commands like ' a=1'
2097 2097 # directly, but this fails for more complicated scenarios
2098 2098 source=source.encode(self.stdin_encoding)
2099 2099 if source[:1] in [' ', '\t']:
2100 2100 source = 'if 1:\n%s' % source
2101 2101
2102 2102 try:
2103 2103 code = self.compile(source,filename,symbol)
2104 2104 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2105 2105 # Case 1
2106 2106 self.showsyntaxerror(filename)
2107 2107 return None
2108 2108
2109 2109 if code is None:
2110 2110 # Case 2
2111 2111 return True
2112 2112
2113 2113 # Case 3
2114 2114 # We store the code object so that threaded shells and
2115 2115 # custom exception handlers can access all this info if needed.
2116 2116 # The source corresponding to this can be obtained from the
2117 2117 # buffer attribute as '\n'.join(self.buffer).
2118 2118 self.code_to_run = code
2119 2119 # now actually execute the code object
2120 2120 if self.runcode(code) == 0:
2121 2121 return False
2122 2122 else:
2123 2123 return None
2124 2124
2125 2125 def runcode(self,code_obj):
2126 2126 """Execute a code object.
2127 2127
2128 2128 When an exception occurs, self.showtraceback() is called to display a
2129 2129 traceback.
2130 2130
2131 2131 Return value: a flag indicating whether the code to be run completed
2132 2132 successfully:
2133 2133
2134 2134 - 0: successful execution.
2135 2135 - 1: an error occurred.
2136 2136 """
2137 2137
2138 2138 # Set our own excepthook in case the user code tries to call it
2139 2139 # directly, so that the IPython crash handler doesn't get triggered
2140 2140 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2141 2141
2142 2142 # we save the original sys.excepthook in the instance, in case config
2143 2143 # code (such as magics) needs access to it.
2144 2144 self.sys_excepthook = old_excepthook
2145 2145 outflag = 1 # happens in more places, so it's easier as default
2146 2146 try:
2147 2147 try:
2148 2148 self.hooks.pre_runcode_hook()
2149 2149 exec code_obj in self.user_global_ns, self.user_ns
2150 2150 finally:
2151 2151 # Reset our crash handler in place
2152 2152 sys.excepthook = old_excepthook
2153 2153 except SystemExit:
2154 2154 self.resetbuffer()
2155 self.showtraceback()
2156 warn("Type %exit or %quit to exit IPython "
2157 "(%Exit or %Quit do so unconditionally).",level=1)
2155 self.showtraceback(exception_only=True)
2156 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2158 2157 except self.custom_exceptions:
2159 2158 etype,value,tb = sys.exc_info()
2160 2159 self.CustomTB(etype,value,tb)
2161 2160 except:
2162 2161 self.showtraceback()
2163 2162 else:
2164 2163 outflag = 0
2165 2164 if softspace(sys.stdout, 0):
2166 2165 print
2167 2166 # Flush out code object which has been run (and source)
2168 2167 self.code_to_run = None
2169 2168 return outflag
2170 2169
2171 2170 def push_line(self, line):
2172 2171 """Push a line to the interpreter.
2173 2172
2174 2173 The line should not have a trailing newline; it may have
2175 2174 internal newlines. The line is appended to a buffer and the
2176 2175 interpreter's runsource() method is called with the
2177 2176 concatenated contents of the buffer as source. If this
2178 2177 indicates that the command was executed or invalid, the buffer
2179 2178 is reset; otherwise, the command is incomplete, and the buffer
2180 2179 is left as it was after the line was appended. The return
2181 2180 value is 1 if more input is required, 0 if the line was dealt
2182 2181 with in some way (this is the same as runsource()).
2183 2182 """
2184 2183
2185 2184 # autoindent management should be done here, and not in the
2186 2185 # interactive loop, since that one is only seen by keyboard input. We
2187 2186 # need this done correctly even for code run via runlines (which uses
2188 2187 # push).
2189 2188
2190 2189 #print 'push line: <%s>' % line # dbg
2191 2190 for subline in line.splitlines():
2192 2191 self._autoindent_update(subline)
2193 2192 self.buffer.append(line)
2194 2193 more = self.runsource('\n'.join(self.buffer), self.filename)
2195 2194 if not more:
2196 2195 self.resetbuffer()
2197 2196 return more
2198 2197
2199 2198 def _autoindent_update(self,line):
2200 2199 """Keep track of the indent level."""
2201 2200
2202 2201 #debugx('line')
2203 2202 #debugx('self.indent_current_nsp')
2204 2203 if self.autoindent:
2205 2204 if line:
2206 2205 inisp = num_ini_spaces(line)
2207 2206 if inisp < self.indent_current_nsp:
2208 2207 self.indent_current_nsp = inisp
2209 2208
2210 2209 if line[-1] == ':':
2211 2210 self.indent_current_nsp += 4
2212 2211 elif dedent_re.match(line):
2213 2212 self.indent_current_nsp -= 4
2214 2213 else:
2215 2214 self.indent_current_nsp = 0
2216 2215
2217 2216 def resetbuffer(self):
2218 2217 """Reset the input buffer."""
2219 2218 self.buffer[:] = []
2220 2219
2221 2220 def raw_input(self,prompt='',continue_prompt=False):
2222 2221 """Write a prompt and read a line.
2223 2222
2224 2223 The returned line does not include the trailing newline.
2225 2224 When the user enters the EOF key sequence, EOFError is raised.
2226 2225
2227 2226 Optional inputs:
2228 2227
2229 2228 - prompt(''): a string to be printed to prompt the user.
2230 2229
2231 2230 - continue_prompt(False): whether this line is the first one or a
2232 2231 continuation in a sequence of inputs.
2233 2232 """
2234 2233 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2235 2234
2236 2235 # Code run by the user may have modified the readline completer state.
2237 2236 # We must ensure that our completer is back in place.
2238 2237
2239 2238 if self.has_readline:
2240 2239 self.set_completer()
2241 2240
2242 2241 try:
2243 2242 line = raw_input_original(prompt).decode(self.stdin_encoding)
2244 2243 except ValueError:
2245 2244 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2246 2245 " or sys.stdout.close()!\nExiting IPython!")
2247 2246 self.ask_exit()
2248 2247 return ""
2249 2248
2250 2249 # Try to be reasonably smart about not re-indenting pasted input more
2251 2250 # than necessary. We do this by trimming out the auto-indent initial
2252 2251 # spaces, if the user's actual input started itself with whitespace.
2253 2252 #debugx('self.buffer[-1]')
2254 2253
2255 2254 if self.autoindent:
2256 2255 if num_ini_spaces(line) > self.indent_current_nsp:
2257 2256 line = line[self.indent_current_nsp:]
2258 2257 self.indent_current_nsp = 0
2259 2258
2260 2259 # store the unfiltered input before the user has any chance to modify
2261 2260 # it.
2262 2261 if line.strip():
2263 2262 if continue_prompt:
2264 2263 self.input_hist_raw[-1] += '%s\n' % line
2265 2264 if self.has_readline and self.readline_use:
2266 2265 try:
2267 2266 histlen = self.readline.get_current_history_length()
2268 2267 if histlen > 1:
2269 2268 newhist = self.input_hist_raw[-1].rstrip()
2270 2269 self.readline.remove_history_item(histlen-1)
2271 2270 self.readline.replace_history_item(histlen-2,
2272 2271 newhist.encode(self.stdin_encoding))
2273 2272 except AttributeError:
2274 2273 pass # re{move,place}_history_item are new in 2.4.
2275 2274 else:
2276 2275 self.input_hist_raw.append('%s\n' % line)
2277 2276 # only entries starting at first column go to shadow history
2278 2277 if line.lstrip() == line:
2279 2278 self.shadowhist.add(line.strip())
2280 2279 elif not continue_prompt:
2281 2280 self.input_hist_raw.append('\n')
2282 2281 try:
2283 2282 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2284 2283 except:
2285 2284 # blanket except, in case a user-defined prefilter crashes, so it
2286 2285 # can't take all of ipython with it.
2287 2286 self.showtraceback()
2288 2287 return ''
2289 2288 else:
2290 2289 return lineout
2291 2290
2292 2291 #-------------------------------------------------------------------------
2293 2292 # Working with components
2294 2293 #-------------------------------------------------------------------------
2295 2294
2296 2295 def get_component(self, name=None, klass=None):
2297 2296 """Fetch a component by name and klass in my tree."""
2298 2297 c = Component.get_instances(root=self, name=name, klass=klass)
2299 2298 if len(c) == 0:
2300 2299 return None
2301 2300 if len(c) == 1:
2302 2301 return c[0]
2303 2302 else:
2304 2303 return c
2305 2304
2306 2305 #-------------------------------------------------------------------------
2307 2306 # IPython extensions
2308 2307 #-------------------------------------------------------------------------
2309 2308
2310 2309 def load_extension(self, module_str):
2311 2310 """Load an IPython extension by its module name.
2312 2311
2313 2312 An IPython extension is an importable Python module that has
2314 2313 a function with the signature::
2315 2314
2316 2315 def load_ipython_extension(ipython):
2317 2316 # Do things with ipython
2318 2317
2319 2318 This function is called after your extension is imported and the
2320 2319 currently active :class:`InteractiveShell` instance is passed as
2321 2320 the only argument. You can do anything you want with IPython at
2322 2321 that point, including defining new magic and aliases, adding new
2323 2322 components, etc.
2324 2323
2325 2324 The :func:`load_ipython_extension` will be called again is you
2326 2325 load or reload the extension again. It is up to the extension
2327 2326 author to add code to manage that.
2328 2327
2329 2328 You can put your extension modules anywhere you want, as long as
2330 2329 they can be imported by Python's standard import mechanism. However,
2331 2330 to make it easy to write extensions, you can also put your extensions
2332 2331 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2333 2332 is added to ``sys.path`` automatically.
2334 2333 """
2335 2334 from IPython.utils.syspathcontext import prepended_to_syspath
2336 2335
2337 2336 if module_str not in sys.modules:
2338 2337 with prepended_to_syspath(self.ipython_extension_dir):
2339 2338 __import__(module_str)
2340 2339 mod = sys.modules[module_str]
2341 2340 return self._call_load_ipython_extension(mod)
2342 2341
2343 2342 def unload_extension(self, module_str):
2344 2343 """Unload an IPython extension by its module name.
2345 2344
2346 2345 This function looks up the extension's name in ``sys.modules`` and
2347 2346 simply calls ``mod.unload_ipython_extension(self)``.
2348 2347 """
2349 2348 if module_str in sys.modules:
2350 2349 mod = sys.modules[module_str]
2351 2350 self._call_unload_ipython_extension(mod)
2352 2351
2353 2352 def reload_extension(self, module_str):
2354 2353 """Reload an IPython extension by calling reload.
2355 2354
2356 2355 If the module has not been loaded before,
2357 2356 :meth:`InteractiveShell.load_extension` is called. Otherwise
2358 2357 :func:`reload` is called and then the :func:`load_ipython_extension`
2359 2358 function of the module, if it exists is called.
2360 2359 """
2361 2360 from IPython.utils.syspathcontext import prepended_to_syspath
2362 2361
2363 2362 with prepended_to_syspath(self.ipython_extension_dir):
2364 2363 if module_str in sys.modules:
2365 2364 mod = sys.modules[module_str]
2366 2365 reload(mod)
2367 2366 self._call_load_ipython_extension(mod)
2368 2367 else:
2369 2368 self.load_extension(module_str)
2370 2369
2371 2370 def _call_load_ipython_extension(self, mod):
2372 2371 if hasattr(mod, 'load_ipython_extension'):
2373 2372 return mod.load_ipython_extension(self)
2374 2373
2375 2374 def _call_unload_ipython_extension(self, mod):
2376 2375 if hasattr(mod, 'unload_ipython_extension'):
2377 2376 return mod.unload_ipython_extension(self)
2378 2377
2379 2378 #-------------------------------------------------------------------------
2380 2379 # Things related to the prefilter
2381 2380 #-------------------------------------------------------------------------
2382 2381
2383 2382 def init_prefilter(self):
2384 2383 self.prefilter_manager = PrefilterManager(self, config=self.config)
2385 2384 # Ultimately this will be refactored in the new interpreter code, but
2386 2385 # for now, we should expose the main prefilter method (there's legacy
2387 2386 # code out there that may rely on this).
2388 2387 self.prefilter = self.prefilter_manager.prefilter_lines
2389 2388
2390 2389 #-------------------------------------------------------------------------
2391 2390 # Utilities
2392 2391 #-------------------------------------------------------------------------
2393 2392
2394 2393 def getoutput(self, cmd):
2395 2394 return getoutput(self.var_expand(cmd,depth=2),
2396 2395 header=self.system_header,
2397 2396 verbose=self.system_verbose)
2398 2397
2399 2398 def getoutputerror(self, cmd):
2400 2399 return getoutputerror(self.var_expand(cmd,depth=2),
2401 2400 header=self.system_header,
2402 2401 verbose=self.system_verbose)
2403 2402
2404 2403 def var_expand(self,cmd,depth=0):
2405 2404 """Expand python variables in a string.
2406 2405
2407 2406 The depth argument indicates how many frames above the caller should
2408 2407 be walked to look for the local namespace where to expand variables.
2409 2408
2410 2409 The global namespace for expansion is always the user's interactive
2411 2410 namespace.
2412 2411 """
2413 2412
2414 2413 return str(ItplNS(cmd,
2415 2414 self.user_ns, # globals
2416 2415 # Skip our own frame in searching for locals:
2417 2416 sys._getframe(depth+1).f_locals # locals
2418 2417 ))
2419 2418
2420 2419 def mktempfile(self,data=None):
2421 2420 """Make a new tempfile and return its filename.
2422 2421
2423 2422 This makes a call to tempfile.mktemp, but it registers the created
2424 2423 filename internally so ipython cleans it up at exit time.
2425 2424
2426 2425 Optional inputs:
2427 2426
2428 2427 - data(None): if data is given, it gets written out to the temp file
2429 2428 immediately, and the file is closed again."""
2430 2429
2431 2430 filename = tempfile.mktemp('.py','ipython_edit_')
2432 2431 self.tempfiles.append(filename)
2433 2432
2434 2433 if data:
2435 2434 tmp_file = open(filename,'w')
2436 2435 tmp_file.write(data)
2437 2436 tmp_file.close()
2438 2437 return filename
2439 2438
2440 2439 def write(self,data):
2441 2440 """Write a string to the default output"""
2442 2441 Term.cout.write(data)
2443 2442
2444 2443 def write_err(self,data):
2445 2444 """Write a string to the default error output"""
2446 2445 Term.cerr.write(data)
2447 2446
2448 2447 def ask_yes_no(self,prompt,default=True):
2449 2448 if self.quiet:
2450 2449 return True
2451 2450 return ask_yes_no(prompt,default)
2452 2451
2453 2452 #-------------------------------------------------------------------------
2454 2453 # Things related to GUI support and pylab
2455 2454 #-------------------------------------------------------------------------
2456 2455
2457 2456 def enable_pylab(self, gui=None):
2458 2457 """Activate pylab support at runtime.
2459 2458
2460 2459 This turns on support for matplotlib, preloads into the interactive
2461 2460 namespace all of numpy and pylab, and configures IPython to correcdtly
2462 2461 interact with the GUI event loop. The GUI backend to be used can be
2463 2462 optionally selected with the optional :param:`gui` argument.
2464 2463
2465 2464 Parameters
2466 2465 ----------
2467 2466 gui : optional, string
2468 2467
2469 2468 If given, dictates the choice of matplotlib GUI backend to use
2470 2469 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2471 2470 'gtk'), otherwise we use the default chosen by matplotlib (as
2472 2471 dictated by the matplotlib build-time options plus the user's
2473 2472 matplotlibrc configuration file).
2474 2473 """
2475 2474 # We want to prevent the loading of pylab to pollute the user's
2476 2475 # namespace as shown by the %who* magics, so we execute the activation
2477 2476 # code in an empty namespace, and we update *both* user_ns and
2478 2477 # user_config_ns with this information.
2479 2478 ns = {}
2480 2479 gui = pylab_activate(ns, gui)
2481 2480 self.user_ns.update(ns)
2482 2481 self.user_config_ns.update(ns)
2483 2482 # Now we must activate the gui pylab wants to use, and fix %run to take
2484 2483 # plot updates into account
2485 2484 enable_gui(gui)
2486 2485 self.magic_run = self._pylab_magic_run
2487 2486
2488 2487 #-------------------------------------------------------------------------
2489 2488 # Things related to IPython exiting
2490 2489 #-------------------------------------------------------------------------
2491 2490
2492 2491 def ask_exit(self):
2493 2492 """ Ask the shell to exit. Can be overiden and used as a callback. """
2494 2493 self.exit_now = True
2495 2494
2496 2495 def exit(self):
2497 2496 """Handle interactive exit.
2498 2497
2499 2498 This method calls the ask_exit callback."""
2500 2499 if self.confirm_exit:
2501 2500 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2502 2501 self.ask_exit()
2503 2502 else:
2504 2503 self.ask_exit()
2505 2504
2506 2505 def atexit_operations(self):
2507 2506 """This will be executed at the time of exit.
2508 2507
2509 2508 Saving of persistent data should be performed here.
2510 2509 """
2511 2510 self.savehist()
2512 2511
2513 2512 # Cleanup all tempfiles left around
2514 2513 for tfile in self.tempfiles:
2515 2514 try:
2516 2515 os.unlink(tfile)
2517 2516 except OSError:
2518 2517 pass
2519 2518
2520 2519 # Clear all user namespaces to release all references cleanly.
2521 2520 self.reset()
2522 2521
2523 2522 # Run user hooks
2524 2523 self.hooks.shutdown_hook()
2525 2524
2526 2525 def cleanup(self):
2527 2526 self.restore_sys_module_state()
2528 2527
2529 2528
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,75 +1,245 b''
1 1 """Tests for the key iplib module, where the main ipython class is defined.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Module imports
5 5 #-----------------------------------------------------------------------------
6 6
7 7 # stdlib
8 8 import os
9 9 import shutil
10 10 import tempfile
11 11
12 12 # third party
13 13 import nose.tools as nt
14 14
15 15 # our own packages
16 from IPython.core import iplib
17 from IPython.core import ipapi
18 16 from IPython.testing import decorators as dec
17 from IPython.testing.globalipapp import get_ipython
19 18
20 19 #-----------------------------------------------------------------------------
21 20 # Globals
22 21 #-----------------------------------------------------------------------------
23 22
24 # Useful global ipapi object and main IPython one. Unfortunately we have a
25 # long precedent of carrying the 'ipapi' global object which is injected into
26 # the system namespace as _ip, but that keeps a pointer to the actual IPython
27 # InteractiveShell instance, which is named IP. Since in testing we do need
28 # access to the real thing (we want to probe beyond what ipapi exposes), make
29 # here a global reference to each. In general, things that are exposed by the
30 # ipapi instance should be read from there, but we also will often need to use
31 # the actual IPython one.
32
33 # Get the public instance of IPython, and if it's None, make one so we can use
34 # it for testing
35 ip = ipapi.get()
36 if ip is None:
37 # IPython not running yet, make one from the testing machinery for
38 # consistency when the test suite is being run via iptest
39 from IPython.testing.plugin import ipdoctest
40 ip = ipapi.get()
23 # Get the public instance of IPython
24 ip = get_ipython()
41 25
42 26 #-----------------------------------------------------------------------------
43 27 # Test functions
44 28 #-----------------------------------------------------------------------------
45 29
46 30 @dec.parametric
47 31 def test_reset():
48 32 """reset must clear most namespaces."""
49 33 # The number of variables in the private user_config_ns is not zero, but it
50 34 # should be constant regardless of what we do
51 35 nvars_config_ns = len(ip.user_config_ns)
52 36
53 37 # Check that reset runs without error
54 38 ip.reset()
55 39
56 40 # Once we've reset it (to clear of any junk that might have been there from
57 41 # other tests, we can count how many variables are in the user's namespace
58 42 nvars_user_ns = len(ip.user_ns)
59 43
60 44 # Now add a few variables to user_ns, and check that reset clears them
61 45 ip.user_ns['x'] = 1
62 46 ip.user_ns['y'] = 1
63 47 ip.reset()
64 48
65 49 # Finally, check that all namespaces have only as many variables as we
66 50 # expect to find in them:
67 51 for ns in ip.ns_refs_table:
68 52 if ns is ip.user_ns:
69 53 nvars_expected = nvars_user_ns
70 54 elif ns is ip.user_config_ns:
71 55 nvars_expected = nvars_config_ns
72 56 else:
73 57 nvars_expected = 0
74 58
75 59 yield nt.assert_equals(len(ns), nvars_expected)
60
61
62 # Tests for reporting of exceptions in various modes, handling of SystemExit,
63 # and %tb functionality. This is really a mix of testing ultraTB and iplib.
64
65 def doctest_tb_plain():
66 """
67 In [18]: xmode plain
68 Exception reporting mode: Plain
69
70 In [19]: run simpleerr.py
71 Traceback (most recent call last):
72 ...line 32, in <module>
73 bar(mode)
74 ...line 16, in bar
75 div0()
76 ...line 8, in div0
77 x/y
78 ZeroDivisionError: integer division or modulo by zero
79 """
80
81
82 def doctest_tb_context():
83 """
84 In [3]: xmode context
85 Exception reporting mode: Context
86
87 In [4]: run simpleerr.py
88 ---------------------------------------------------------------------------
89 ZeroDivisionError Traceback (most recent call last)
90 <BLANKLINE>
91 ... in <module>()
92 30 mode = 'div'
93 31
94 ---> 32 bar(mode)
95 33
96 34
97 <BLANKLINE>
98 ... in bar(mode)
99 14 "bar"
100 15 if mode=='div':
101 ---> 16 div0()
102 17 elif mode=='exit':
103 18 try:
104 <BLANKLINE>
105 ... in div0()
106 6 x = 1
107 7 y = 0
108 ----> 8 x/y
109 9
110 10 def sysexit(stat, mode):
111 <BLANKLINE>
112 ZeroDivisionError: integer division or modulo by zero
113 """
114
115
116 def doctest_tb_verbose():
117 """
118 In [5]: xmode verbose
119 Exception reporting mode: Verbose
120
121 In [6]: run simpleerr.py
122 ---------------------------------------------------------------------------
123 ZeroDivisionError Traceback (most recent call last)
124 <BLANKLINE>
125 ... in <module>()
126 30 mode = 'div'
127 31
128 ---> 32 bar(mode)
129 global bar = <function bar at ...>
130 global mode = 'div'
131 33
132 34
133 <BLANKLINE>
134 ... in bar(mode='div')
135 14 "bar"
136 15 if mode=='div':
137 ---> 16 div0()
138 global div0 = <function div0 at ...>
139 17 elif mode=='exit':
140 18 try:
141 <BLANKLINE>
142 ... in div0()
143 6 x = 1
144 7 y = 0
145 ----> 8 x/y
146 x = 1
147 y = 0
148 9
149 10 def sysexit(stat, mode):
150 <BLANKLINE>
151 ZeroDivisionError: integer division or modulo by zero
152 """
153
154
155 def doctest_tb_sysexit():
156 """
157 In [17]: %xmode plain
158 Exception reporting mode: Plain
159
160 In [18]: %run simpleerr.py exit
161 An exception has occurred, use %tb to see the full traceback.
162 SystemExit: (1, 'Mode = exit')
163
164 In [19]: %run simpleerr.py exit 2
165 An exception has occurred, use %tb to see the full traceback.
166 SystemExit: (2, 'Mode = exit')
167
168 In [20]: %tb
169 Traceback (most recent call last):
170 File ... in <module>
171 bar(mode)
172 File ... line 22, in bar
173 sysexit(stat, mode)
174 File ... line 11, in sysexit
175 raise SystemExit(stat, 'Mode = %s' % mode)
176 SystemExit: (2, 'Mode = exit')
177
178 In [21]: %xmode context
179 Exception reporting mode: Context
180
181 In [22]: %tb
182 ---------------------------------------------------------------------------
183 SystemExit Traceback (most recent call last)
184 <BLANKLINE>
185 ...<module>()
186 30 mode = 'div'
187 31
188 ---> 32 bar(mode)
189 33
190 34
191 <BLANKLINE>
192 ...bar(mode)
193 20 except:
194 21 stat = 1
195 ---> 22 sysexit(stat, mode)
196 23 else:
197 24 raise ValueError('Unknown mode')
198 <BLANKLINE>
199 ...sysexit(stat, mode)
200 9
201 10 def sysexit(stat, mode):
202 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
203 12
204 13 def bar(mode):
205 <BLANKLINE>
206 SystemExit: (2, 'Mode = exit')
207
208 In [23]: %xmode verbose
209 Exception reporting mode: Verbose
210
211 In [24]: %tb
212 ---------------------------------------------------------------------------
213 SystemExit Traceback (most recent call last)
214 <BLANKLINE>
215 ... in <module>()
216 30 mode = 'div'
217 31
218 ---> 32 bar(mode)
219 global bar = <function bar at ...>
220 global mode = 'exit'
221 33
222 34
223 <BLANKLINE>
224 ... in bar(mode='exit')
225 20 except:
226 21 stat = 1
227 ---> 22 sysexit(stat, mode)
228 global sysexit = <function sysexit at ...>
229 stat = 2
230 mode = 'exit'
231 23 else:
232 24 raise ValueError('Unknown mode')
233 <BLANKLINE>
234 ... in sysexit(stat=2, mode='exit')
235 9
236 10 def sysexit(stat, mode):
237 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
238 global SystemExit = undefined
239 stat = 2
240 mode = 'exit'
241 12
242 13 def bar(mode):
243 <BLANKLINE>
244 SystemExit: (2, 'Mode = exit')
245 """
@@ -1,1062 +1,1098 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 string
81 81 import sys
82 82 import time
83 83 import tokenize
84 84 import traceback
85 85 import types
86 86
87 87 # For purposes of monkeypatching inspect to fix a bug in it.
88 88 from inspect import getsourcefile, getfile, getmodule,\
89 89 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
90 90
91 91
92 92 # IPython's own modules
93 93 # Modified pdb which doesn't damage IPython's readline handling
94 94 from IPython.utils import PyColorize
95 95 from IPython.core import debugger, ipapi
96 96 from IPython.core.display_trap import DisplayTrap
97 97 from IPython.utils.ipstruct import Struct
98 98 from IPython.core.excolors import exception_colors
99 99 from IPython.utils.genutils import Term, uniq_stable, error, info
100 100
101 101 # Globals
102 102 # amount of space to put line numbers before verbose tracebacks
103 103 INDENT_SIZE = 8
104 104
105 105 # Default color scheme. This is used, for example, by the traceback
106 106 # formatter. When running in an actual IPython instance, the user's rc.colors
107 107 # value is used, but havinga module global makes this functionality available
108 108 # to users of ultratb who are NOT running inside ipython.
109 109 DEFAULT_SCHEME = 'NoColor'
110 110
111 111 #---------------------------------------------------------------------------
112 112 # Code begins
113 113
114 114 # Utility functions
115 115 def inspect_error():
116 116 """Print a message about internal inspect errors.
117 117
118 118 These are unfortunately quite common."""
119 119
120 120 error('Internal Python error in the inspect module.\n'
121 121 'Below is the traceback from this internal error.\n')
122 122
123 123
124 124 def findsource(object):
125 125 """Return the entire source file and starting line number for an object.
126 126
127 127 The argument may be a module, class, method, function, traceback, frame,
128 128 or code object. The source code is returned as a list of all the lines
129 129 in the file and the line number indexes a line in that list. An IOError
130 130 is raised if the source code cannot be retrieved.
131 131
132 132 FIXED version with which we monkeypatch the stdlib to work around a bug."""
133 133
134 134 file = getsourcefile(object) or getfile(object)
135 135 # If the object is a frame, then trying to get the globals dict from its
136 136 # module won't work. Instead, the frame object itself has the globals
137 137 # dictionary.
138 138 globals_dict = None
139 139 if inspect.isframe(object):
140 140 # XXX: can this ever be false?
141 141 globals_dict = object.f_globals
142 142 else:
143 143 module = getmodule(object, file)
144 144 if module:
145 145 globals_dict = module.__dict__
146 146 lines = linecache.getlines(file, globals_dict)
147 147 if not lines:
148 148 raise IOError('could not get source code')
149 149
150 150 if ismodule(object):
151 151 return lines, 0
152 152
153 153 if isclass(object):
154 154 name = object.__name__
155 155 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
156 156 # make some effort to find the best matching class definition:
157 157 # use the one with the least indentation, which is the one
158 158 # that's most probably not inside a function definition.
159 159 candidates = []
160 160 for i in range(len(lines)):
161 161 match = pat.match(lines[i])
162 162 if match:
163 163 # if it's at toplevel, it's already the best one
164 164 if lines[i][0] == 'c':
165 165 return lines, i
166 166 # else add whitespace to candidate list
167 167 candidates.append((match.group(1), i))
168 168 if candidates:
169 169 # this will sort by whitespace, and by line number,
170 170 # less whitespace first
171 171 candidates.sort()
172 172 return lines, candidates[0][1]
173 173 else:
174 174 raise IOError('could not find class definition')
175 175
176 176 if ismethod(object):
177 177 object = object.im_func
178 178 if isfunction(object):
179 179 object = object.func_code
180 180 if istraceback(object):
181 181 object = object.tb_frame
182 182 if isframe(object):
183 183 object = object.f_code
184 184 if iscode(object):
185 185 if not hasattr(object, 'co_firstlineno'):
186 186 raise IOError('could not find function definition')
187 187 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
188 188 pmatch = pat.match
189 189 # fperez - fix: sometimes, co_firstlineno can give a number larger than
190 190 # the length of lines, which causes an error. Safeguard against that.
191 191 lnum = min(object.co_firstlineno,len(lines))-1
192 192 while lnum > 0:
193 193 if pmatch(lines[lnum]): break
194 194 lnum -= 1
195 195
196 196 return lines, lnum
197 197 raise IOError('could not find code object')
198 198
199 199 # Monkeypatch inspect to apply our bugfix. This code only works with py25
200 200 if sys.version_info[:2] >= (2,5):
201 201 inspect.findsource = findsource
202 202
203 203 def fix_frame_records_filenames(records):
204 204 """Try to fix the filenames in each record from inspect.getinnerframes().
205 205
206 206 Particularly, modules loaded from within zip files have useless filenames
207 207 attached to their code object, and inspect.getinnerframes() just uses it.
208 208 """
209 209 fixed_records = []
210 210 for frame, filename, line_no, func_name, lines, index in records:
211 211 # Look inside the frame's globals dictionary for __file__, which should
212 212 # be better.
213 213 better_fn = frame.f_globals.get('__file__', None)
214 214 if isinstance(better_fn, str):
215 215 # Check the type just in case someone did something weird with
216 216 # __file__. It might also be None if the error occurred during
217 217 # import.
218 218 filename = better_fn
219 219 fixed_records.append((frame, filename, line_no, func_name, lines, index))
220 220 return fixed_records
221 221
222 222
223 223 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
224 224 import linecache
225 225 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
226 226
227 227 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
228 228
229 229 # If the error is at the console, don't build any context, since it would
230 230 # otherwise produce 5 blank lines printed out (there is no file at the
231 231 # console)
232 232 rec_check = records[tb_offset:]
233 233 try:
234 234 rname = rec_check[0][1]
235 235 if rname == '<ipython console>' or rname.endswith('<string>'):
236 236 return rec_check
237 237 except IndexError:
238 238 pass
239 239
240 240 aux = traceback.extract_tb(etb)
241 241 assert len(records) == len(aux)
242 242 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
243 243 maybeStart = lnum-1 - context//2
244 244 start = max(maybeStart, 0)
245 245 end = start + context
246 246 lines = linecache.getlines(file)[start:end]
247 247 # pad with empty lines if necessary
248 248 if maybeStart < 0:
249 249 lines = (['\n'] * -maybeStart) + lines
250 250 if len(lines) < context:
251 251 lines += ['\n'] * (context - len(lines))
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 new_line, err = _line_format(line,'str',scheme)
283 283 if not err: line = new_line
284 284
285 285 if i == lnum:
286 286 # This is the line with the error
287 287 pad = numbers_width - len(str(i))
288 288 if pad >= 3:
289 289 marker = '-'*(pad-3) + '-> '
290 290 elif pad == 2:
291 291 marker = '> '
292 292 elif pad == 1:
293 293 marker = '>'
294 294 else:
295 295 marker = ''
296 296 num = marker + str(i)
297 297 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
298 298 Colors.line, line, Colors.Normal)
299 299 else:
300 300 num = '%*s' % (numbers_width,i)
301 301 line = '%s%s%s %s' %(Colors.lineno, num,
302 302 Colors.Normal, line)
303 303
304 304 res.append(line)
305 305 if lvals and i == lnum:
306 306 res.append(lvals + '\n')
307 307 i = i + 1
308 308 return res
309 309
310 310
311 311 #---------------------------------------------------------------------------
312 312 # Module classes
313 313 class TBTools:
314 314 """Basic tools used by all traceback printer classes."""
315 #: Default output stream, can be overridden at call time. A special value
316 #: of 'stdout' *as a string* can be given to force extraction of sys.stdout
317 #: at runtime. This allows testing exception printing with doctests, that
318 #: swap sys.stdout just at execution time.
319 out_stream = sys.stderr
315 320
316 321 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
317 322 # Whether to call the interactive pdb debugger after printing
318 323 # tracebacks or not
319 324 self.call_pdb = call_pdb
320 325
321 326 # Create color table
322 327 self.color_scheme_table = exception_colors()
323 328
324 329 self.set_colors(color_scheme)
325 330 self.old_scheme = color_scheme # save initial value for toggles
326 331
327 332 if call_pdb:
328 333 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
329 334 else:
330 335 self.pdb = None
331 336
332 337 def set_colors(self,*args,**kw):
333 338 """Shorthand access to the color table scheme selector method."""
334 339
335 340 # Set own color table
336 341 self.color_scheme_table.set_active_scheme(*args,**kw)
337 342 # for convenience, set Colors to the active scheme
338 343 self.Colors = self.color_scheme_table.active_colors
339 344 # Also set colors of debugger
340 345 if hasattr(self,'pdb') and self.pdb is not None:
341 346 self.pdb.set_colors(*args,**kw)
342 347
343 348 def color_toggle(self):
344 349 """Toggle between the currently active color scheme and NoColor."""
345 350
346 351 if self.color_scheme_table.active_scheme_name == 'NoColor':
347 352 self.color_scheme_table.set_active_scheme(self.old_scheme)
348 353 self.Colors = self.color_scheme_table.active_colors
349 354 else:
350 355 self.old_scheme = self.color_scheme_table.active_scheme_name
351 356 self.color_scheme_table.set_active_scheme('NoColor')
352 357 self.Colors = self.color_scheme_table.active_colors
353 358
354 359 #---------------------------------------------------------------------------
355 360 class ListTB(TBTools):
356 361 """Print traceback information from a traceback list, with optional color.
357 362
358 363 Calling: requires 3 arguments:
359 364 (etype, evalue, elist)
360 365 as would be obtained by:
361 366 etype, evalue, tb = sys.exc_info()
362 367 if tb:
363 368 elist = traceback.extract_tb(tb)
364 369 else:
365 370 elist = None
366 371
367 372 It can thus be used by programs which need to process the traceback before
368 373 printing (such as console replacements based on the code module from the
369 374 standard library).
370 375
371 376 Because they are meant to be called without a full traceback (only a
372 377 list), instances of this class can't call the interactive pdb debugger."""
373 378
374 379 def __init__(self,color_scheme = 'NoColor'):
375 380 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
376 381
377 382 def __call__(self, etype, value, elist):
378 383 Term.cout.flush()
379 384 print >> Term.cerr, self.text(etype,value,elist)
380 385 Term.cerr.flush()
381 386
382 def text(self,etype, value, elist,context=5):
383 """Return a color formatted string with the traceback info."""
387 def text(self, etype, value, elist, context=5):
388 """Return a color formatted string with the traceback info.
389
390 Parameters
391 ----------
392 etype : exception type
393 Type of the exception raised.
394
395 value : object
396 Data stored in the exception
397
398 elist : list
399 List of frames, see class docstring for details.
400
401 Returns
402 -------
403 String with formatted exception.
404 """
384 405
385 406 Colors = self.Colors
386 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
407 out_string = []
387 408 if elist:
388 out_string.append('Traceback %s(most recent call last)%s:' % \
409 out_string.append('Traceback %s(most recent call last)%s:' %
389 410 (Colors.normalEm, Colors.Normal) + '\n')
390 411 out_string.extend(self._format_list(elist))
391 412 lines = self._format_exception_only(etype, value)
392 413 for line in lines[:-1]:
393 414 out_string.append(" "+line)
394 415 out_string.append(lines[-1])
395 416 return ''.join(out_string)
396 417
397 418 def _format_list(self, extracted_list):
398 419 """Format a list of traceback entry tuples for printing.
399 420
400 421 Given a list of tuples as returned by extract_tb() or
401 422 extract_stack(), return a list of strings ready for printing.
402 423 Each string in the resulting list corresponds to the item with the
403 424 same index in the argument list. Each string ends in a newline;
404 425 the strings may contain internal newlines as well, for those items
405 426 whose source text line is not None.
406 427
407 428 Lifted almost verbatim from traceback.py
408 429 """
409 430
410 431 Colors = self.Colors
411 432 list = []
412 433 for filename, lineno, name, line in extracted_list[:-1]:
413 434 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
414 435 (Colors.filename, filename, Colors.Normal,
415 436 Colors.lineno, lineno, Colors.Normal,
416 437 Colors.name, name, Colors.Normal)
417 438 if line:
418 439 item = item + ' %s\n' % line.strip()
419 440 list.append(item)
420 441 # Emphasize the last entry
421 442 filename, lineno, name, line = extracted_list[-1]
422 443 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
423 444 (Colors.normalEm,
424 445 Colors.filenameEm, filename, Colors.normalEm,
425 446 Colors.linenoEm, lineno, Colors.normalEm,
426 447 Colors.nameEm, name, Colors.normalEm,
427 448 Colors.Normal)
428 449 if line:
429 450 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
430 451 Colors.Normal)
431 452 list.append(item)
432 453 return list
433 454
434 455 def _format_exception_only(self, etype, value):
435 456 """Format the exception part of a traceback.
436 457
437 458 The arguments are the exception type and value such as given by
438 459 sys.exc_info()[:2]. The return value is a list of strings, each ending
439 460 in a newline. Normally, the list contains a single string; however,
440 461 for SyntaxError exceptions, it contains several lines that (when
441 462 printed) display detailed information about where the syntax error
442 463 occurred. The message indicating which exception occurred is the
443 464 always last string in the list.
444 465
445 466 Also lifted nearly verbatim from traceback.py
446 467 """
447 468
448 469 have_filedata = False
449 470 Colors = self.Colors
450 471 list = []
451 472 try:
452 473 stype = Colors.excName + etype.__name__ + Colors.Normal
453 474 except AttributeError:
454 475 stype = etype # String exceptions don't get special coloring
455 476 if value is None:
456 477 list.append( str(stype) + '\n')
457 478 else:
458 479 if etype is SyntaxError:
459 480 try:
460 481 msg, (filename, lineno, offset, line) = value
461 482 except:
462 483 have_filedata = False
463 484 else:
464 485 have_filedata = True
465 486 #print 'filename is',filename # dbg
466 487 if not filename: filename = "<string>"
467 488 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
468 489 (Colors.normalEm,
469 490 Colors.filenameEm, filename, Colors.normalEm,
470 491 Colors.linenoEm, lineno, Colors.Normal ))
471 492 if line is not None:
472 493 i = 0
473 494 while i < len(line) and line[i].isspace():
474 495 i = i+1
475 496 list.append('%s %s%s\n' % (Colors.line,
476 497 line.strip(),
477 498 Colors.Normal))
478 499 if offset is not None:
479 500 s = ' '
480 501 for c in line[i:offset-1]:
481 502 if c.isspace():
482 503 s = s + c
483 504 else:
484 505 s = s + ' '
485 506 list.append('%s%s^%s\n' % (Colors.caret, s,
486 507 Colors.Normal) )
487 508 value = msg
488 509 s = self._some_str(value)
489 510 if s:
490 511 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
491 512 Colors.Normal, s))
492 513 else:
493 514 list.append('%s\n' % str(stype))
494 515
495 # vds:>>
516 # sync with user hooks
496 517 if have_filedata:
497 518 ipinst = ipapi.get()
498 519 if ipinst is not None:
499 520 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
500 # vds:<<
501 521
502 522 return list
503 523
524 def show_exception_only(self, etype, value):
525 """Only print the exception type and message, without a traceback.
526
527 Parameters
528 ----------
529 etype : exception type
530 value : exception value
531 """
532 # This method needs to use __call__ from *this* class, not the one from
533 # a subclass whose signature or behavior may be different
534 Term.cout.flush()
535 ostream = sys.stdout if self.out_stream == 'stdout' else Term.cerr
536 print >> ostream, ListTB.text(self, etype, value, []),
537 ostream.flush()
538
504 539 def _some_str(self, value):
505 540 # Lifted from traceback.py
506 541 try:
507 542 return str(value)
508 543 except:
509 544 return '<unprintable %s object>' % type(value).__name__
510 545
511 546 #----------------------------------------------------------------------------
512 547 class VerboseTB(TBTools):
513 548 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
514 549 of HTML. Requires inspect and pydoc. Crazy, man.
515 550
516 551 Modified version which optionally strips the topmost entries from the
517 552 traceback, to be used with alternate interpreters (because their own code
518 553 would appear in the traceback)."""
519 554
520 555 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
521 556 call_pdb = 0, include_vars=1):
522 557 """Specify traceback offset, headers and color scheme.
523 558
524 559 Define how many frames to drop from the tracebacks. Calling it with
525 560 tb_offset=1 allows use of this handler in interpreters which will have
526 561 their own code at the top of the traceback (VerboseTB will first
527 562 remove that frame before printing the traceback info)."""
528 563 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
529 564 self.tb_offset = tb_offset
530 565 self.long_header = long_header
531 566 self.include_vars = include_vars
532 567
533 568 def text(self, etype, evalue, etb, context=5):
534 569 """Return a nice text document describing the traceback."""
535 570
536 571 # some locals
537 572 try:
538 573 etype = etype.__name__
539 574 except AttributeError:
540 575 pass
541 576 Colors = self.Colors # just a shorthand + quicker name lookup
542 577 ColorsNormal = Colors.Normal # used a lot
543 578 col_scheme = self.color_scheme_table.active_scheme_name
544 579 indent = ' '*INDENT_SIZE
545 580 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
546 581 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
547 582 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
548 583
549 584 # some internal-use functions
550 585 def text_repr(value):
551 586 """Hopefully pretty robust repr equivalent."""
552 587 # this is pretty horrible but should always return *something*
553 588 try:
554 589 return pydoc.text.repr(value)
555 590 except KeyboardInterrupt:
556 591 raise
557 592 except:
558 593 try:
559 594 return repr(value)
560 595 except KeyboardInterrupt:
561 596 raise
562 597 except:
563 598 try:
564 599 # all still in an except block so we catch
565 600 # getattr raising
566 601 name = getattr(value, '__name__', None)
567 602 if name:
568 603 # ick, recursion
569 604 return text_repr(name)
570 605 klass = getattr(value, '__class__', None)
571 606 if klass:
572 607 return '%s instance' % text_repr(klass)
573 608 except KeyboardInterrupt:
574 609 raise
575 610 except:
576 611 return 'UNRECOVERABLE REPR FAILURE'
577 612 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
578 613 def nullrepr(value, repr=text_repr): return ''
579 614
580 615 # meat of the code begins
581 616 try:
582 617 etype = etype.__name__
583 618 except AttributeError:
584 619 pass
585 620
586 621 if self.long_header:
587 622 # Header with the exception type, python version, and date
588 623 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
589 624 date = time.ctime(time.time())
590 625
591 626 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
592 627 exc, ' '*(75-len(str(etype))-len(pyver)),
593 628 pyver, string.rjust(date, 75) )
594 629 head += "\nA problem occured executing Python code. Here is the sequence of function"\
595 630 "\ncalls leading up to the error, with the most recent (innermost) call last."
596 631 else:
597 632 # Simplified header
598 633 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
599 634 string.rjust('Traceback (most recent call last)',
600 635 75 - len(str(etype)) ) )
601 636 frames = []
602 637 # Flush cache before calling inspect. This helps alleviate some of the
603 638 # problems with python 2.3's inspect.py.
604 639 linecache.checkcache()
605 640 # Drop topmost frames if requested
606 641 try:
607 642 # Try the default getinnerframes and Alex's: Alex's fixes some
608 643 # problems, but it generates empty tracebacks for console errors
609 644 # (5 blanks lines) where none should be returned.
610 645 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
611 646 #print 'python records:', records # dbg
612 647 records = _fixed_getinnerframes(etb, context,self.tb_offset)
613 648 #print 'alex records:', records # dbg
614 649 except:
615 650
616 651 # FIXME: I've been getting many crash reports from python 2.3
617 652 # users, traceable to inspect.py. If I can find a small test-case
618 653 # to reproduce this, I should either write a better workaround or
619 654 # file a bug report against inspect (if that's the real problem).
620 655 # So far, I haven't been able to find an isolated example to
621 656 # reproduce the problem.
622 657 inspect_error()
623 658 traceback.print_exc(file=Term.cerr)
624 659 info('\nUnfortunately, your original traceback can not be constructed.\n')
625 660 return ''
626 661
627 662 # build some color string templates outside these nested loops
628 663 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
629 664 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
630 665 ColorsNormal)
631 666 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
632 667 (Colors.vName, Colors.valEm, ColorsNormal)
633 668 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
634 669 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
635 670 Colors.vName, ColorsNormal)
636 671 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
637 672 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
638 673 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
639 674 ColorsNormal)
640 675
641 676 # now, loop over all records printing context and info
642 677 abspath = os.path.abspath
643 678 for frame, file, lnum, func, lines, index in records:
644 679 #print '*** record:',file,lnum,func,lines,index # dbg
645 680 try:
646 681 file = file and abspath(file) or '?'
647 682 except OSError:
648 683 # if file is '<console>' or something not in the filesystem,
649 684 # the abspath call will throw an OSError. Just ignore it and
650 685 # keep the original file string.
651 686 pass
652 687 link = tpl_link % file
653 688 try:
654 689 args, varargs, varkw, locals = inspect.getargvalues(frame)
655 690 except:
656 691 # This can happen due to a bug in python2.3. We should be
657 692 # able to remove this try/except when 2.4 becomes a
658 693 # requirement. Bug details at http://python.org/sf/1005466
659 694 inspect_error()
660 695 traceback.print_exc(file=Term.cerr)
661 696 info("\nIPython's exception reporting continues...\n")
662 697
663 698 if func == '?':
664 699 call = ''
665 700 else:
666 701 # Decide whether to include variable details or not
667 702 var_repr = self.include_vars and eqrepr or nullrepr
668 703 try:
669 704 call = tpl_call % (func,inspect.formatargvalues(args,
670 705 varargs, varkw,
671 706 locals,formatvalue=var_repr))
672 707 except KeyError:
673 708 # Very odd crash from inspect.formatargvalues(). The
674 709 # scenario under which it appeared was a call to
675 710 # view(array,scale) in NumTut.view.view(), where scale had
676 711 # been defined as a scalar (it should be a tuple). Somehow
677 712 # inspect messes up resolving the argument list of view()
678 713 # and barfs out. At some point I should dig into this one
679 714 # and file a bug report about it.
680 715 inspect_error()
681 716 traceback.print_exc(file=Term.cerr)
682 717 info("\nIPython's exception reporting continues...\n")
683 718 call = tpl_call_fail % func
684 719
685 720 # Initialize a list of names on the current line, which the
686 721 # tokenizer below will populate.
687 722 names = []
688 723
689 724 def tokeneater(token_type, token, start, end, line):
690 725 """Stateful tokeneater which builds dotted names.
691 726
692 727 The list of names it appends to (from the enclosing scope) can
693 728 contain repeated composite names. This is unavoidable, since
694 729 there is no way to disambguate partial dotted structures until
695 730 the full list is known. The caller is responsible for pruning
696 731 the final list of duplicates before using it."""
697 732
698 733 # build composite names
699 734 if token == '.':
700 735 try:
701 736 names[-1] += '.'
702 737 # store state so the next token is added for x.y.z names
703 738 tokeneater.name_cont = True
704 739 return
705 740 except IndexError:
706 741 pass
707 742 if token_type == tokenize.NAME and token not in keyword.kwlist:
708 743 if tokeneater.name_cont:
709 744 # Dotted names
710 745 names[-1] += token
711 746 tokeneater.name_cont = False
712 747 else:
713 748 # Regular new names. We append everything, the caller
714 749 # will be responsible for pruning the list later. It's
715 750 # very tricky to try to prune as we go, b/c composite
716 751 # names can fool us. The pruning at the end is easy
717 752 # to do (or the caller can print a list with repeated
718 753 # names if so desired.
719 754 names.append(token)
720 755 elif token_type == tokenize.NEWLINE:
721 756 raise IndexError
722 757 # we need to store a bit of state in the tokenizer to build
723 758 # dotted names
724 759 tokeneater.name_cont = False
725 760
726 761 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
727 762 line = getline(file, lnum[0])
728 763 lnum[0] += 1
729 764 return line
730 765
731 766 # Build the list of names on this line of code where the exception
732 767 # occurred.
733 768 try:
734 769 # This builds the names list in-place by capturing it from the
735 770 # enclosing scope.
736 771 tokenize.tokenize(linereader, tokeneater)
737 772 except IndexError:
738 773 # signals exit of tokenizer
739 774 pass
740 775 except tokenize.TokenError,msg:
741 776 _m = ("An unexpected error occurred while tokenizing input\n"
742 777 "The following traceback may be corrupted or invalid\n"
743 778 "The error message is: %s\n" % msg)
744 779 error(_m)
745 780
746 781 # prune names list of duplicates, but keep the right order
747 782 unique_names = uniq_stable(names)
748 783
749 784 # Start loop over vars
750 785 lvals = []
751 786 if self.include_vars:
752 787 for name_full in unique_names:
753 788 name_base = name_full.split('.',1)[0]
754 789 if name_base in frame.f_code.co_varnames:
755 790 if locals.has_key(name_base):
756 791 try:
757 792 value = repr(eval(name_full,locals))
758 793 except:
759 794 value = undefined
760 795 else:
761 796 value = undefined
762 797 name = tpl_local_var % name_full
763 798 else:
764 799 if frame.f_globals.has_key(name_base):
765 800 try:
766 801 value = repr(eval(name_full,frame.f_globals))
767 802 except:
768 803 value = undefined
769 804 else:
770 805 value = undefined
771 806 name = tpl_global_var % name_full
772 807 lvals.append(tpl_name_val % (name,value))
773 808 if lvals:
774 809 lvals = '%s%s' % (indent,em_normal.join(lvals))
775 810 else:
776 811 lvals = ''
777 812
778 813 level = '%s %s\n' % (link,call)
779 814
780 815 if index is None:
781 816 frames.append(level)
782 817 else:
783 818 frames.append('%s%s' % (level,''.join(
784 819 _format_traceback_lines(lnum,index,lines,Colors,lvals,
785 820 col_scheme))))
786 821
787 822 # Get (safely) a string form of the exception info
788 823 try:
789 824 etype_str,evalue_str = map(str,(etype,evalue))
790 825 except:
791 826 # User exception is improperly defined.
792 827 etype,evalue = str,sys.exc_info()[:2]
793 828 etype_str,evalue_str = map(str,(etype,evalue))
794 829 # ... and format it
795 830 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
796 831 ColorsNormal, evalue_str)]
797 832 if type(evalue) is types.InstanceType:
798 833 try:
799 834 names = [w for w in dir(evalue) if isinstance(w, basestring)]
800 835 except:
801 836 # Every now and then, an object with funny inernals blows up
802 837 # when dir() is called on it. We do the best we can to report
803 838 # the problem and continue
804 839 _m = '%sException reporting error (object with broken dir())%s:'
805 840 exception.append(_m % (Colors.excName,ColorsNormal))
806 841 etype_str,evalue_str = map(str,sys.exc_info()[:2])
807 842 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
808 843 ColorsNormal, evalue_str))
809 844 names = []
810 845 for name in names:
811 846 value = text_repr(getattr(evalue, name))
812 847 exception.append('\n%s%s = %s' % (indent, name, value))
813 848
814 849 # vds: >>
815 850 if records:
816 851 filepath, lnum = records[-1][1:3]
817 852 #print "file:", str(file), "linenb", str(lnum) # dbg
818 853 filepath = os.path.abspath(filepath)
819 854 ipinst = ipapi.get()
820 855 if ipinst is not None:
821 856 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
822 857 # vds: <<
823 858
824 859 # return all our info assembled as a single string
825 860 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
826 861
827 862 def debugger(self,force=False):
828 863 """Call up the pdb debugger if desired, always clean up the tb
829 864 reference.
830 865
831 866 Keywords:
832 867
833 868 - force(False): by default, this routine checks the instance call_pdb
834 869 flag and does not actually invoke the debugger if the flag is false.
835 870 The 'force' option forces the debugger to activate even if the flag
836 871 is false.
837 872
838 873 If the call_pdb flag is set, the pdb interactive debugger is
839 874 invoked. In all cases, the self.tb reference to the current traceback
840 875 is deleted to prevent lingering references which hamper memory
841 876 management.
842 877
843 878 Note that each call to pdb() does an 'import readline', so if your app
844 879 requires a special setup for the readline completers, you'll have to
845 880 fix that by hand after invoking the exception handler."""
846 881
847 882 if force or self.call_pdb:
848 883 if self.pdb is None:
849 884 self.pdb = debugger.Pdb(
850 885 self.color_scheme_table.active_scheme_name)
851 886 # the system displayhook may have changed, restore the original
852 887 # for pdb
853 888 display_trap = DisplayTrap(None, sys.__displayhook__)
854 889 with display_trap:
855 890 self.pdb.reset()
856 891 # Find the right frame so we don't pop up inside ipython itself
857 892 if hasattr(self,'tb') and self.tb is not None:
858 893 etb = self.tb
859 894 else:
860 895 etb = self.tb = sys.last_traceback
861 896 while self.tb is not None and self.tb.tb_next is not None:
862 897 self.tb = self.tb.tb_next
863 898 if etb and etb.tb_next:
864 899 etb = etb.tb_next
865 900 self.pdb.botframe = etb.tb_frame
866 901 self.pdb.interaction(self.tb.tb_frame, self.tb)
867 902
868 903 if hasattr(self,'tb'):
869 904 del self.tb
870 905
871 906 def handler(self, info=None):
872 907 (etype, evalue, etb) = info or sys.exc_info()
873 908 self.tb = etb
874 909 Term.cout.flush()
875 910 print >> Term.cerr, self.text(etype, evalue, etb)
876 911 Term.cerr.flush()
877 912
878 913 # Changed so an instance can just be called as VerboseTB_inst() and print
879 914 # out the right info on its own.
880 915 def __call__(self, etype=None, evalue=None, etb=None):
881 916 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
882 917 if etb is None:
883 918 self.handler()
884 919 else:
885 920 self.handler((etype, evalue, etb))
886 921 try:
887 922 self.debugger()
888 923 except KeyboardInterrupt:
889 924 print "\nKeyboardInterrupt"
890 925
891 926 #----------------------------------------------------------------------------
892 927 class FormattedTB(VerboseTB,ListTB):
893 928 """Subclass ListTB but allow calling with a traceback.
894 929
895 930 It can thus be used as a sys.excepthook for Python > 2.1.
896 931
897 932 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
898 933
899 934 Allows a tb_offset to be specified. This is useful for situations where
900 935 one needs to remove a number of topmost frames from the traceback (such as
901 936 occurs with python programs that themselves execute other python code,
902 937 like Python shells). """
903 938
904 939 def __init__(self, mode = 'Plain', color_scheme='Linux',
905 940 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
906 941
907 942 # NEVER change the order of this list. Put new modes at the end:
908 943 self.valid_modes = ['Plain','Context','Verbose']
909 944 self.verbose_modes = self.valid_modes[1:3]
910 945
911 946 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
912 947 call_pdb=call_pdb,include_vars=include_vars)
913 948 self.set_mode(mode)
914 949
915 950 def _extract_tb(self,tb):
916 951 if tb:
917 952 return traceback.extract_tb(tb)
918 953 else:
919 954 return None
920 955
921 956 def text(self, etype, value, tb,context=5,mode=None):
922 957 """Return formatted traceback.
923 958
924 959 If the optional mode parameter is given, it overrides the current
925 960 mode."""
926 961
927 962 if mode is None:
928 963 mode = self.mode
929 964 if mode in self.verbose_modes:
930 965 # verbose modes need a full traceback
931 966 return VerboseTB.text(self,etype, value, tb,context=5)
932 967 else:
933 968 # We must check the source cache because otherwise we can print
934 969 # out-of-date source code.
935 970 linecache.checkcache()
936 971 # Now we can extract and format the exception
937 972 elist = self._extract_tb(tb)
938 973 if len(elist) > self.tb_offset:
939 974 del elist[:self.tb_offset]
940 975 return ListTB.text(self,etype,value,elist)
941 976
942 977 def set_mode(self,mode=None):
943 978 """Switch to the desired mode.
944 979
945 980 If mode is not specified, cycles through the available modes."""
946 981
947 982 if not mode:
948 983 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
949 984 len(self.valid_modes)
950 985 self.mode = self.valid_modes[new_idx]
951 986 elif mode not in self.valid_modes:
952 987 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
953 988 'Valid modes: '+str(self.valid_modes)
954 989 else:
955 990 self.mode = mode
956 991 # include variable details only in 'Verbose' mode
957 992 self.include_vars = (self.mode == self.valid_modes[2])
958 993
959 994 # some convenient shorcuts
960 995 def plain(self):
961 996 self.set_mode(self.valid_modes[0])
962 997
963 998 def context(self):
964 999 self.set_mode(self.valid_modes[1])
965 1000
966 1001 def verbose(self):
967 1002 self.set_mode(self.valid_modes[2])
968 1003
969 1004 #----------------------------------------------------------------------------
970 1005 class AutoFormattedTB(FormattedTB):
971 1006 """A traceback printer which can be called on the fly.
972 1007
973 1008 It will find out about exceptions by itself.
974 1009
975 1010 A brief example:
976 1011
977 1012 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
978 1013 try:
979 1014 ...
980 1015 except:
981 1016 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
982 1017 """
1018
983 1019 def __call__(self,etype=None,evalue=None,etb=None,
984 1020 out=None,tb_offset=None):
985 1021 """Print out a formatted exception traceback.
986 1022
987 1023 Optional arguments:
988 1024 - out: an open file-like object to direct output to.
989 1025
990 1026 - tb_offset: the number of frames to skip over in the stack, on a
991 1027 per-call basis (this overrides temporarily the instance's tb_offset
992 1028 given at initialization time. """
993
1029
994 1030 if out is None:
995 out = Term.cerr
1031 out = sys.stdout if self.out_stream=='stdout' else self.out_stream
996 1032 Term.cout.flush()
997 1033 if tb_offset is not None:
998 1034 tb_offset, self.tb_offset = self.tb_offset, tb_offset
999 1035 print >> out, self.text(etype, evalue, etb)
1000 1036 self.tb_offset = tb_offset
1001 1037 else:
1002 1038 print >> out, self.text(etype, evalue, etb)
1003 1039 out.flush()
1004 1040 try:
1005 1041 self.debugger()
1006 1042 except KeyboardInterrupt:
1007 1043 print "\nKeyboardInterrupt"
1008 1044
1009 1045 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
1010 1046 if etype is None:
1011 1047 etype,value,tb = sys.exc_info()
1012 1048 self.tb = tb
1013 1049 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
1014 1050
1015 1051 #---------------------------------------------------------------------------
1016 1052 # A simple class to preserve Nathan's original functionality.
1017 1053 class ColorTB(FormattedTB):
1018 1054 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1019 1055 def __init__(self,color_scheme='Linux',call_pdb=0):
1020 1056 FormattedTB.__init__(self,color_scheme=color_scheme,
1021 1057 call_pdb=call_pdb)
1022 1058
1023 1059 #----------------------------------------------------------------------------
1024 1060 # module testing (minimal)
1025 1061 if __name__ == "__main__":
1026 1062 def spam(c, (d, e)):
1027 1063 x = c + d
1028 1064 y = c * d
1029 1065 foo(x, y)
1030 1066
1031 1067 def foo(a, b, bar=1):
1032 1068 eggs(a, b + bar)
1033 1069
1034 1070 def eggs(f, g, z=globals()):
1035 1071 h = f + g
1036 1072 i = f - g
1037 1073 return h / i
1038 1074
1039 1075 print ''
1040 1076 print '*** Before ***'
1041 1077 try:
1042 1078 print spam(1, (2, 3))
1043 1079 except:
1044 1080 traceback.print_exc()
1045 1081 print ''
1046 1082
1047 1083 handler = ColorTB()
1048 1084 print '*** ColorTB ***'
1049 1085 try:
1050 1086 print spam(1, (2, 3))
1051 1087 except:
1052 1088 apply(handler, sys.exc_info() )
1053 1089 print ''
1054 1090
1055 1091 handler = VerboseTB()
1056 1092 print '*** VerboseTB ***'
1057 1093 try:
1058 1094 print spam(1, (2, 3))
1059 1095 except:
1060 1096 apply(handler, sys.exc_info() )
1061 1097 print ''
1062 1098
@@ -1,169 +1,171 b''
1 1 """Global IPython app to support test running.
2 2
3 3 We must start our own ipython object and heavily muck with it so that all the
4 4 modifications IPython makes to system behavior don't send the doctest machinery
5 5 into a fit. This code should be considered a gross hack, but it gets the job
6 6 done.
7 7 """
8 8
9 9 from __future__ import absolute_import
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Module imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # From the standard library
16 16 import __builtin__
17 17 import commands
18 18 import new
19 19 import os
20 20 import sys
21 21
22 22 from . import tools
23 from IPython.utils.genutils import Term
23 24
24 25 #-----------------------------------------------------------------------------
25 26 # Functions
26 27 #-----------------------------------------------------------------------------
27 28
28 29 # Hack to modify the %run command so we can sync the user's namespace with the
29 30 # test globals. Once we move over to a clean magic system, this will be done
30 31 # with much less ugliness.
31 32
32 33 class py_file_finder(object):
33 34 def __init__(self,test_filename):
34 35 self.test_filename = test_filename
35 36
36 37 def __call__(self,name):
37 38 from IPython.utils.genutils import get_py_filename
38 39 try:
39 40 return get_py_filename(name)
40 41 except IOError:
41 42 test_dir = os.path.dirname(self.test_filename)
42 43 new_path = os.path.join(test_dir,name)
43 44 return get_py_filename(new_path)
44 45
45 46
46 47 def _run_ns_sync(self,arg_s,runner=None):
47 48 """Modified version of %run that syncs testing namespaces.
48 49
49 50 This is strictly needed for running doctests that call %run.
50 51 """
51 52 #print >> sys.stderr, 'in run_ns_sync', arg_s # dbg
52 53
53 54 _ip = get_ipython()
54 55 finder = py_file_finder(arg_s)
55 56 out = _ip.magic_run_ori(arg_s,runner,finder)
56 57 return out
57 58
58 59
59 60 class ipnsdict(dict):
60 61 """A special subclass of dict for use as an IPython namespace in doctests.
61 62
62 63 This subclass adds a simple checkpointing capability so that when testing
63 64 machinery clears it (we use it as the test execution context), it doesn't
64 65 get completely destroyed.
65 66 """
66 67
67 68 def __init__(self,*a):
68 69 dict.__init__(self,*a)
69 70 self._savedict = {}
70 71
71 72 def clear(self):
72 73 dict.clear(self)
73 74 self.update(self._savedict)
74 75
75 76 def _checkpoint(self):
76 77 self._savedict.clear()
77 78 self._savedict.update(self)
78 79
79 80 def update(self,other):
80 81 self._checkpoint()
81 82 dict.update(self,other)
82 83
83 84 # If '_' is in the namespace, python won't set it when executing code,
84 85 # and we have examples that test it. So we ensure that the namespace
85 86 # is always 'clean' of it before it's used for test code execution.
86 87 self.pop('_',None)
87 88
88 89 # The builtins namespace must *always* be the real __builtin__ module,
89 90 # else weird stuff happens. The main ipython code does have provisions
90 91 # to ensure this after %run, but since in this class we do some
91 92 # aggressive low-level cleaning of the execution namespace, we need to
92 93 # correct for that ourselves, to ensure consitency with the 'real'
93 94 # ipython.
94 95 self['__builtins__'] = __builtin__
95 96
96 97
97 98 def get_ipython():
98 99 # This will get replaced by the real thing once we start IPython below
99 return None
100 return start_ipython()
100 101
101 102 def start_ipython():
102 103 """Start a global IPython shell, which we need for IPython-specific syntax.
103 104 """
104 105 global get_ipython
105 106
106 107 # This function should only ever run once!
107 108 if hasattr(start_ipython,'already_called'):
108 109 return
109 110 start_ipython.already_called = True
110 111
111 112 # Ok, first time we're called, go ahead
112 113 from IPython.core import ipapp, iplib
113 114
114 115 def xsys(cmd):
115 116 """Execute a command and print its output.
116 117
117 118 This is just a convenience function to replace the IPython system call
118 119 with one that is more doctest-friendly.
119 120 """
120 121 cmd = _ip.var_expand(cmd,depth=1)
121 122 sys.stdout.write(commands.getoutput(cmd))
122 123 sys.stdout.flush()
123 124
124 125 # Store certain global objects that IPython modifies
125 126 _displayhook = sys.displayhook
126 127 _excepthook = sys.excepthook
127 128 _main = sys.modules.get('__main__')
128 129
129 130 argv = tools.default_argv()
130 131
131 132 # Start IPython instance. We customize it to start with minimal frills.
132 133 user_ns,global_ns = iplib.make_user_namespaces(ipnsdict(),{})
133 134 ip = ipapp.IPythonApp(argv, user_ns=user_ns, user_global_ns=global_ns)
134 135 ip.initialize()
135 136 ip.shell.builtin_trap.set()
137 # Set stderr to stdout so nose can doctest exceptions
138 ## Term.cerr = sys.stdout
139 ## sys.stderr = sys.stdout
140 ip.shell.InteractiveTB.out_stream = 'stdout'
136 141 # Butcher the logger
137 142 ip.shell.log = lambda *a,**k: None
138 143
139 144 # Deactivate the various python system hooks added by ipython for
140 145 # interactive convenience so we don't confuse the doctest system
141 146 sys.modules['__main__'] = _main
142 147 sys.displayhook = _displayhook
143 148 sys.excepthook = _excepthook
144 149
145 150 # So that ipython magics and aliases can be doctested (they work by making
146 # a call into a global _ip object)
147
151 # a call into a global _ip object). Also make the top-level get_ipython
152 # now return this without calling here again
148 153 _ip = ip.shell
149 154 get_ipython = _ip.get_ipython
150 155 __builtin__._ip = _ip
151 156 __builtin__.get_ipython = get_ipython
152 157
153 158 # Modify the IPython system call with one that uses getoutput, so that we
154 159 # can capture subcommands and print them to Python's stdout, otherwise the
155 160 # doctest machinery would miss them.
156 161 ip.shell.system = xsys
157 162
158 # Also patch our %run function in.
159 ## im = new.instancemethod(_run_ns_sync,_ip, _ip.__class__)
160 ## ip.shell.magic_run_ori = _ip.magic_run
161 ## ip.shell.magic_run = im
162
163 163 # XXX - For some very bizarre reason, the loading of %history by default is
164 164 # failing. This needs to be fixed later, but for now at least this ensures
165 165 # that tests that use %hist run to completion.
166 166 from IPython.core import history
167 167 history.init_ipython(ip.shell)
168 168 if not hasattr(ip.shell,'magic_history'):
169 169 raise RuntimeError("Can't load magics, aborting")
170
171 return _ip
General Comments 0
You need to be logged in to leave comments. Login now