##// END OF EJS Templates
Improvements to exception handling to transport structured tracebacks....
Fernando Perez -
Show More
@@ -1,2127 +1,2150 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import abc
22 22 import codeop
23 23 import exceptions
24 24 import new
25 25 import os
26 26 import re
27 27 import string
28 28 import sys
29 29 import tempfile
30 30 from contextlib import nested
31 31
32 from IPython.config.configurable import Configurable
32 33 from IPython.core import debugger, oinspect
33 34 from IPython.core import history as ipcorehist
34 35 from IPython.core import prefilter
35 36 from IPython.core import shadowns
36 37 from IPython.core import ultratb
37 38 from IPython.core.alias import AliasManager
38 39 from IPython.core.builtin_trap import BuiltinTrap
39 from IPython.config.configurable import Configurable
40 40 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.displayhook import DisplayHook
41 42 from IPython.core.error import UsageError
42 43 from IPython.core.extensions import ExtensionManager
43 44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 45 from IPython.core.inputlist import InputList
45 46 from IPython.core.logger import Logger
46 47 from IPython.core.magic import Magic
47 48 from IPython.core.payload import PayloadManager
48 49 from IPython.core.plugin import PluginManager
49 50 from IPython.core.prefilter import PrefilterManager
50 from IPython.core.displayhook import DisplayHook
51 import IPython.core.hooks
52 51 from IPython.external.Itpl import ItplNS
53 52 from IPython.utils import PyColorize
53 from IPython.utils import io
54 54 from IPython.utils import pickleshare
55 55 from IPython.utils.doctestreload import doctest_reload
56 from IPython.utils.io import ask_yes_no, rprint
56 57 from IPython.utils.ipstruct import Struct
57 import IPython.utils.io
58 from IPython.utils.io import ask_yes_no
59 58 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
60 59 from IPython.utils.process import getoutput, getoutputerror
61 60 from IPython.utils.strdispatch import StrDispatch
62 61 from IPython.utils.syspathcontext import prepended_to_syspath
63 62 from IPython.utils.text import num_ini_spaces
63 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
64 List, Unicode, Instance, Type)
64 65 from IPython.utils.warn import warn, error, fatal
65 from IPython.utils.traitlets import (
66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance, Type
67 )
66 import IPython.core.hooks
68 67
69 68 # from IPython.utils import growl
70 69 # growl.start("IPython")
71 70
72 71 #-----------------------------------------------------------------------------
73 72 # Globals
74 73 #-----------------------------------------------------------------------------
75 74
76 75 # compiled regexps for autoindent management
77 76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78 77
79 78 #-----------------------------------------------------------------------------
80 79 # Utilities
81 80 #-----------------------------------------------------------------------------
82 81
83 82 # store the builtin raw_input globally, and use this always, in case user code
84 83 # overwrites it (like wx.py.PyShell does)
85 84 raw_input_original = raw_input
86 85
87 86 def softspace(file, newvalue):
88 87 """Copied from code.py, to remove the dependency"""
89 88
90 89 oldvalue = 0
91 90 try:
92 91 oldvalue = file.softspace
93 92 except AttributeError:
94 93 pass
95 94 try:
96 95 file.softspace = newvalue
97 96 except (AttributeError, TypeError):
98 97 # "attribute-less object" or "read-only attributes"
99 98 pass
100 99 return oldvalue
101 100
102 101
103 102 def no_op(*a, **kw): pass
104 103
105 104 class SpaceInInput(exceptions.Exception): pass
106 105
107 106 class Bunch: pass
108 107
109 108
110 109 def get_default_colors():
111 110 if sys.platform=='darwin':
112 111 return "LightBG"
113 112 elif os.name=='nt':
114 113 return 'Linux'
115 114 else:
116 115 return 'Linux'
117 116
118 117
119 118 class SeparateStr(Str):
120 119 """A Str subclass to validate separate_in, separate_out, etc.
121 120
122 121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
123 122 """
124 123
125 124 def validate(self, obj, value):
126 125 if value == '0': value = ''
127 126 value = value.replace('\\n','\n')
128 127 return super(SeparateStr, self).validate(obj, value)
129 128
130 129 class MultipleInstanceError(Exception):
131 130 pass
132 131
133 132
134 133 #-----------------------------------------------------------------------------
135 134 # Main IPython class
136 135 #-----------------------------------------------------------------------------
137 136
138 137
139 138 class InteractiveShell(Configurable, Magic):
140 139 """An enhanced, interactive shell for Python."""
141 140
142 141 _instance = None
143 142 autocall = Enum((0,1,2), default_value=1, config=True)
144 143 # TODO: remove all autoindent logic and put into frontends.
145 144 # We can't do this yet because even runlines uses the autoindent.
146 145 autoindent = CBool(True, config=True)
147 146 automagic = CBool(True, config=True)
148 147 cache_size = Int(1000, config=True)
149 148 color_info = CBool(True, config=True)
150 149 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 150 default_value=get_default_colors(), config=True)
152 151 debug = CBool(False, config=True)
153 152 deep_reload = CBool(False, config=True)
154 153 displayhook_class = Type(DisplayHook)
155 154 filename = Str("<ipython console>")
156 155 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
157 156 logstart = CBool(False, config=True)
158 157 logfile = Str('', config=True)
159 158 logappend = Str('', config=True)
160 159 object_info_string_level = Enum((0,1,2), default_value=0,
161 160 config=True)
162 161 pdb = CBool(False, config=True)
163 162 pprint = CBool(True, config=True)
164 163 profile = Str('', config=True)
165 164 prompt_in1 = Str('In [\\#]: ', config=True)
166 165 prompt_in2 = Str(' .\\D.: ', config=True)
167 166 prompt_out = Str('Out[\\#]: ', config=True)
168 167 prompts_pad_left = CBool(True, config=True)
169 168 quiet = CBool(False, config=True)
170 169
171 170 # The readline stuff will eventually be moved to the terminal subclass
172 171 # but for now, we can't do that as readline is welded in everywhere.
173 172 readline_use = CBool(True, config=True)
174 173 readline_merge_completions = CBool(True, config=True)
175 174 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
176 175 readline_remove_delims = Str('-/~', config=True)
177 176 readline_parse_and_bind = List([
178 177 'tab: complete',
179 178 '"\C-l": clear-screen',
180 179 'set show-all-if-ambiguous on',
181 180 '"\C-o": tab-insert',
182 181 '"\M-i": " "',
183 182 '"\M-o": "\d\d\d\d"',
184 183 '"\M-I": "\d\d\d\d"',
185 184 '"\C-r": reverse-search-history',
186 185 '"\C-s": forward-search-history',
187 186 '"\C-p": history-search-backward',
188 187 '"\C-n": history-search-forward',
189 188 '"\e[A": history-search-backward',
190 189 '"\e[B": history-search-forward',
191 190 '"\C-k": kill-line',
192 191 '"\C-u": unix-line-discard',
193 192 ], allow_none=False, config=True)
194 193
195 194 # TODO: this part of prompt management should be moved to the frontends.
196 195 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
197 196 separate_in = SeparateStr('\n', config=True)
198 197 separate_out = SeparateStr('\n', config=True)
199 198 separate_out2 = SeparateStr('\n', config=True)
200 199 system_header = Str('IPython system call: ', config=True)
201 200 system_verbose = CBool(False, config=True)
202 201 wildcards_case_sensitive = CBool(True, config=True)
203 202 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
204 203 default_value='Context', config=True)
205 204
206 205 # Subcomponents of InteractiveShell
207 206 alias_manager = Instance('IPython.core.alias.AliasManager')
208 207 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
209 208 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
210 209 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
211 210 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
212 211 plugin_manager = Instance('IPython.core.plugin.PluginManager')
213 212 payload_manager = Instance('IPython.core.payload.PayloadManager')
214 213
215 214 def __init__(self, config=None, ipython_dir=None,
216 215 user_ns=None, user_global_ns=None,
217 216 custom_exceptions=((),None)):
218 217
219 218 # This is where traits with a config_key argument are updated
220 219 # from the values on config.
221 220 super(InteractiveShell, self).__init__(config=config)
222 221
223 222 # These are relatively independent and stateless
224 223 self.init_ipython_dir(ipython_dir)
225 224 self.init_instance_attrs()
226 225
227 226 # Create namespaces (user_ns, user_global_ns, etc.)
228 227 self.init_create_namespaces(user_ns, user_global_ns)
229 228 # This has to be done after init_create_namespaces because it uses
230 229 # something in self.user_ns, but before init_sys_modules, which
231 230 # is the first thing to modify sys.
232 231 # TODO: When we override sys.stdout and sys.stderr before this class
233 232 # is created, we are saving the overridden ones here. Not sure if this
234 233 # is what we want to do.
235 234 self.save_sys_module_state()
236 235 self.init_sys_modules()
237 236
238 237 self.init_history()
239 238 self.init_encoding()
240 239 self.init_prefilter()
241 240
242 241 Magic.__init__(self, self)
243 242
244 243 self.init_syntax_highlighting()
245 244 self.init_hooks()
246 245 self.init_pushd_popd_magic()
247 246 # self.init_traceback_handlers use to be here, but we moved it below
248 247 # because it and init_io have to come after init_readline.
249 248 self.init_user_ns()
250 249 self.init_logger()
251 250 self.init_alias()
252 251 self.init_builtins()
253 252
254 253 # pre_config_initialization
255 254 self.init_shadow_hist()
256 255
257 256 # The next section should contain averything that was in ipmaker.
258 257 self.init_logstart()
259 258
260 259 # The following was in post_config_initialization
261 260 self.init_inspector()
262 261 # init_readline() must come before init_io(), because init_io uses
263 262 # readline related things.
264 263 self.init_readline()
265 264 # TODO: init_io() needs to happen before init_traceback handlers
266 265 # because the traceback handlers hardcode the stdout/stderr streams.
267 266 # This logic in in debugger.Pdb and should eventually be changed.
268 267 self.init_io()
269 268 self.init_traceback_handlers(custom_exceptions)
270 269 self.init_prompts()
271 270 self.init_displayhook()
272 271 self.init_reload_doctest()
273 272 self.init_magics()
274 273 self.init_pdb()
275 274 self.init_extension_manager()
276 275 self.init_plugin_manager()
277 276 self.init_payload()
278 277 self.hooks.late_startup_hook()
279 278
280 279 @classmethod
281 280 def instance(cls, *args, **kwargs):
282 281 """Returns a global InteractiveShell instance."""
283 282 if cls._instance is None:
284 283 inst = cls(*args, **kwargs)
285 284 # Now make sure that the instance will also be returned by
286 285 # the subclasses instance attribute.
287 286 for subclass in cls.mro():
288 287 if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell):
289 288 subclass._instance = inst
290 289 else:
291 290 break
292 291 if isinstance(cls._instance, cls):
293 292 return cls._instance
294 293 else:
295 294 raise MultipleInstanceError(
296 295 'Multiple incompatible subclass instances of '
297 296 'InteractiveShell are being created.'
298 297 )
299 298
300 299 @classmethod
301 300 def initialized(cls):
302 301 return hasattr(cls, "_instance")
303 302
304 303 def get_ipython(self):
305 304 """Return the currently running IPython instance."""
306 305 return self
307 306
308 307 #-------------------------------------------------------------------------
309 308 # Trait changed handlers
310 309 #-------------------------------------------------------------------------
311 310
312 311 def _ipython_dir_changed(self, name, new):
313 312 if not os.path.isdir(new):
314 313 os.makedirs(new, mode = 0777)
315 314
316 315 def set_autoindent(self,value=None):
317 316 """Set the autoindent flag, checking for readline support.
318 317
319 318 If called with no arguments, it acts as a toggle."""
320 319
321 320 if not self.has_readline:
322 321 if os.name == 'posix':
323 322 warn("The auto-indent feature requires the readline library")
324 323 self.autoindent = 0
325 324 return
326 325 if value is None:
327 326 self.autoindent = not self.autoindent
328 327 else:
329 328 self.autoindent = value
330 329
331 330 #-------------------------------------------------------------------------
332 331 # init_* methods called by __init__
333 332 #-------------------------------------------------------------------------
334 333
335 334 def init_ipython_dir(self, ipython_dir):
336 335 if ipython_dir is not None:
337 336 self.ipython_dir = ipython_dir
338 337 self.config.Global.ipython_dir = self.ipython_dir
339 338 return
340 339
341 340 if hasattr(self.config.Global, 'ipython_dir'):
342 341 self.ipython_dir = self.config.Global.ipython_dir
343 342 else:
344 343 self.ipython_dir = get_ipython_dir()
345 344
346 345 # All children can just read this
347 346 self.config.Global.ipython_dir = self.ipython_dir
348 347
349 348 def init_instance_attrs(self):
350 349 self.more = False
351 350
352 351 # command compiler
353 352 self.compile = codeop.CommandCompiler()
354 353
355 354 # User input buffer
356 355 self.buffer = []
357 356
358 357 # Make an empty namespace, which extension writers can rely on both
359 358 # existing and NEVER being used by ipython itself. This gives them a
360 359 # convenient location for storing additional information and state
361 360 # their extensions may require, without fear of collisions with other
362 361 # ipython names that may develop later.
363 362 self.meta = Struct()
364 363
365 364 # Object variable to store code object waiting execution. This is
366 365 # used mainly by the multithreaded shells, but it can come in handy in
367 366 # other situations. No need to use a Queue here, since it's a single
368 367 # item which gets cleared once run.
369 368 self.code_to_run = None
370 369
371 370 # Temporary files used for various purposes. Deleted at exit.
372 371 self.tempfiles = []
373 372
374 373 # Keep track of readline usage (later set by init_readline)
375 374 self.has_readline = False
376 375
377 376 # keep track of where we started running (mainly for crash post-mortem)
378 377 # This is not being used anywhere currently.
379 378 self.starting_dir = os.getcwd()
380 379
381 380 # Indentation management
382 381 self.indent_current_nsp = 0
383 382
384 383 def init_encoding(self):
385 384 # Get system encoding at startup time. Certain terminals (like Emacs
386 385 # under Win32 have it set to None, and we need to have a known valid
387 386 # encoding to use in the raw_input() method
388 387 try:
389 388 self.stdin_encoding = sys.stdin.encoding or 'ascii'
390 389 except AttributeError:
391 390 self.stdin_encoding = 'ascii'
392 391
393 392 def init_syntax_highlighting(self):
394 393 # Python source parser/formatter for syntax highlighting
395 394 pyformat = PyColorize.Parser().format
396 395 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
397 396
398 397 def init_pushd_popd_magic(self):
399 398 # for pushd/popd management
400 399 try:
401 400 self.home_dir = get_home_dir()
402 401 except HomeDirError, msg:
403 402 fatal(msg)
404 403
405 404 self.dir_stack = []
406 405
407 406 def init_logger(self):
408 407 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
409 408 # local shortcut, this is used a LOT
410 409 self.log = self.logger.log
411 410
412 411 def init_logstart(self):
413 412 if self.logappend:
414 413 self.magic_logstart(self.logappend + ' append')
415 414 elif self.logfile:
416 415 self.magic_logstart(self.logfile)
417 416 elif self.logstart:
418 417 self.magic_logstart()
419 418
420 419 def init_builtins(self):
421 420 self.builtin_trap = BuiltinTrap(shell=self)
422 421
423 422 def init_inspector(self):
424 423 # Object inspector
425 424 self.inspector = oinspect.Inspector(oinspect.InspectColors,
426 425 PyColorize.ANSICodeColors,
427 426 'NoColor',
428 427 self.object_info_string_level)
429 428
430 429 def init_io(self):
431 430 import IPython.utils.io
432 431 if sys.platform == 'win32' and self.has_readline:
433 Term = IPython.utils.io.IOTerm(
432 Term = io.IOTerm(
434 433 cout=self.readline._outputfile,cerr=self.readline._outputfile
435 434 )
436 435 else:
437 Term = IPython.utils.io.IOTerm()
438 IPython.utils.io.Term = Term
436 Term = io.IOTerm()
437 io.Term = Term
439 438
440 439 def init_prompts(self):
441 440 # TODO: This is a pass for now because the prompts are managed inside
442 441 # the DisplayHook. Once there is a separate prompt manager, this
443 442 # will initialize that object and all prompt related information.
444 443 pass
445 444
446 445 def init_displayhook(self):
447 446 # Initialize displayhook, set in/out prompts and printing system
448 447 self.displayhook = self.displayhook_class(
449 448 shell=self,
450 449 cache_size=self.cache_size,
451 450 input_sep = self.separate_in,
452 451 output_sep = self.separate_out,
453 452 output_sep2 = self.separate_out2,
454 453 ps1 = self.prompt_in1,
455 454 ps2 = self.prompt_in2,
456 455 ps_out = self.prompt_out,
457 456 pad_left = self.prompts_pad_left
458 457 )
459 458 # This is a context manager that installs/revmoes the displayhook at
460 459 # the appropriate time.
461 460 self.display_trap = DisplayTrap(hook=self.displayhook)
462 461
463 462 def init_reload_doctest(self):
464 463 # Do a proper resetting of doctest, including the necessary displayhook
465 464 # monkeypatching
466 465 try:
467 466 doctest_reload()
468 467 except ImportError:
469 468 warn("doctest module does not exist.")
470 469
471 470 #-------------------------------------------------------------------------
472 471 # Things related to injections into the sys module
473 472 #-------------------------------------------------------------------------
474 473
475 474 def save_sys_module_state(self):
476 475 """Save the state of hooks in the sys module.
477 476
478 477 This has to be called after self.user_ns is created.
479 478 """
480 479 self._orig_sys_module_state = {}
481 480 self._orig_sys_module_state['stdin'] = sys.stdin
482 481 self._orig_sys_module_state['stdout'] = sys.stdout
483 482 self._orig_sys_module_state['stderr'] = sys.stderr
484 483 self._orig_sys_module_state['excepthook'] = sys.excepthook
485 484 try:
486 485 self._orig_sys_modules_main_name = self.user_ns['__name__']
487 486 except KeyError:
488 487 pass
489 488
490 489 def restore_sys_module_state(self):
491 490 """Restore the state of the sys module."""
492 491 try:
493 492 for k, v in self._orig_sys_module_state.items():
494 493 setattr(sys, k, v)
495 494 except AttributeError:
496 495 pass
497 496 try:
498 497 delattr(sys, 'ipcompleter')
499 498 except AttributeError:
500 499 pass
501 500 # Reset what what done in self.init_sys_modules
502 501 try:
503 502 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
504 503 except (AttributeError, KeyError):
505 504 pass
506 505
507 506 #-------------------------------------------------------------------------
508 507 # Things related to hooks
509 508 #-------------------------------------------------------------------------
510 509
511 510 def init_hooks(self):
512 511 # hooks holds pointers used for user-side customizations
513 512 self.hooks = Struct()
514 513
515 514 self.strdispatchers = {}
516 515
517 516 # Set all default hooks, defined in the IPython.hooks module.
518 517 hooks = IPython.core.hooks
519 518 for hook_name in hooks.__all__:
520 519 # default hooks have priority 100, i.e. low; user hooks should have
521 520 # 0-100 priority
522 521 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
523 522
524 523 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
525 524 """set_hook(name,hook) -> sets an internal IPython hook.
526 525
527 526 IPython exposes some of its internal API as user-modifiable hooks. By
528 527 adding your function to one of these hooks, you can modify IPython's
529 528 behavior to call at runtime your own routines."""
530 529
531 530 # At some point in the future, this should validate the hook before it
532 531 # accepts it. Probably at least check that the hook takes the number
533 532 # of args it's supposed to.
534 533
535 534 f = new.instancemethod(hook,self,self.__class__)
536 535
537 536 # check if the hook is for strdispatcher first
538 537 if str_key is not None:
539 538 sdp = self.strdispatchers.get(name, StrDispatch())
540 539 sdp.add_s(str_key, f, priority )
541 540 self.strdispatchers[name] = sdp
542 541 return
543 542 if re_key is not None:
544 543 sdp = self.strdispatchers.get(name, StrDispatch())
545 544 sdp.add_re(re.compile(re_key), f, priority )
546 545 self.strdispatchers[name] = sdp
547 546 return
548 547
549 548 dp = getattr(self.hooks, name, None)
550 549 if name not in IPython.core.hooks.__all__:
551 550 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
552 551 if not dp:
553 552 dp = IPython.core.hooks.CommandChainDispatcher()
554 553
555 554 try:
556 555 dp.add(f,priority)
557 556 except AttributeError:
558 557 # it was not commandchain, plain old func - replace
559 558 dp = f
560 559
561 560 setattr(self.hooks,name, dp)
562 561
563 562 #-------------------------------------------------------------------------
564 563 # Things related to the "main" module
565 564 #-------------------------------------------------------------------------
566 565
567 566 def new_main_mod(self,ns=None):
568 567 """Return a new 'main' module object for user code execution.
569 568 """
570 569 main_mod = self._user_main_module
571 570 init_fakemod_dict(main_mod,ns)
572 571 return main_mod
573 572
574 573 def cache_main_mod(self,ns,fname):
575 574 """Cache a main module's namespace.
576 575
577 576 When scripts are executed via %run, we must keep a reference to the
578 577 namespace of their __main__ module (a FakeModule instance) around so
579 578 that Python doesn't clear it, rendering objects defined therein
580 579 useless.
581 580
582 581 This method keeps said reference in a private dict, keyed by the
583 582 absolute path of the module object (which corresponds to the script
584 583 path). This way, for multiple executions of the same script we only
585 584 keep one copy of the namespace (the last one), thus preventing memory
586 585 leaks from old references while allowing the objects from the last
587 586 execution to be accessible.
588 587
589 588 Note: we can not allow the actual FakeModule instances to be deleted,
590 589 because of how Python tears down modules (it hard-sets all their
591 590 references to None without regard for reference counts). This method
592 591 must therefore make a *copy* of the given namespace, to allow the
593 592 original module's __dict__ to be cleared and reused.
594 593
595 594
596 595 Parameters
597 596 ----------
598 597 ns : a namespace (a dict, typically)
599 598
600 599 fname : str
601 600 Filename associated with the namespace.
602 601
603 602 Examples
604 603 --------
605 604
606 605 In [10]: import IPython
607 606
608 607 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
609 608
610 609 In [12]: IPython.__file__ in _ip._main_ns_cache
611 610 Out[12]: True
612 611 """
613 612 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
614 613
615 614 def clear_main_mod_cache(self):
616 615 """Clear the cache of main modules.
617 616
618 617 Mainly for use by utilities like %reset.
619 618
620 619 Examples
621 620 --------
622 621
623 622 In [15]: import IPython
624 623
625 624 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
626 625
627 626 In [17]: len(_ip._main_ns_cache) > 0
628 627 Out[17]: True
629 628
630 629 In [18]: _ip.clear_main_mod_cache()
631 630
632 631 In [19]: len(_ip._main_ns_cache) == 0
633 632 Out[19]: True
634 633 """
635 634 self._main_ns_cache.clear()
636 635
637 636 #-------------------------------------------------------------------------
638 637 # Things related to debugging
639 638 #-------------------------------------------------------------------------
640 639
641 640 def init_pdb(self):
642 641 # Set calling of pdb on exceptions
643 642 # self.call_pdb is a property
644 643 self.call_pdb = self.pdb
645 644
646 645 def _get_call_pdb(self):
647 646 return self._call_pdb
648 647
649 648 def _set_call_pdb(self,val):
650 649
651 650 if val not in (0,1,False,True):
652 651 raise ValueError,'new call_pdb value must be boolean'
653 652
654 653 # store value in instance
655 654 self._call_pdb = val
656 655
657 656 # notify the actual exception handlers
658 657 self.InteractiveTB.call_pdb = val
659 658
660 659 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
661 660 'Control auto-activation of pdb at exceptions')
662 661
663 662 def debugger(self,force=False):
664 663 """Call the pydb/pdb debugger.
665 664
666 665 Keywords:
667 666
668 667 - force(False): by default, this routine checks the instance call_pdb
669 668 flag and does not actually invoke the debugger if the flag is false.
670 669 The 'force' option forces the debugger to activate even if the flag
671 670 is false.
672 671 """
673 672
674 673 if not (force or self.call_pdb):
675 674 return
676 675
677 676 if not hasattr(sys,'last_traceback'):
678 677 error('No traceback has been produced, nothing to debug.')
679 678 return
680 679
681 680 # use pydb if available
682 681 if debugger.has_pydb:
683 682 from pydb import pm
684 683 else:
685 684 # fallback to our internal debugger
686 685 pm = lambda : self.InteractiveTB.debugger(force=True)
687 686 self.history_saving_wrapper(pm)()
688 687
689 688 #-------------------------------------------------------------------------
690 689 # Things related to IPython's various namespaces
691 690 #-------------------------------------------------------------------------
692 691
693 692 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
694 693 # Create the namespace where the user will operate. user_ns is
695 694 # normally the only one used, and it is passed to the exec calls as
696 695 # the locals argument. But we do carry a user_global_ns namespace
697 696 # given as the exec 'globals' argument, This is useful in embedding
698 697 # situations where the ipython shell opens in a context where the
699 698 # distinction between locals and globals is meaningful. For
700 699 # non-embedded contexts, it is just the same object as the user_ns dict.
701 700
702 701 # FIXME. For some strange reason, __builtins__ is showing up at user
703 702 # level as a dict instead of a module. This is a manual fix, but I
704 703 # should really track down where the problem is coming from. Alex
705 704 # Schmolck reported this problem first.
706 705
707 706 # A useful post by Alex Martelli on this topic:
708 707 # Re: inconsistent value from __builtins__
709 708 # Von: Alex Martelli <aleaxit@yahoo.com>
710 709 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
711 710 # Gruppen: comp.lang.python
712 711
713 712 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
714 713 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
715 714 # > <type 'dict'>
716 715 # > >>> print type(__builtins__)
717 716 # > <type 'module'>
718 717 # > Is this difference in return value intentional?
719 718
720 719 # Well, it's documented that '__builtins__' can be either a dictionary
721 720 # or a module, and it's been that way for a long time. Whether it's
722 721 # intentional (or sensible), I don't know. In any case, the idea is
723 722 # that if you need to access the built-in namespace directly, you
724 723 # should start with "import __builtin__" (note, no 's') which will
725 724 # definitely give you a module. Yeah, it's somewhat confusing:-(.
726 725
727 726 # These routines return properly built dicts as needed by the rest of
728 727 # the code, and can also be used by extension writers to generate
729 728 # properly initialized namespaces.
730 729 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
731 730
732 731 # Assign namespaces
733 732 # This is the namespace where all normal user variables live
734 733 self.user_ns = user_ns
735 734 self.user_global_ns = user_global_ns
736 735
737 736 # An auxiliary namespace that checks what parts of the user_ns were
738 737 # loaded at startup, so we can list later only variables defined in
739 738 # actual interactive use. Since it is always a subset of user_ns, it
740 739 # doesn't need to be separately tracked in the ns_table.
741 740 self.user_ns_hidden = {}
742 741
743 742 # A namespace to keep track of internal data structures to prevent
744 743 # them from cluttering user-visible stuff. Will be updated later
745 744 self.internal_ns = {}
746 745
747 746 # Now that FakeModule produces a real module, we've run into a nasty
748 747 # problem: after script execution (via %run), the module where the user
749 748 # code ran is deleted. Now that this object is a true module (needed
750 749 # so docetst and other tools work correctly), the Python module
751 750 # teardown mechanism runs over it, and sets to None every variable
752 751 # present in that module. Top-level references to objects from the
753 752 # script survive, because the user_ns is updated with them. However,
754 753 # calling functions defined in the script that use other things from
755 754 # the script will fail, because the function's closure had references
756 755 # to the original objects, which are now all None. So we must protect
757 756 # these modules from deletion by keeping a cache.
758 757 #
759 758 # To avoid keeping stale modules around (we only need the one from the
760 759 # last run), we use a dict keyed with the full path to the script, so
761 760 # only the last version of the module is held in the cache. Note,
762 761 # however, that we must cache the module *namespace contents* (their
763 762 # __dict__). Because if we try to cache the actual modules, old ones
764 763 # (uncached) could be destroyed while still holding references (such as
765 764 # those held by GUI objects that tend to be long-lived)>
766 765 #
767 766 # The %reset command will flush this cache. See the cache_main_mod()
768 767 # and clear_main_mod_cache() methods for details on use.
769 768
770 769 # This is the cache used for 'main' namespaces
771 770 self._main_ns_cache = {}
772 771 # And this is the single instance of FakeModule whose __dict__ we keep
773 772 # copying and clearing for reuse on each %run
774 773 self._user_main_module = FakeModule()
775 774
776 775 # A table holding all the namespaces IPython deals with, so that
777 776 # introspection facilities can search easily.
778 777 self.ns_table = {'user':user_ns,
779 778 'user_global':user_global_ns,
780 779 'internal':self.internal_ns,
781 780 'builtin':__builtin__.__dict__
782 781 }
783 782
784 783 # Similarly, track all namespaces where references can be held and that
785 784 # we can safely clear (so it can NOT include builtin). This one can be
786 785 # a simple list.
787 786 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
788 787 self.internal_ns, self._main_ns_cache ]
789 788
790 789 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
791 790 """Return a valid local and global user interactive namespaces.
792 791
793 792 This builds a dict with the minimal information needed to operate as a
794 793 valid IPython user namespace, which you can pass to the various
795 794 embedding classes in ipython. The default implementation returns the
796 795 same dict for both the locals and the globals to allow functions to
797 796 refer to variables in the namespace. Customized implementations can
798 797 return different dicts. The locals dictionary can actually be anything
799 798 following the basic mapping protocol of a dict, but the globals dict
800 799 must be a true dict, not even a subclass. It is recommended that any
801 800 custom object for the locals namespace synchronize with the globals
802 801 dict somehow.
803 802
804 803 Raises TypeError if the provided globals namespace is not a true dict.
805 804
806 805 Parameters
807 806 ----------
808 807 user_ns : dict-like, optional
809 808 The current user namespace. The items in this namespace should
810 809 be included in the output. If None, an appropriate blank
811 810 namespace should be created.
812 811 user_global_ns : dict, optional
813 812 The current user global namespace. The items in this namespace
814 813 should be included in the output. If None, an appropriate
815 814 blank namespace should be created.
816 815
817 816 Returns
818 817 -------
819 818 A pair of dictionary-like object to be used as the local namespace
820 819 of the interpreter and a dict to be used as the global namespace.
821 820 """
822 821
823 822
824 823 # We must ensure that __builtin__ (without the final 's') is always
825 824 # available and pointing to the __builtin__ *module*. For more details:
826 825 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
827 826
828 827 if user_ns is None:
829 828 # Set __name__ to __main__ to better match the behavior of the
830 829 # normal interpreter.
831 830 user_ns = {'__name__' :'__main__',
832 831 '__builtin__' : __builtin__,
833 832 '__builtins__' : __builtin__,
834 833 }
835 834 else:
836 835 user_ns.setdefault('__name__','__main__')
837 836 user_ns.setdefault('__builtin__',__builtin__)
838 837 user_ns.setdefault('__builtins__',__builtin__)
839 838
840 839 if user_global_ns is None:
841 840 user_global_ns = user_ns
842 841 if type(user_global_ns) is not dict:
843 842 raise TypeError("user_global_ns must be a true dict; got %r"
844 843 % type(user_global_ns))
845 844
846 845 return user_ns, user_global_ns
847 846
848 847 def init_sys_modules(self):
849 848 # We need to insert into sys.modules something that looks like a
850 849 # module but which accesses the IPython namespace, for shelve and
851 850 # pickle to work interactively. Normally they rely on getting
852 851 # everything out of __main__, but for embedding purposes each IPython
853 852 # instance has its own private namespace, so we can't go shoving
854 853 # everything into __main__.
855 854
856 855 # note, however, that we should only do this for non-embedded
857 856 # ipythons, which really mimic the __main__.__dict__ with their own
858 857 # namespace. Embedded instances, on the other hand, should not do
859 858 # this because they need to manage the user local/global namespaces
860 859 # only, but they live within a 'normal' __main__ (meaning, they
861 860 # shouldn't overtake the execution environment of the script they're
862 861 # embedded in).
863 862
864 863 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
865 864
866 865 try:
867 866 main_name = self.user_ns['__name__']
868 867 except KeyError:
869 868 raise KeyError('user_ns dictionary MUST have a "__name__" key')
870 869 else:
871 870 sys.modules[main_name] = FakeModule(self.user_ns)
872 871
873 872 def init_user_ns(self):
874 873 """Initialize all user-visible namespaces to their minimum defaults.
875 874
876 875 Certain history lists are also initialized here, as they effectively
877 876 act as user namespaces.
878 877
879 878 Notes
880 879 -----
881 880 All data structures here are only filled in, they are NOT reset by this
882 881 method. If they were not empty before, data will simply be added to
883 882 therm.
884 883 """
885 884 # This function works in two parts: first we put a few things in
886 885 # user_ns, and we sync that contents into user_ns_hidden so that these
887 886 # initial variables aren't shown by %who. After the sync, we add the
888 887 # rest of what we *do* want the user to see with %who even on a new
889 888 # session (probably nothing, so theye really only see their own stuff)
890 889
891 890 # The user dict must *always* have a __builtin__ reference to the
892 891 # Python standard __builtin__ namespace, which must be imported.
893 892 # This is so that certain operations in prompt evaluation can be
894 893 # reliably executed with builtins. Note that we can NOT use
895 894 # __builtins__ (note the 's'), because that can either be a dict or a
896 895 # module, and can even mutate at runtime, depending on the context
897 896 # (Python makes no guarantees on it). In contrast, __builtin__ is
898 897 # always a module object, though it must be explicitly imported.
899 898
900 899 # For more details:
901 900 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
902 901 ns = dict(__builtin__ = __builtin__)
903 902
904 903 # Put 'help' in the user namespace
905 904 try:
906 905 from site import _Helper
907 906 ns['help'] = _Helper()
908 907 except ImportError:
909 908 warn('help() not available - check site.py')
910 909
911 910 # make global variables for user access to the histories
912 911 ns['_ih'] = self.input_hist
913 912 ns['_oh'] = self.output_hist
914 913 ns['_dh'] = self.dir_hist
915 914
916 915 ns['_sh'] = shadowns
917 916
918 917 # user aliases to input and output histories. These shouldn't show up
919 918 # in %who, as they can have very large reprs.
920 919 ns['In'] = self.input_hist
921 920 ns['Out'] = self.output_hist
922 921
923 922 # Store myself as the public api!!!
924 923 ns['get_ipython'] = self.get_ipython
925 924
926 925 # Sync what we've added so far to user_ns_hidden so these aren't seen
927 926 # by %who
928 927 self.user_ns_hidden.update(ns)
929 928
930 929 # Anything put into ns now would show up in %who. Think twice before
931 930 # putting anything here, as we really want %who to show the user their
932 931 # stuff, not our variables.
933 932
934 933 # Finally, update the real user's namespace
935 934 self.user_ns.update(ns)
936 935
937 936
938 937 def reset(self):
939 938 """Clear all internal namespaces.
940 939
941 940 Note that this is much more aggressive than %reset, since it clears
942 941 fully all namespaces, as well as all input/output lists.
943 942 """
944 943 for ns in self.ns_refs_table:
945 944 ns.clear()
946 945
947 946 self.alias_manager.clear_aliases()
948 947
949 948 # Clear input and output histories
950 949 self.input_hist[:] = []
951 950 self.input_hist_raw[:] = []
952 951 self.output_hist.clear()
953 952
954 953 # Restore the user namespaces to minimal usability
955 954 self.init_user_ns()
956 955
957 956 # Restore the default and user aliases
958 957 self.alias_manager.init_aliases()
959 958
960 959 def reset_selective(self, regex=None):
961 960 """Clear selective variables from internal namespaces based on a specified regular expression.
962 961
963 962 Parameters
964 963 ----------
965 964 regex : string or compiled pattern, optional
966 965 A regular expression pattern that will be used in searching variable names in the users
967 966 namespaces.
968 967 """
969 968 if regex is not None:
970 969 try:
971 970 m = re.compile(regex)
972 971 except TypeError:
973 972 raise TypeError('regex must be a string or compiled pattern')
974 973 # Search for keys in each namespace that match the given regex
975 974 # If a match is found, delete the key/value pair.
976 975 for ns in self.ns_refs_table:
977 976 for var in ns:
978 977 if m.search(var):
979 978 del ns[var]
980 979
981 980 def push(self, variables, interactive=True):
982 981 """Inject a group of variables into the IPython user namespace.
983 982
984 983 Parameters
985 984 ----------
986 985 variables : dict, str or list/tuple of str
987 986 The variables to inject into the user's namespace. If a dict,
988 987 a simple update is done. If a str, the string is assumed to
989 988 have variable names separated by spaces. A list/tuple of str
990 989 can also be used to give the variable names. If just the variable
991 990 names are give (list/tuple/str) then the variable values looked
992 991 up in the callers frame.
993 992 interactive : bool
994 993 If True (default), the variables will be listed with the ``who``
995 994 magic.
996 995 """
997 996 vdict = None
998 997
999 998 # We need a dict of name/value pairs to do namespace updates.
1000 999 if isinstance(variables, dict):
1001 1000 vdict = variables
1002 1001 elif isinstance(variables, (basestring, list, tuple)):
1003 1002 if isinstance(variables, basestring):
1004 1003 vlist = variables.split()
1005 1004 else:
1006 1005 vlist = variables
1007 1006 vdict = {}
1008 1007 cf = sys._getframe(1)
1009 1008 for name in vlist:
1010 1009 try:
1011 1010 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1012 1011 except:
1013 1012 print ('Could not get variable %s from %s' %
1014 1013 (name,cf.f_code.co_name))
1015 1014 else:
1016 1015 raise ValueError('variables must be a dict/str/list/tuple')
1017 1016
1018 1017 # Propagate variables to user namespace
1019 1018 self.user_ns.update(vdict)
1020 1019
1021 1020 # And configure interactive visibility
1022 1021 config_ns = self.user_ns_hidden
1023 1022 if interactive:
1024 1023 for name, val in vdict.iteritems():
1025 1024 config_ns.pop(name, None)
1026 1025 else:
1027 1026 for name,val in vdict.iteritems():
1028 1027 config_ns[name] = val
1029 1028
1030 1029 #-------------------------------------------------------------------------
1031 1030 # Things related to history management
1032 1031 #-------------------------------------------------------------------------
1033 1032
1034 1033 def init_history(self):
1035 1034 # List of input with multi-line handling.
1036 1035 self.input_hist = InputList()
1037 1036 # This one will hold the 'raw' input history, without any
1038 1037 # pre-processing. This will allow users to retrieve the input just as
1039 1038 # it was exactly typed in by the user, with %hist -r.
1040 1039 self.input_hist_raw = InputList()
1041 1040
1042 1041 # list of visited directories
1043 1042 try:
1044 1043 self.dir_hist = [os.getcwd()]
1045 1044 except OSError:
1046 1045 self.dir_hist = []
1047 1046
1048 1047 # dict of output history
1049 1048 self.output_hist = {}
1050 1049
1051 1050 # Now the history file
1052 1051 if self.profile:
1053 1052 histfname = 'history-%s' % self.profile
1054 1053 else:
1055 1054 histfname = 'history'
1056 1055 self.histfile = os.path.join(self.ipython_dir, histfname)
1057 1056
1058 1057 # Fill the history zero entry, user counter starts at 1
1059 1058 self.input_hist.append('\n')
1060 1059 self.input_hist_raw.append('\n')
1061 1060
1062 1061 def init_shadow_hist(self):
1063 1062 try:
1064 1063 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1065 1064 except exceptions.UnicodeDecodeError:
1066 1065 print "Your ipython_dir can't be decoded to unicode!"
1067 1066 print "Please set HOME environment variable to something that"
1068 1067 print r"only has ASCII characters, e.g. c:\home"
1069 1068 print "Now it is", self.ipython_dir
1070 1069 sys.exit()
1071 1070 self.shadowhist = ipcorehist.ShadowHist(self.db)
1072 1071
1073 1072 def savehist(self):
1074 1073 """Save input history to a file (via readline library)."""
1075 1074
1076 1075 try:
1077 1076 self.readline.write_history_file(self.histfile)
1078 1077 except:
1079 1078 print 'Unable to save IPython command history to file: ' + \
1080 1079 `self.histfile`
1081 1080
1082 1081 def reloadhist(self):
1083 1082 """Reload the input history from disk file."""
1084 1083
1085 1084 try:
1086 1085 self.readline.clear_history()
1087 1086 self.readline.read_history_file(self.shell.histfile)
1088 1087 except AttributeError:
1089 1088 pass
1090 1089
1091 1090 def history_saving_wrapper(self, func):
1092 1091 """ Wrap func for readline history saving
1093 1092
1094 1093 Convert func into callable that saves & restores
1095 1094 history around the call """
1096 1095
1097 1096 if self.has_readline:
1098 1097 from IPython.utils import rlineimpl as readline
1099 1098 else:
1100 1099 return func
1101 1100
1102 1101 def wrapper():
1103 1102 self.savehist()
1104 1103 try:
1105 1104 func()
1106 1105 finally:
1107 1106 readline.read_history_file(self.histfile)
1108 1107 return wrapper
1109 1108
1110 1109 def get_history(self, index=None, raw=False, output=True):
1111 1110 """Get the history list.
1112 1111
1113 1112 Get the input and output history.
1114 1113
1115 1114 Parameters
1116 1115 ----------
1117 1116 index : n or (n1, n2) or None
1118 1117 If n, then the last entries. If a tuple, then all in
1119 1118 range(n1, n2). If None, then all entries. Raises IndexError if
1120 1119 the format of index is incorrect.
1121 1120 raw : bool
1122 1121 If True, return the raw input.
1123 1122 output : bool
1124 1123 If True, then return the output as well.
1125 1124
1126 1125 Returns
1127 1126 -------
1128 1127 If output is True, then return a dict of tuples, keyed by the prompt
1129 1128 numbers and with values of (input, output). If output is False, then
1130 1129 a dict, keyed by the prompt number with the values of input. Raises
1131 1130 IndexError if no history is found.
1132 1131 """
1133 1132 if raw:
1134 1133 input_hist = self.input_hist_raw
1135 1134 else:
1136 1135 input_hist = self.input_hist
1137 1136 if output:
1138 1137 output_hist = self.user_ns['Out']
1139 1138 n = len(input_hist)
1140 1139 if index is None:
1141 1140 start=0; stop=n
1142 1141 elif isinstance(index, int):
1143 1142 start=n-index; stop=n
1144 1143 elif isinstance(index, tuple) and len(index) == 2:
1145 1144 start=index[0]; stop=index[1]
1146 1145 else:
1147 1146 raise IndexError('Not a valid index for the input history: %r' % index)
1148 1147 hist = {}
1149 1148 for i in range(start, stop):
1150 1149 if output:
1151 1150 hist[i] = (input_hist[i], output_hist.get(i))
1152 1151 else:
1153 1152 hist[i] = input_hist[i]
1154 1153 if len(hist)==0:
1155 1154 raise IndexError('No history for range of indices: %r' % index)
1156 1155 return hist
1157 1156
1158 1157 #-------------------------------------------------------------------------
1159 1158 # Things related to exception handling and tracebacks (not debugging)
1160 1159 #-------------------------------------------------------------------------
1161 1160
1162 1161 def init_traceback_handlers(self, custom_exceptions):
1163 1162 # Syntax error handler.
1164 1163 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1165 1164
1166 1165 # The interactive one is initialized with an offset, meaning we always
1167 1166 # want to remove the topmost item in the traceback, which is our own
1168 1167 # internal code. Valid modes: ['Plain','Context','Verbose']
1169 1168 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1170 1169 color_scheme='NoColor',
1171 1170 tb_offset = 1)
1172 1171
1173 1172 # The instance will store a pointer to the system-wide exception hook,
1174 1173 # so that runtime code (such as magics) can access it. This is because
1175 1174 # during the read-eval loop, it may get temporarily overwritten.
1176 1175 self.sys_excepthook = sys.excepthook
1177 1176
1178 1177 # and add any custom exception handlers the user may have specified
1179 1178 self.set_custom_exc(*custom_exceptions)
1180 1179
1181 1180 # Set the exception mode
1182 1181 self.InteractiveTB.set_mode(mode=self.xmode)
1183 1182
1184 def set_custom_exc(self,exc_tuple,handler):
1183 def set_custom_exc(self, exc_tuple, handler):
1185 1184 """set_custom_exc(exc_tuple,handler)
1186 1185
1187 1186 Set a custom exception handler, which will be called if any of the
1188 1187 exceptions in exc_tuple occur in the mainloop (specifically, in the
1189 1188 runcode() method.
1190 1189
1191 1190 Inputs:
1192 1191
1193 1192 - exc_tuple: a *tuple* of valid exceptions to call the defined
1194 1193 handler for. It is very important that you use a tuple, and NOT A
1195 1194 LIST here, because of the way Python's except statement works. If
1196 1195 you only want to trap a single exception, use a singleton tuple:
1197 1196
1198 1197 exc_tuple == (MyCustomException,)
1199 1198
1200 1199 - handler: this must be defined as a function with the following
1201 basic interface: def my_handler(self,etype,value,tb).
1200 basic interface::
1201
1202 def my_handler(self, etype, value, tb, tb_offset=None)
1203 ...
1204 # The return value must be
1205 return structured_traceback
1202 1206
1203 1207 This will be made into an instance method (via new.instancemethod)
1204 1208 of IPython itself, and it will be called if any of the exceptions
1205 1209 listed in the exc_tuple are caught. If the handler is None, an
1206 1210 internal basic one is used, which just prints basic info.
1207 1211
1208 1212 WARNING: by putting in your own exception handler into IPython's main
1209 1213 execution loop, you run a very good chance of nasty crashes. This
1210 1214 facility should only be used if you really know what you are doing."""
1211 1215
1212 1216 assert type(exc_tuple)==type(()) , \
1213 1217 "The custom exceptions must be given AS A TUPLE."
1214 1218
1215 1219 def dummy_handler(self,etype,value,tb):
1216 1220 print '*** Simple custom exception handler ***'
1217 1221 print 'Exception type :',etype
1218 1222 print 'Exception value:',value
1219 1223 print 'Traceback :',tb
1220 1224 print 'Source code :','\n'.join(self.buffer)
1221 1225
1222 1226 if handler is None: handler = dummy_handler
1223 1227
1224 1228 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1225 1229 self.custom_exceptions = exc_tuple
1226 1230
1227 1231 def excepthook(self, etype, value, tb):
1228 1232 """One more defense for GUI apps that call sys.excepthook.
1229 1233
1230 1234 GUI frameworks like wxPython trap exceptions and call
1231 1235 sys.excepthook themselves. I guess this is a feature that
1232 1236 enables them to keep running after exceptions that would
1233 1237 otherwise kill their mainloop. This is a bother for IPython
1234 1238 which excepts to catch all of the program exceptions with a try:
1235 1239 except: statement.
1236 1240
1237 1241 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1238 1242 any app directly invokes sys.excepthook, it will look to the user like
1239 1243 IPython crashed. In order to work around this, we can disable the
1240 1244 CrashHandler and replace it with this excepthook instead, which prints a
1241 1245 regular traceback using our InteractiveTB. In this fashion, apps which
1242 1246 call sys.excepthook will generate a regular-looking exception from
1243 1247 IPython, and the CrashHandler will only be triggered by real IPython
1244 1248 crashes.
1245 1249
1246 1250 This hook should be used sparingly, only in places which are not likely
1247 1251 to be true IPython errors.
1248 1252 """
1249 1253 self.showtraceback((etype,value,tb),tb_offset=0)
1250 1254
1251 1255 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1252 1256 exception_only=False):
1253 1257 """Display the exception that just occurred.
1254 1258
1255 1259 If nothing is known about the exception, this is the method which
1256 1260 should be used throughout the code for presenting user tracebacks,
1257 1261 rather than directly invoking the InteractiveTB object.
1258 1262
1259 1263 A specific showsyntaxerror() also exists, but this method can take
1260 1264 care of calling it if needed, so unless you are explicitly catching a
1261 1265 SyntaxError exception, don't try to analyze the stack manually and
1262 1266 simply call this method."""
1263 1267
1264 1268 try:
1265 1269 if exc_tuple is None:
1266 1270 etype, value, tb = sys.exc_info()
1267 1271 else:
1268 1272 etype, value, tb = exc_tuple
1269 1273
1270 1274 if etype is None:
1271 1275 if hasattr(sys, 'last_type'):
1272 1276 etype, value, tb = sys.last_type, sys.last_value, \
1273 1277 sys.last_traceback
1274 1278 else:
1275 self.write('No traceback available to show.\n')
1279 self.write_err('No traceback available to show.\n')
1276 1280 return
1277 1281
1278 1282 if etype is SyntaxError:
1279 1283 # Though this won't be called by syntax errors in the input
1280 1284 # line, there may be SyntaxError cases whith imported code.
1281 1285 self.showsyntaxerror(filename)
1282 1286 elif etype is UsageError:
1283 1287 print "UsageError:", value
1284 1288 else:
1285 1289 # WARNING: these variables are somewhat deprecated and not
1286 1290 # necessarily safe to use in a threaded environment, but tools
1287 1291 # like pdb depend on their existence, so let's set them. If we
1288 1292 # find problems in the field, we'll need to revisit their use.
1289 1293 sys.last_type = etype
1290 1294 sys.last_value = value
1291 1295 sys.last_traceback = tb
1292 1296
1293 1297 if etype in self.custom_exceptions:
1294 self.CustomTB(etype,value,tb)
1298 # FIXME: Old custom traceback objects may just return a
1299 # string, in that case we just put it into a list
1300 stb = self.CustomTB(etype, value, tb, tb_offset)
1301 if isinstance(ctb, basestring):
1302 stb = [stb]
1295 1303 else:
1296 1304 if exception_only:
1297 m = ('An exception has occurred, use %tb to see the '
1298 'full traceback.')
1299 print m
1300 self.InteractiveTB.show_exception_only(etype, value)
1305 stb = ['An exception has occurred, use %tb to see '
1306 'the full traceback.']
1307 stb.extend(self.InteractiveTB.get_exception_only(etype,
1308 value))
1301 1309 else:
1302 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1310 stb = self.InteractiveTB.structured_traceback(etype,
1311 value, tb, tb_offset=tb_offset)
1312 # FIXME: the pdb calling should be done by us, not by
1313 # the code computing the traceback.
1303 1314 if self.InteractiveTB.call_pdb:
1304 1315 # pdb mucks up readline, fix it back
1305 1316 self.set_completer()
1306
1317
1318 # Actually show the traceback
1319 self._showtraceback(etype, value, stb)
1320
1307 1321 except KeyboardInterrupt:
1308 self.write("\nKeyboardInterrupt\n")
1309
1322 self.write_err("\nKeyboardInterrupt\n")
1323
1324 def _showtraceback(self, etype, evalue, stb):
1325 """Actually show a traceback.
1326
1327 Subclasses may override this method to put the traceback on a different
1328 place, like a side channel.
1329 """
1330 self.write_err('\n'.join(stb))
1310 1331
1311 1332 def showsyntaxerror(self, filename=None):
1312 1333 """Display the syntax error that just occurred.
1313 1334
1314 1335 This doesn't display a stack trace because there isn't one.
1315 1336
1316 1337 If a filename is given, it is stuffed in the exception instead
1317 1338 of what was there before (because Python's parser always uses
1318 1339 "<string>" when reading from a string).
1319 1340 """
1320 1341 etype, value, last_traceback = sys.exc_info()
1321 1342
1322 1343 # See note about these variables in showtraceback() above
1323 1344 sys.last_type = etype
1324 1345 sys.last_value = value
1325 1346 sys.last_traceback = last_traceback
1326 1347
1327 1348 if filename and etype is SyntaxError:
1328 1349 # Work hard to stuff the correct filename in the exception
1329 1350 try:
1330 1351 msg, (dummy_filename, lineno, offset, line) = value
1331 1352 except:
1332 1353 # Not the format we expect; leave it alone
1333 1354 pass
1334 1355 else:
1335 1356 # Stuff in the right filename
1336 1357 try:
1337 1358 # Assume SyntaxError is a class exception
1338 1359 value = SyntaxError(msg, (filename, lineno, offset, line))
1339 1360 except:
1340 1361 # If that failed, assume SyntaxError is a string
1341 1362 value = msg, (filename, lineno, offset, line)
1342 self.SyntaxTB(etype,value,[])
1363 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1364 self._showtraceback(etype, value, stb)
1343 1365
1344 1366 #-------------------------------------------------------------------------
1345 1367 # Things related to tab completion
1346 1368 #-------------------------------------------------------------------------
1347 1369
1348 1370 def complete(self, text):
1349 1371 """Return a sorted list of all possible completions on text.
1350 1372
1351 1373 Inputs:
1352 1374
1353 1375 - text: a string of text to be completed on.
1354 1376
1355 1377 This is a wrapper around the completion mechanism, similar to what
1356 1378 readline does at the command line when the TAB key is hit. By
1357 1379 exposing it as a method, it can be used by other non-readline
1358 1380 environments (such as GUIs) for text completion.
1359 1381
1360 1382 Simple usage example:
1361 1383
1362 1384 In [7]: x = 'hello'
1363 1385
1364 1386 In [8]: x
1365 1387 Out[8]: 'hello'
1366 1388
1367 1389 In [9]: print x
1368 1390 hello
1369 1391
1370 1392 In [10]: _ip.complete('x.l')
1371 1393 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1372 1394 """
1373 1395
1374 1396 # Inject names into __builtin__ so we can complete on the added names.
1375 1397 with self.builtin_trap:
1376 1398 complete = self.Completer.complete
1377 1399 state = 0
1378 1400 # use a dict so we get unique keys, since ipyhton's multiple
1379 1401 # completers can return duplicates. When we make 2.4 a requirement,
1380 1402 # start using sets instead, which are faster.
1381 1403 comps = {}
1382 1404 while True:
1383 1405 newcomp = complete(text,state,line_buffer=text)
1384 1406 if newcomp is None:
1385 1407 break
1386 1408 comps[newcomp] = 1
1387 1409 state += 1
1388 1410 outcomps = comps.keys()
1389 1411 outcomps.sort()
1390 1412 #print "T:",text,"OC:",outcomps # dbg
1391 1413 #print "vars:",self.user_ns.keys()
1392 1414 return outcomps
1393 1415
1394 1416 def set_custom_completer(self,completer,pos=0):
1395 1417 """Adds a new custom completer function.
1396 1418
1397 1419 The position argument (defaults to 0) is the index in the completers
1398 1420 list where you want the completer to be inserted."""
1399 1421
1400 1422 newcomp = new.instancemethod(completer,self.Completer,
1401 1423 self.Completer.__class__)
1402 1424 self.Completer.matchers.insert(pos,newcomp)
1403 1425
1404 1426 def set_completer(self):
1405 1427 """Reset readline's completer to be our own."""
1406 1428 self.readline.set_completer(self.Completer.complete)
1407 1429
1408 1430 def set_completer_frame(self, frame=None):
1409 1431 """Set the frame of the completer."""
1410 1432 if frame:
1411 1433 self.Completer.namespace = frame.f_locals
1412 1434 self.Completer.global_namespace = frame.f_globals
1413 1435 else:
1414 1436 self.Completer.namespace = self.user_ns
1415 1437 self.Completer.global_namespace = self.user_global_ns
1416 1438
1417 1439 #-------------------------------------------------------------------------
1418 1440 # Things related to readline
1419 1441 #-------------------------------------------------------------------------
1420 1442
1421 1443 def init_readline(self):
1422 1444 """Command history completion/saving/reloading."""
1423 1445
1424 1446 if self.readline_use:
1425 1447 import IPython.utils.rlineimpl as readline
1426 1448
1427 1449 self.rl_next_input = None
1428 1450 self.rl_do_indent = False
1429 1451
1430 1452 if not self.readline_use or not readline.have_readline:
1431 1453 self.has_readline = False
1432 1454 self.readline = None
1433 1455 # Set a number of methods that depend on readline to be no-op
1434 1456 self.savehist = no_op
1435 1457 self.reloadhist = no_op
1436 1458 self.set_completer = no_op
1437 1459 self.set_custom_completer = no_op
1438 1460 self.set_completer_frame = no_op
1439 1461 warn('Readline services not available or not loaded.')
1440 1462 else:
1441 1463 self.has_readline = True
1442 1464 self.readline = readline
1443 1465 sys.modules['readline'] = readline
1444 1466 import atexit
1445 1467 from IPython.core.completer import IPCompleter
1446 1468 self.Completer = IPCompleter(self,
1447 1469 self.user_ns,
1448 1470 self.user_global_ns,
1449 1471 self.readline_omit__names,
1450 1472 self.alias_manager.alias_table)
1451 1473 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1452 1474 self.strdispatchers['complete_command'] = sdisp
1453 1475 self.Completer.custom_completers = sdisp
1454 1476 # Platform-specific configuration
1455 1477 if os.name == 'nt':
1456 1478 self.readline_startup_hook = readline.set_pre_input_hook
1457 1479 else:
1458 1480 self.readline_startup_hook = readline.set_startup_hook
1459 1481
1460 1482 # Load user's initrc file (readline config)
1461 1483 # Or if libedit is used, load editrc.
1462 1484 inputrc_name = os.environ.get('INPUTRC')
1463 1485 if inputrc_name is None:
1464 1486 home_dir = get_home_dir()
1465 1487 if home_dir is not None:
1466 1488 inputrc_name = '.inputrc'
1467 1489 if readline.uses_libedit:
1468 1490 inputrc_name = '.editrc'
1469 1491 inputrc_name = os.path.join(home_dir, inputrc_name)
1470 1492 if os.path.isfile(inputrc_name):
1471 1493 try:
1472 1494 readline.read_init_file(inputrc_name)
1473 1495 except:
1474 1496 warn('Problems reading readline initialization file <%s>'
1475 1497 % inputrc_name)
1476 1498
1477 1499 # save this in sys so embedded copies can restore it properly
1478 1500 sys.ipcompleter = self.Completer.complete
1479 1501 self.set_completer()
1480 1502
1481 1503 # Configure readline according to user's prefs
1482 1504 # This is only done if GNU readline is being used. If libedit
1483 1505 # is being used (as on Leopard) the readline config is
1484 1506 # not run as the syntax for libedit is different.
1485 1507 if not readline.uses_libedit:
1486 1508 for rlcommand in self.readline_parse_and_bind:
1487 1509 #print "loading rl:",rlcommand # dbg
1488 1510 readline.parse_and_bind(rlcommand)
1489 1511
1490 1512 # Remove some chars from the delimiters list. If we encounter
1491 1513 # unicode chars, discard them.
1492 1514 delims = readline.get_completer_delims().encode("ascii", "ignore")
1493 1515 delims = delims.translate(string._idmap,
1494 1516 self.readline_remove_delims)
1495 1517 readline.set_completer_delims(delims)
1496 1518 # otherwise we end up with a monster history after a while:
1497 1519 readline.set_history_length(1000)
1498 1520 try:
1499 1521 #print '*** Reading readline history' # dbg
1500 1522 readline.read_history_file(self.histfile)
1501 1523 except IOError:
1502 1524 pass # It doesn't exist yet.
1503 1525
1504 1526 atexit.register(self.atexit_operations)
1505 1527 del atexit
1506 1528
1507 1529 # Configure auto-indent for all platforms
1508 1530 self.set_autoindent(self.autoindent)
1509 1531
1510 1532 def set_next_input(self, s):
1511 1533 """ Sets the 'default' input string for the next command line.
1512 1534
1513 1535 Requires readline.
1514 1536
1515 1537 Example:
1516 1538
1517 1539 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1518 1540 [D:\ipython]|2> Hello Word_ # cursor is here
1519 1541 """
1520 1542
1521 1543 self.rl_next_input = s
1522 1544
1523 1545 # Maybe move this to the terminal subclass?
1524 1546 def pre_readline(self):
1525 1547 """readline hook to be used at the start of each line.
1526 1548
1527 1549 Currently it handles auto-indent only."""
1528 1550
1529 1551 if self.rl_do_indent:
1530 1552 self.readline.insert_text(self._indent_current_str())
1531 1553 if self.rl_next_input is not None:
1532 1554 self.readline.insert_text(self.rl_next_input)
1533 1555 self.rl_next_input = None
1534 1556
1535 1557 def _indent_current_str(self):
1536 1558 """return the current level of indentation as a string"""
1537 1559 return self.indent_current_nsp * ' '
1538 1560
1539 1561 #-------------------------------------------------------------------------
1540 1562 # Things related to magics
1541 1563 #-------------------------------------------------------------------------
1542 1564
1543 1565 def init_magics(self):
1544 1566 # FIXME: Move the color initialization to the DisplayHook, which
1545 1567 # should be split into a prompt manager and displayhook. We probably
1546 1568 # even need a centralize colors management object.
1547 1569 self.magic_colors(self.colors)
1548 1570 # History was moved to a separate module
1549 1571 from . import history
1550 1572 history.init_ipython(self)
1551 1573
1552 1574 def magic(self,arg_s):
1553 1575 """Call a magic function by name.
1554 1576
1555 1577 Input: a string containing the name of the magic function to call and any
1556 1578 additional arguments to be passed to the magic.
1557 1579
1558 1580 magic('name -opt foo bar') is equivalent to typing at the ipython
1559 1581 prompt:
1560 1582
1561 1583 In[1]: %name -opt foo bar
1562 1584
1563 1585 To call a magic without arguments, simply use magic('name').
1564 1586
1565 1587 This provides a proper Python function to call IPython's magics in any
1566 1588 valid Python code you can type at the interpreter, including loops and
1567 1589 compound statements.
1568 1590 """
1569 1591 args = arg_s.split(' ',1)
1570 1592 magic_name = args[0]
1571 1593 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1572 1594
1573 1595 try:
1574 1596 magic_args = args[1]
1575 1597 except IndexError:
1576 1598 magic_args = ''
1577 1599 fn = getattr(self,'magic_'+magic_name,None)
1578 1600 if fn is None:
1579 1601 error("Magic function `%s` not found." % magic_name)
1580 1602 else:
1581 1603 magic_args = self.var_expand(magic_args,1)
1582 1604 with nested(self.builtin_trap,):
1583 1605 result = fn(magic_args)
1584 1606 return result
1585 1607
1586 1608 def define_magic(self, magicname, func):
1587 1609 """Expose own function as magic function for ipython
1588 1610
1589 1611 def foo_impl(self,parameter_s=''):
1590 1612 'My very own magic!. (Use docstrings, IPython reads them).'
1591 1613 print 'Magic function. Passed parameter is between < >:'
1592 1614 print '<%s>' % parameter_s
1593 1615 print 'The self object is:',self
1594 1616
1595 1617 self.define_magic('foo',foo_impl)
1596 1618 """
1597 1619
1598 1620 import new
1599 1621 im = new.instancemethod(func,self, self.__class__)
1600 1622 old = getattr(self, "magic_" + magicname, None)
1601 1623 setattr(self, "magic_" + magicname, im)
1602 1624 return old
1603 1625
1604 1626 #-------------------------------------------------------------------------
1605 1627 # Things related to macros
1606 1628 #-------------------------------------------------------------------------
1607 1629
1608 1630 def define_macro(self, name, themacro):
1609 1631 """Define a new macro
1610 1632
1611 1633 Parameters
1612 1634 ----------
1613 1635 name : str
1614 1636 The name of the macro.
1615 1637 themacro : str or Macro
1616 1638 The action to do upon invoking the macro. If a string, a new
1617 1639 Macro object is created by passing the string to it.
1618 1640 """
1619 1641
1620 1642 from IPython.core import macro
1621 1643
1622 1644 if isinstance(themacro, basestring):
1623 1645 themacro = macro.Macro(themacro)
1624 1646 if not isinstance(themacro, macro.Macro):
1625 1647 raise ValueError('A macro must be a string or a Macro instance.')
1626 1648 self.user_ns[name] = themacro
1627 1649
1628 1650 #-------------------------------------------------------------------------
1629 1651 # Things related to the running of system commands
1630 1652 #-------------------------------------------------------------------------
1631 1653
1632 1654 def system(self, cmd):
1633 1655 """Make a system call, using IPython."""
1634 1656 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1635 1657
1636 1658 #-------------------------------------------------------------------------
1637 1659 # Things related to aliases
1638 1660 #-------------------------------------------------------------------------
1639 1661
1640 1662 def init_alias(self):
1641 1663 self.alias_manager = AliasManager(shell=self, config=self.config)
1642 1664 self.ns_table['alias'] = self.alias_manager.alias_table,
1643 1665
1644 1666 #-------------------------------------------------------------------------
1645 1667 # Things related to extensions and plugins
1646 1668 #-------------------------------------------------------------------------
1647 1669
1648 1670 def init_extension_manager(self):
1649 1671 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1650 1672
1651 1673 def init_plugin_manager(self):
1652 1674 self.plugin_manager = PluginManager(config=self.config)
1653 1675
1654 1676 #-------------------------------------------------------------------------
1655 1677 # Things related to payloads
1656 1678 #-------------------------------------------------------------------------
1657 1679
1658 1680 def init_payload(self):
1659 1681 self.payload_manager = PayloadManager(config=self.config)
1660 1682
1661 1683 #-------------------------------------------------------------------------
1662 1684 # Things related to the prefilter
1663 1685 #-------------------------------------------------------------------------
1664 1686
1665 1687 def init_prefilter(self):
1666 1688 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1667 1689 # Ultimately this will be refactored in the new interpreter code, but
1668 1690 # for now, we should expose the main prefilter method (there's legacy
1669 1691 # code out there that may rely on this).
1670 1692 self.prefilter = self.prefilter_manager.prefilter_lines
1671 1693
1672 1694 #-------------------------------------------------------------------------
1673 1695 # Things related to the running of code
1674 1696 #-------------------------------------------------------------------------
1675 1697
1676 1698 def ex(self, cmd):
1677 1699 """Execute a normal python statement in user namespace."""
1678 1700 with nested(self.builtin_trap,):
1679 1701 exec cmd in self.user_global_ns, self.user_ns
1680 1702
1681 1703 def ev(self, expr):
1682 1704 """Evaluate python expression expr in user namespace.
1683 1705
1684 1706 Returns the result of evaluation
1685 1707 """
1686 1708 with nested(self.builtin_trap,):
1687 1709 return eval(expr, self.user_global_ns, self.user_ns)
1688 1710
1689 1711 def safe_execfile(self, fname, *where, **kw):
1690 1712 """A safe version of the builtin execfile().
1691 1713
1692 1714 This version will never throw an exception, but instead print
1693 1715 helpful error messages to the screen. This only works on pure
1694 1716 Python files with the .py extension.
1695 1717
1696 1718 Parameters
1697 1719 ----------
1698 1720 fname : string
1699 1721 The name of the file to be executed.
1700 1722 where : tuple
1701 1723 One or two namespaces, passed to execfile() as (globals,locals).
1702 1724 If only one is given, it is passed as both.
1703 1725 exit_ignore : bool (False)
1704 1726 If True, then silence SystemExit for non-zero status (it is always
1705 1727 silenced for zero status, as it is so common).
1706 1728 """
1707 1729 kw.setdefault('exit_ignore', False)
1708 1730
1709 1731 fname = os.path.abspath(os.path.expanduser(fname))
1710 1732
1711 1733 # Make sure we have a .py file
1712 1734 if not fname.endswith('.py'):
1713 1735 warn('File must end with .py to be run using execfile: <%s>' % fname)
1714 1736
1715 1737 # Make sure we can open the file
1716 1738 try:
1717 1739 with open(fname) as thefile:
1718 1740 pass
1719 1741 except:
1720 1742 warn('Could not open file <%s> for safe execution.' % fname)
1721 1743 return
1722 1744
1723 1745 # Find things also in current directory. This is needed to mimic the
1724 1746 # behavior of running a script from the system command line, where
1725 1747 # Python inserts the script's directory into sys.path
1726 1748 dname = os.path.dirname(fname)
1727 1749
1728 1750 with prepended_to_syspath(dname):
1729 1751 try:
1730 1752 execfile(fname,*where)
1731 1753 except SystemExit, status:
1732 1754 # If the call was made with 0 or None exit status (sys.exit(0)
1733 1755 # or sys.exit() ), don't bother showing a traceback, as both of
1734 1756 # these are considered normal by the OS:
1735 1757 # > python -c'import sys;sys.exit(0)'; echo $?
1736 1758 # 0
1737 1759 # > python -c'import sys;sys.exit()'; echo $?
1738 1760 # 0
1739 1761 # For other exit status, we show the exception unless
1740 1762 # explicitly silenced, but only in short form.
1741 1763 if status.code not in (0, None) and not kw['exit_ignore']:
1742 1764 self.showtraceback(exception_only=True)
1743 1765 except:
1744 1766 self.showtraceback()
1745 1767
1746 1768 def safe_execfile_ipy(self, fname):
1747 1769 """Like safe_execfile, but for .ipy files with IPython syntax.
1748 1770
1749 1771 Parameters
1750 1772 ----------
1751 1773 fname : str
1752 1774 The name of the file to execute. The filename must have a
1753 1775 .ipy extension.
1754 1776 """
1755 1777 fname = os.path.abspath(os.path.expanduser(fname))
1756 1778
1757 1779 # Make sure we have a .py file
1758 1780 if not fname.endswith('.ipy'):
1759 1781 warn('File must end with .py to be run using execfile: <%s>' % fname)
1760 1782
1761 1783 # Make sure we can open the file
1762 1784 try:
1763 1785 with open(fname) as thefile:
1764 1786 pass
1765 1787 except:
1766 1788 warn('Could not open file <%s> for safe execution.' % fname)
1767 1789 return
1768 1790
1769 1791 # Find things also in current directory. This is needed to mimic the
1770 1792 # behavior of running a script from the system command line, where
1771 1793 # Python inserts the script's directory into sys.path
1772 1794 dname = os.path.dirname(fname)
1773 1795
1774 1796 with prepended_to_syspath(dname):
1775 1797 try:
1776 1798 with open(fname) as thefile:
1777 1799 script = thefile.read()
1778 1800 # self.runlines currently captures all exceptions
1779 1801 # raise in user code. It would be nice if there were
1780 1802 # versions of runlines, execfile that did raise, so
1781 1803 # we could catch the errors.
1782 1804 self.runlines(script, clean=True)
1783 1805 except:
1784 1806 self.showtraceback()
1785 1807 warn('Unknown failure executing file: <%s>' % fname)
1786 1808
1787 1809 def runlines(self, lines, clean=False):
1788 1810 """Run a string of one or more lines of source.
1789 1811
1790 1812 This method is capable of running a string containing multiple source
1791 1813 lines, as if they had been entered at the IPython prompt. Since it
1792 1814 exposes IPython's processing machinery, the given strings can contain
1793 1815 magic calls (%magic), special shell access (!cmd), etc.
1794 1816 """
1795
1817
1796 1818 if isinstance(lines, (list, tuple)):
1797 1819 lines = '\n'.join(lines)
1798 1820
1799 1821 if clean:
1800 1822 lines = self._cleanup_ipy_script(lines)
1801 1823
1802 1824 # We must start with a clean buffer, in case this is run from an
1803 1825 # interactive IPython session (via a magic, for example).
1804 1826 self.resetbuffer()
1805 1827 lines = lines.splitlines()
1806 1828 more = 0
1807 1829
1808 1830 with nested(self.builtin_trap, self.display_trap):
1809 1831 for line in lines:
1810 1832 # skip blank lines so we don't mess up the prompt counter, but do
1811 1833 # NOT skip even a blank line if we are in a code block (more is
1812 1834 # true)
1813 1835
1814 1836 if line or more:
1815 1837 # push to raw history, so hist line numbers stay in sync
1816 1838 self.input_hist_raw.append("# " + line + "\n")
1817 1839 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1818 1840 more = self.push_line(prefiltered)
1819 1841 # IPython's runsource returns None if there was an error
1820 1842 # compiling the code. This allows us to stop processing right
1821 1843 # away, so the user gets the error message at the right place.
1822 1844 if more is None:
1823 1845 break
1824 1846 else:
1825 1847 self.input_hist_raw.append("\n")
1826 1848 # final newline in case the input didn't have it, so that the code
1827 1849 # actually does get executed
1828 1850 if more:
1829 1851 self.push_line('\n')
1830 1852
1831 1853 def runsource(self, source, filename='<input>', symbol='single'):
1832 1854 """Compile and run some source in the interpreter.
1833 1855
1834 1856 Arguments are as for compile_command().
1835 1857
1836 1858 One several things can happen:
1837 1859
1838 1860 1) The input is incorrect; compile_command() raised an
1839 1861 exception (SyntaxError or OverflowError). A syntax traceback
1840 1862 will be printed by calling the showsyntaxerror() method.
1841 1863
1842 1864 2) The input is incomplete, and more input is required;
1843 1865 compile_command() returned None. Nothing happens.
1844 1866
1845 1867 3) The input is complete; compile_command() returned a code
1846 1868 object. The code is executed by calling self.runcode() (which
1847 1869 also handles run-time exceptions, except for SystemExit).
1848 1870
1849 1871 The return value is:
1850 1872
1851 1873 - True in case 2
1852 1874
1853 1875 - False in the other cases, unless an exception is raised, where
1854 1876 None is returned instead. This can be used by external callers to
1855 1877 know whether to continue feeding input or not.
1856 1878
1857 1879 The return value can be used to decide whether to use sys.ps1 or
1858 1880 sys.ps2 to prompt the next line."""
1859 1881
1860 1882 # if the source code has leading blanks, add 'if 1:\n' to it
1861 1883 # this allows execution of indented pasted code. It is tempting
1862 1884 # to add '\n' at the end of source to run commands like ' a=1'
1863 1885 # directly, but this fails for more complicated scenarios
1864 1886 source=source.encode(self.stdin_encoding)
1865 1887 if source[:1] in [' ', '\t']:
1866 1888 source = 'if 1:\n%s' % source
1867 1889
1868 1890 try:
1869 1891 code = self.compile(source,filename,symbol)
1870 1892 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1871 1893 # Case 1
1872 1894 self.showsyntaxerror(filename)
1873 1895 return None
1874 1896
1875 1897 if code is None:
1876 1898 # Case 2
1877 1899 return True
1878 1900
1879 1901 # Case 3
1880 1902 # We store the code object so that threaded shells and
1881 1903 # custom exception handlers can access all this info if needed.
1882 1904 # The source corresponding to this can be obtained from the
1883 1905 # buffer attribute as '\n'.join(self.buffer).
1884 1906 self.code_to_run = code
1885 1907 # now actually execute the code object
1886 1908 if self.runcode(code) == 0:
1887 1909 return False
1888 1910 else:
1889 1911 return None
1890 1912
1891 1913 def runcode(self,code_obj):
1892 1914 """Execute a code object.
1893 1915
1894 1916 When an exception occurs, self.showtraceback() is called to display a
1895 1917 traceback.
1896 1918
1897 1919 Return value: a flag indicating whether the code to be run completed
1898 1920 successfully:
1899 1921
1900 1922 - 0: successful execution.
1901 1923 - 1: an error occurred.
1902 1924 """
1903 1925
1904 1926 # Set our own excepthook in case the user code tries to call it
1905 1927 # directly, so that the IPython crash handler doesn't get triggered
1906 1928 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1907 1929
1908 1930 # we save the original sys.excepthook in the instance, in case config
1909 1931 # code (such as magics) needs access to it.
1910 1932 self.sys_excepthook = old_excepthook
1911 1933 outflag = 1 # happens in more places, so it's easier as default
1912 1934 try:
1913 1935 try:
1914 1936 self.hooks.pre_runcode_hook()
1937 #rprint('Running code') # dbg
1915 1938 exec code_obj in self.user_global_ns, self.user_ns
1916 1939 finally:
1917 1940 # Reset our crash handler in place
1918 1941 sys.excepthook = old_excepthook
1919 1942 except SystemExit:
1920 1943 self.resetbuffer()
1921 1944 self.showtraceback(exception_only=True)
1922 1945 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1923 1946 except self.custom_exceptions:
1924 1947 etype,value,tb = sys.exc_info()
1925 1948 self.CustomTB(etype,value,tb)
1926 1949 except:
1927 1950 self.showtraceback()
1928 1951 else:
1929 1952 outflag = 0
1930 1953 if softspace(sys.stdout, 0):
1931 1954 print
1932 1955 # Flush out code object which has been run (and source)
1933 1956 self.code_to_run = None
1934 1957 return outflag
1935 1958
1936 1959 def push_line(self, line):
1937 1960 """Push a line to the interpreter.
1938 1961
1939 1962 The line should not have a trailing newline; it may have
1940 1963 internal newlines. The line is appended to a buffer and the
1941 1964 interpreter's runsource() method is called with the
1942 1965 concatenated contents of the buffer as source. If this
1943 1966 indicates that the command was executed or invalid, the buffer
1944 1967 is reset; otherwise, the command is incomplete, and the buffer
1945 1968 is left as it was after the line was appended. The return
1946 1969 value is 1 if more input is required, 0 if the line was dealt
1947 1970 with in some way (this is the same as runsource()).
1948 1971 """
1949 1972
1950 1973 # autoindent management should be done here, and not in the
1951 1974 # interactive loop, since that one is only seen by keyboard input. We
1952 1975 # need this done correctly even for code run via runlines (which uses
1953 1976 # push).
1954 1977
1955 1978 #print 'push line: <%s>' % line # dbg
1956 1979 for subline in line.splitlines():
1957 1980 self._autoindent_update(subline)
1958 1981 self.buffer.append(line)
1959 1982 more = self.runsource('\n'.join(self.buffer), self.filename)
1960 1983 if not more:
1961 1984 self.resetbuffer()
1962 1985 return more
1963 1986
1964 1987 def resetbuffer(self):
1965 1988 """Reset the input buffer."""
1966 1989 self.buffer[:] = []
1967 1990
1968 1991 def _is_secondary_block_start(self, s):
1969 1992 if not s.endswith(':'):
1970 1993 return False
1971 1994 if (s.startswith('elif') or
1972 1995 s.startswith('else') or
1973 1996 s.startswith('except') or
1974 1997 s.startswith('finally')):
1975 1998 return True
1976 1999
1977 2000 def _cleanup_ipy_script(self, script):
1978 2001 """Make a script safe for self.runlines()
1979 2002
1980 2003 Currently, IPython is lines based, with blocks being detected by
1981 2004 empty lines. This is a problem for block based scripts that may
1982 2005 not have empty lines after blocks. This script adds those empty
1983 2006 lines to make scripts safe for running in the current line based
1984 2007 IPython.
1985 2008 """
1986 2009 res = []
1987 2010 lines = script.splitlines()
1988 2011 level = 0
1989 2012
1990 2013 for l in lines:
1991 2014 lstripped = l.lstrip()
1992 2015 stripped = l.strip()
1993 2016 if not stripped:
1994 2017 continue
1995 2018 newlevel = len(l) - len(lstripped)
1996 2019 if level > 0 and newlevel == 0 and \
1997 2020 not self._is_secondary_block_start(stripped):
1998 2021 # add empty line
1999 2022 res.append('')
2000 2023 res.append(l)
2001 2024 level = newlevel
2002 2025
2003 2026 return '\n'.join(res) + '\n'
2004 2027
2005 2028 def _autoindent_update(self,line):
2006 2029 """Keep track of the indent level."""
2007 2030
2008 2031 #debugx('line')
2009 2032 #debugx('self.indent_current_nsp')
2010 2033 if self.autoindent:
2011 2034 if line:
2012 2035 inisp = num_ini_spaces(line)
2013 2036 if inisp < self.indent_current_nsp:
2014 2037 self.indent_current_nsp = inisp
2015 2038
2016 2039 if line[-1] == ':':
2017 2040 self.indent_current_nsp += 4
2018 2041 elif dedent_re.match(line):
2019 2042 self.indent_current_nsp -= 4
2020 2043 else:
2021 2044 self.indent_current_nsp = 0
2022 2045
2023 2046 #-------------------------------------------------------------------------
2024 2047 # Things related to GUI support and pylab
2025 2048 #-------------------------------------------------------------------------
2026 2049
2027 2050 def enable_pylab(self, gui=None):
2028 2051 raise NotImplementedError('Implement enable_pylab in a subclass')
2029 2052
2030 2053 #-------------------------------------------------------------------------
2031 2054 # Utilities
2032 2055 #-------------------------------------------------------------------------
2033 2056
2034 2057 def getoutput(self, cmd):
2035 2058 return getoutput(self.var_expand(cmd,depth=2),
2036 2059 header=self.system_header,
2037 2060 verbose=self.system_verbose)
2038 2061
2039 2062 def getoutputerror(self, cmd):
2040 2063 return getoutputerror(self.var_expand(cmd,depth=2),
2041 2064 header=self.system_header,
2042 2065 verbose=self.system_verbose)
2043 2066
2044 2067 def var_expand(self,cmd,depth=0):
2045 2068 """Expand python variables in a string.
2046 2069
2047 2070 The depth argument indicates how many frames above the caller should
2048 2071 be walked to look for the local namespace where to expand variables.
2049 2072
2050 2073 The global namespace for expansion is always the user's interactive
2051 2074 namespace.
2052 2075 """
2053 2076
2054 2077 return str(ItplNS(cmd,
2055 2078 self.user_ns, # globals
2056 2079 # Skip our own frame in searching for locals:
2057 2080 sys._getframe(depth+1).f_locals # locals
2058 2081 ))
2059 2082
2060 2083 def mktempfile(self,data=None):
2061 2084 """Make a new tempfile and return its filename.
2062 2085
2063 2086 This makes a call to tempfile.mktemp, but it registers the created
2064 2087 filename internally so ipython cleans it up at exit time.
2065 2088
2066 2089 Optional inputs:
2067 2090
2068 2091 - data(None): if data is given, it gets written out to the temp file
2069 2092 immediately, and the file is closed again."""
2070 2093
2071 2094 filename = tempfile.mktemp('.py','ipython_edit_')
2072 2095 self.tempfiles.append(filename)
2073 2096
2074 2097 if data:
2075 2098 tmp_file = open(filename,'w')
2076 2099 tmp_file.write(data)
2077 2100 tmp_file.close()
2078 2101 return filename
2079 2102
2080 2103 # TODO: This should be removed when Term is refactored.
2081 2104 def write(self,data):
2082 2105 """Write a string to the default output"""
2083 IPython.utils.io.Term.cout.write(data)
2106 io.Term.cout.write(data)
2084 2107
2085 2108 # TODO: This should be removed when Term is refactored.
2086 2109 def write_err(self,data):
2087 2110 """Write a string to the default error output"""
2088 IPython.utils.io.Term.cerr.write(data)
2111 io.Term.cerr.write(data)
2089 2112
2090 2113 def ask_yes_no(self,prompt,default=True):
2091 2114 if self.quiet:
2092 2115 return True
2093 2116 return ask_yes_no(prompt,default)
2094 2117
2095 2118 #-------------------------------------------------------------------------
2096 2119 # Things related to IPython exiting
2097 2120 #-------------------------------------------------------------------------
2098 2121
2099 2122 def atexit_operations(self):
2100 2123 """This will be executed at the time of exit.
2101 2124
2102 2125 Saving of persistent data should be performed here.
2103 2126 """
2104 2127 self.savehist()
2105 2128
2106 2129 # Cleanup all tempfiles left around
2107 2130 for tfile in self.tempfiles:
2108 2131 try:
2109 2132 os.unlink(tfile)
2110 2133 except OSError:
2111 2134 pass
2112 2135
2113 2136 # Clear all user namespaces to release all references cleanly.
2114 2137 self.reset()
2115 2138
2116 2139 # Run user hooks
2117 2140 self.hooks.shutdown_hook()
2118 2141
2119 2142 def cleanup(self):
2120 2143 self.restore_sys_module_state()
2121 2144
2122 2145
2123 2146 class InteractiveShellABC(object):
2124 2147 """An abstract base class for InteractiveShell."""
2125 2148 __metaclass__ = abc.ABCMeta
2126 2149
2127 2150 InteractiveShellABC.register(InteractiveShell)
@@ -1,1156 +1,1202 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 # IPython's own modules
92 92 # Modified pdb which doesn't damage IPython's readline handling
93 from IPython.utils import PyColorize
94 93 from IPython.core import debugger, ipapi
95 94 from IPython.core.display_trap import DisplayTrap
96 95 from IPython.core.excolors import exception_colors
96 from IPython.utils import PyColorize
97 from IPython.utils import io
97 98 from IPython.utils.data import uniq_stable
98 import IPython.utils.io
99 99 from IPython.utils.warn import info, error
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 class TBTools:
313 class TBTools(object):
314 314 """Basic tools used by all traceback printer classes."""
315 315
316 316 # This attribute us used in globalipapp.py to have stdout used for
317 317 # writting exceptions. This is needed so nose can trap them. This attribute
318 318 # should be None (the default, which will use IPython.utils.io.Term) or
319 319 # the string 'stdout' which will cause the override to sys.stdout.
320 320 out_stream = None
321 321
322 # Number of frames to skip when reporting tracebacks
323 tb_offset = 0
324
322 325 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
323 326 # Whether to call the interactive pdb debugger after printing
324 327 # tracebacks or not
325 328 self.call_pdb = call_pdb
326 329
327 330 # Create color table
328 331 self.color_scheme_table = exception_colors()
329 332
330 333 self.set_colors(color_scheme)
331 334 self.old_scheme = color_scheme # save initial value for toggles
332 335
333 336 if call_pdb:
334 337 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
335 338 else:
336 339 self.pdb = None
337 340
338 341 def set_colors(self,*args,**kw):
339 342 """Shorthand access to the color table scheme selector method."""
340 343
341 344 # Set own color table
342 345 self.color_scheme_table.set_active_scheme(*args,**kw)
343 346 # for convenience, set Colors to the active scheme
344 347 self.Colors = self.color_scheme_table.active_colors
345 348 # Also set colors of debugger
346 349 if hasattr(self,'pdb') and self.pdb is not None:
347 350 self.pdb.set_colors(*args,**kw)
348 351
349 352 def color_toggle(self):
350 353 """Toggle between the currently active color scheme and NoColor."""
351 354
352 355 if self.color_scheme_table.active_scheme_name == 'NoColor':
353 356 self.color_scheme_table.set_active_scheme(self.old_scheme)
354 357 self.Colors = self.color_scheme_table.active_colors
355 358 else:
356 359 self.old_scheme = self.color_scheme_table.active_scheme_name
357 360 self.color_scheme_table.set_active_scheme('NoColor')
358 361 self.Colors = self.color_scheme_table.active_colors
359 362
363 def text(self, etype, value, tb, tb_offset=None, context=5):
364 """Return formatted traceback.
365
366 Subclasses may override this if they add extra arguments.
367 """
368 tb_list = self.structured_traceback(etype, value, tb,
369 tb_offset, context)
370 return '\n'.join(tb_list)
371
372 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
373 context=5, mode=None):
374 """Return a list of traceback frames.
375
376 Must be implemented by each class.
377 """
378 raise NotImplementedError()
379
380
360 381 #---------------------------------------------------------------------------
361 382 class ListTB(TBTools):
362 383 """Print traceback information from a traceback list, with optional color.
363 384
364 385 Calling: requires 3 arguments:
365 386 (etype, evalue, elist)
366 387 as would be obtained by:
367 388 etype, evalue, tb = sys.exc_info()
368 389 if tb:
369 390 elist = traceback.extract_tb(tb)
370 391 else:
371 392 elist = None
372 393
373 394 It can thus be used by programs which need to process the traceback before
374 395 printing (such as console replacements based on the code module from the
375 396 standard library).
376 397
377 398 Because they are meant to be called without a full traceback (only a
378 399 list), instances of this class can't call the interactive pdb debugger."""
379 400
380 401 def __init__(self,color_scheme = 'NoColor'):
381 402 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
382 403
383 404 def __call__(self, etype, value, elist):
384 IPython.utils.io.Term.cout.flush()
385 IPython.utils.io.Term.cerr.write(self.text(etype,value,elist))
386 IPython.utils.io.Term.cerr.write('\n')
405 io.Term.cout.flush()
406 io.Term.cerr.write(self.text(etype, value, elist))
407 io.Term.cerr.write('\n')
387 408
388 def structured_traceback(self, etype, value, elist, context=5):
409 def structured_traceback(self, etype, value, elist, tb_offset=None,
410 context=5):
389 411 """Return a color formatted string with the traceback info.
390 412
391 413 Parameters
392 414 ----------
393 415 etype : exception type
394 416 Type of the exception raised.
395 417
396 418 value : object
397 419 Data stored in the exception
398 420
399 421 elist : list
400 422 List of frames, see class docstring for details.
401 423
424 tb_offset : int, optional
425 Number of frames in the traceback to skip. If not given, the
426 instance value is used (set in constructor).
427
428 context : int, optional
429 Number of lines of context information to print.
430
402 431 Returns
403 432 -------
404 433 String with formatted exception.
405 434 """
406
435 tb_offset = self.tb_offset if tb_offset is None else tb_offset
407 436 Colors = self.Colors
408 out_string = []
437 out_list = []
409 438 if elist:
410 out_string.append('Traceback %s(most recent call last)%s:' %
439
440 if tb_offset and len(elist) > tb_offset:
441 elist = elist[tb_offset:]
442
443 out_list.append('Traceback %s(most recent call last)%s:' %
411 444 (Colors.normalEm, Colors.Normal) + '\n')
412 out_string.extend(self._format_list(elist))
413 lines = self._format_exception_only(etype, value)
414 for line in lines[:-1]:
415 out_string.append(" "+line)
416 out_string.append(lines[-1])
417 return out_string
418
419 def text(self, etype, value, elist, context=5):
420 out_string = ListTB.structured_traceback(
421 self, etype, value, elist, context
422 )
423 return ''.join(out_string)
445 out_list.extend(self._format_list(elist))
446 # The exception info should be a single entry in the list.
447 lines = ''.join(self._format_exception_only(etype, value))
448 out_list.append(lines)
449
450 # Note: this code originally read:
451
452 ## for line in lines[:-1]:
453 ## out_list.append(" "+line)
454 ## out_list.append(lines[-1])
455
456 # This means it was indenting everything but the last line by a little
457 # bit. I've disabled this for now, but if we see ugliness somewhre we
458 # can restore it.
459
460 return out_list
424 461
425 462 def _format_list(self, extracted_list):
426 463 """Format a list of traceback entry tuples for printing.
427 464
428 465 Given a list of tuples as returned by extract_tb() or
429 466 extract_stack(), return a list of strings ready for printing.
430 467 Each string in the resulting list corresponds to the item with the
431 468 same index in the argument list. Each string ends in a newline;
432 469 the strings may contain internal newlines as well, for those items
433 470 whose source text line is not None.
434 471
435 472 Lifted almost verbatim from traceback.py
436 473 """
437 474
438 475 Colors = self.Colors
439 476 list = []
440 477 for filename, lineno, name, line in extracted_list[:-1]:
441 478 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
442 479 (Colors.filename, filename, Colors.Normal,
443 480 Colors.lineno, lineno, Colors.Normal,
444 481 Colors.name, name, Colors.Normal)
445 482 if line:
446 483 item = item + ' %s\n' % line.strip()
447 484 list.append(item)
448 485 # Emphasize the last entry
449 486 filename, lineno, name, line = extracted_list[-1]
450 487 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
451 488 (Colors.normalEm,
452 489 Colors.filenameEm, filename, Colors.normalEm,
453 490 Colors.linenoEm, lineno, Colors.normalEm,
454 491 Colors.nameEm, name, Colors.normalEm,
455 492 Colors.Normal)
456 493 if line:
457 494 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
458 495 Colors.Normal)
459 496 list.append(item)
497 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
460 498 return list
461 499
462 500 def _format_exception_only(self, etype, value):
463 501 """Format the exception part of a traceback.
464 502
465 503 The arguments are the exception type and value such as given by
466 504 sys.exc_info()[:2]. The return value is a list of strings, each ending
467 505 in a newline. Normally, the list contains a single string; however,
468 506 for SyntaxError exceptions, it contains several lines that (when
469 507 printed) display detailed information about where the syntax error
470 508 occurred. The message indicating which exception occurred is the
471 509 always last string in the list.
472 510
473 511 Also lifted nearly verbatim from traceback.py
474 512 """
475 513
476 514 have_filedata = False
477 515 Colors = self.Colors
478 516 list = []
479 517 try:
480 518 stype = Colors.excName + etype.__name__ + Colors.Normal
481 519 except AttributeError:
482 520 stype = etype # String exceptions don't get special coloring
483 521 if value is None:
484 522 list.append( str(stype) + '\n')
485 523 else:
486 524 if etype is SyntaxError:
487 525 try:
488 526 msg, (filename, lineno, offset, line) = value
489 527 except:
490 528 have_filedata = False
491 529 else:
492 530 have_filedata = True
493 531 #print 'filename is',filename # dbg
494 532 if not filename: filename = "<string>"
495 533 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
496 534 (Colors.normalEm,
497 535 Colors.filenameEm, filename, Colors.normalEm,
498 536 Colors.linenoEm, lineno, Colors.Normal ))
499 537 if line is not None:
500 538 i = 0
501 539 while i < len(line) and line[i].isspace():
502 540 i = i+1
503 541 list.append('%s %s%s\n' % (Colors.line,
504 542 line.strip(),
505 543 Colors.Normal))
506 544 if offset is not None:
507 545 s = ' '
508 546 for c in line[i:offset-1]:
509 547 if c.isspace():
510 548 s = s + c
511 549 else:
512 550 s = s + ' '
513 551 list.append('%s%s^%s\n' % (Colors.caret, s,
514 552 Colors.Normal) )
515 553 value = msg
516 554 s = self._some_str(value)
517 555 if s:
518 556 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
519 557 Colors.Normal, s))
520 558 else:
521 559 list.append('%s\n' % str(stype))
522 560
523 561 # sync with user hooks
524 562 if have_filedata:
525 563 ipinst = ipapi.get()
526 564 if ipinst is not None:
527 565 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
528 566
529 567 return list
530 568
569 def get_exception_only(self, etype, value):
570 """Only print the exception type and message, without a traceback.
571
572 Parameters
573 ----------
574 etype : exception type
575 value : exception value
576 """
577 return ListTB.structured_traceback(self, etype, value, [])
578
579
531 580 def show_exception_only(self, etype, value):
532 581 """Only print the exception type and message, without a traceback.
533 582
534 583 Parameters
535 584 ----------
536 585 etype : exception type
537 586 value : exception value
538 587 """
539 588 # This method needs to use __call__ from *this* class, not the one from
540 589 # a subclass whose signature or behavior may be different
541 590 if self.out_stream == 'stdout':
542 591 ostream = sys.stdout
543 592 else:
544 ostream = IPython.utils.io.Term.cerr
593 ostream = io.Term.cerr
545 594 ostream.flush()
546 ostream.write(ListTB.text(self, etype, value, []))
595 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
547 596 ostream.flush()
548 597
549 598 def _some_str(self, value):
550 599 # Lifted from traceback.py
551 600 try:
552 601 return str(value)
553 602 except:
554 603 return '<unprintable %s object>' % type(value).__name__
555 604
556 605 #----------------------------------------------------------------------------
557 606 class VerboseTB(TBTools):
558 607 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
559 608 of HTML. Requires inspect and pydoc. Crazy, man.
560 609
561 610 Modified version which optionally strips the topmost entries from the
562 611 traceback, to be used with alternate interpreters (because their own code
563 612 would appear in the traceback)."""
564 613
565 614 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
566 615 call_pdb = 0, include_vars=1):
567 616 """Specify traceback offset, headers and color scheme.
568 617
569 618 Define how many frames to drop from the tracebacks. Calling it with
570 619 tb_offset=1 allows use of this handler in interpreters which will have
571 620 their own code at the top of the traceback (VerboseTB will first
572 621 remove that frame before printing the traceback info)."""
573 622 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
574 623 self.tb_offset = tb_offset
575 624 self.long_header = long_header
576 625 self.include_vars = include_vars
577 626
578 def structured_traceback(self, etype, evalue, etb, context=5):
627 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
628 context=5):
579 629 """Return a nice text document describing the traceback."""
580 630
631 tb_offset = self.tb_offset if tb_offset is None else tb_offset
632
581 633 # some locals
582 634 try:
583 635 etype = etype.__name__
584 636 except AttributeError:
585 637 pass
586 638 Colors = self.Colors # just a shorthand + quicker name lookup
587 639 ColorsNormal = Colors.Normal # used a lot
588 640 col_scheme = self.color_scheme_table.active_scheme_name
589 641 indent = ' '*INDENT_SIZE
590 642 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
591 643 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
592 644 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
593 645
594 646 # some internal-use functions
595 647 def text_repr(value):
596 648 """Hopefully pretty robust repr equivalent."""
597 649 # this is pretty horrible but should always return *something*
598 650 try:
599 651 return pydoc.text.repr(value)
600 652 except KeyboardInterrupt:
601 653 raise
602 654 except:
603 655 try:
604 656 return repr(value)
605 657 except KeyboardInterrupt:
606 658 raise
607 659 except:
608 660 try:
609 661 # all still in an except block so we catch
610 662 # getattr raising
611 663 name = getattr(value, '__name__', None)
612 664 if name:
613 665 # ick, recursion
614 666 return text_repr(name)
615 667 klass = getattr(value, '__class__', None)
616 668 if klass:
617 669 return '%s instance' % text_repr(klass)
618 670 except KeyboardInterrupt:
619 671 raise
620 672 except:
621 673 return 'UNRECOVERABLE REPR FAILURE'
622 674 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
623 675 def nullrepr(value, repr=text_repr): return ''
624 676
625 677 # meat of the code begins
626 678 try:
627 679 etype = etype.__name__
628 680 except AttributeError:
629 681 pass
630 682
631 683 if self.long_header:
632 684 # Header with the exception type, python version, and date
633 685 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
634 686 date = time.ctime(time.time())
635 687
636 688 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
637 689 exc, ' '*(75-len(str(etype))-len(pyver)),
638 690 pyver, string.rjust(date, 75) )
639 691 head += "\nA problem occured executing Python code. Here is the sequence of function"\
640 692 "\ncalls leading up to the error, with the most recent (innermost) call last."
641 693 else:
642 694 # Simplified header
643 695 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
644 696 string.rjust('Traceback (most recent call last)',
645 697 75 - len(str(etype)) ) )
646 698 frames = []
647 699 # Flush cache before calling inspect. This helps alleviate some of the
648 700 # problems with python 2.3's inspect.py.
649 701 linecache.checkcache()
650 702 # Drop topmost frames if requested
651 703 try:
652 704 # Try the default getinnerframes and Alex's: Alex's fixes some
653 705 # problems, but it generates empty tracebacks for console errors
654 706 # (5 blanks lines) where none should be returned.
655 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
707 #records = inspect.getinnerframes(etb, context)[tb_offset:]
656 708 #print 'python records:', records # dbg
657 records = _fixed_getinnerframes(etb, context,self.tb_offset)
709 records = _fixed_getinnerframes(etb, context, tb_offset)
658 710 #print 'alex records:', records # dbg
659 711 except:
660 712
661 713 # FIXME: I've been getting many crash reports from python 2.3
662 714 # users, traceable to inspect.py. If I can find a small test-case
663 715 # to reproduce this, I should either write a better workaround or
664 716 # file a bug report against inspect (if that's the real problem).
665 717 # So far, I haven't been able to find an isolated example to
666 718 # reproduce the problem.
667 719 inspect_error()
668 traceback.print_exc(file=IPython.utils.io.Term.cerr)
720 traceback.print_exc(file=io.Term.cerr)
669 721 info('\nUnfortunately, your original traceback can not be constructed.\n')
670 722 return ''
671 723
672 724 # build some color string templates outside these nested loops
673 725 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
674 726 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
675 727 ColorsNormal)
676 728 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
677 729 (Colors.vName, Colors.valEm, ColorsNormal)
678 730 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
679 731 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
680 732 Colors.vName, ColorsNormal)
681 733 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
682 734 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
683 735 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
684 736 ColorsNormal)
685 737
686 738 # now, loop over all records printing context and info
687 739 abspath = os.path.abspath
688 740 for frame, file, lnum, func, lines, index in records:
689 741 #print '*** record:',file,lnum,func,lines,index # dbg
690 742 try:
691 743 file = file and abspath(file) or '?'
692 744 except OSError:
693 745 # if file is '<console>' or something not in the filesystem,
694 746 # the abspath call will throw an OSError. Just ignore it and
695 747 # keep the original file string.
696 748 pass
697 749 link = tpl_link % file
698 750 try:
699 751 args, varargs, varkw, locals = inspect.getargvalues(frame)
700 752 except:
701 753 # This can happen due to a bug in python2.3. We should be
702 754 # able to remove this try/except when 2.4 becomes a
703 755 # requirement. Bug details at http://python.org/sf/1005466
704 756 inspect_error()
705 traceback.print_exc(file=IPython.utils.io.Term.cerr)
757 traceback.print_exc(file=io.Term.cerr)
706 758 info("\nIPython's exception reporting continues...\n")
707 759
708 760 if func == '?':
709 761 call = ''
710 762 else:
711 763 # Decide whether to include variable details or not
712 764 var_repr = self.include_vars and eqrepr or nullrepr
713 765 try:
714 766 call = tpl_call % (func,inspect.formatargvalues(args,
715 767 varargs, varkw,
716 768 locals,formatvalue=var_repr))
717 769 except KeyError:
718 770 # Very odd crash from inspect.formatargvalues(). The
719 771 # scenario under which it appeared was a call to
720 772 # view(array,scale) in NumTut.view.view(), where scale had
721 773 # been defined as a scalar (it should be a tuple). Somehow
722 774 # inspect messes up resolving the argument list of view()
723 775 # and barfs out. At some point I should dig into this one
724 776 # and file a bug report about it.
725 777 inspect_error()
726 traceback.print_exc(file=IPython.utils.io.Term.cerr)
778 traceback.print_exc(file=io.Term.cerr)
727 779 info("\nIPython's exception reporting continues...\n")
728 780 call = tpl_call_fail % func
729 781
730 782 # Initialize a list of names on the current line, which the
731 783 # tokenizer below will populate.
732 784 names = []
733 785
734 786 def tokeneater(token_type, token, start, end, line):
735 787 """Stateful tokeneater which builds dotted names.
736 788
737 789 The list of names it appends to (from the enclosing scope) can
738 790 contain repeated composite names. This is unavoidable, since
739 791 there is no way to disambguate partial dotted structures until
740 792 the full list is known. The caller is responsible for pruning
741 793 the final list of duplicates before using it."""
742 794
743 795 # build composite names
744 796 if token == '.':
745 797 try:
746 798 names[-1] += '.'
747 799 # store state so the next token is added for x.y.z names
748 800 tokeneater.name_cont = True
749 801 return
750 802 except IndexError:
751 803 pass
752 804 if token_type == tokenize.NAME and token not in keyword.kwlist:
753 805 if tokeneater.name_cont:
754 806 # Dotted names
755 807 names[-1] += token
756 808 tokeneater.name_cont = False
757 809 else:
758 810 # Regular new names. We append everything, the caller
759 811 # will be responsible for pruning the list later. It's
760 812 # very tricky to try to prune as we go, b/c composite
761 813 # names can fool us. The pruning at the end is easy
762 814 # to do (or the caller can print a list with repeated
763 815 # names if so desired.
764 816 names.append(token)
765 817 elif token_type == tokenize.NEWLINE:
766 818 raise IndexError
767 819 # we need to store a bit of state in the tokenizer to build
768 820 # dotted names
769 821 tokeneater.name_cont = False
770 822
771 823 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
772 824 line = getline(file, lnum[0])
773 825 lnum[0] += 1
774 826 return line
775 827
776 828 # Build the list of names on this line of code where the exception
777 829 # occurred.
778 830 try:
779 831 # This builds the names list in-place by capturing it from the
780 832 # enclosing scope.
781 833 tokenize.tokenize(linereader, tokeneater)
782 834 except IndexError:
783 835 # signals exit of tokenizer
784 836 pass
785 837 except tokenize.TokenError,msg:
786 838 _m = ("An unexpected error occurred while tokenizing input\n"
787 839 "The following traceback may be corrupted or invalid\n"
788 840 "The error message is: %s\n" % msg)
789 841 error(_m)
790 842
791 843 # prune names list of duplicates, but keep the right order
792 844 unique_names = uniq_stable(names)
793 845
794 846 # Start loop over vars
795 847 lvals = []
796 848 if self.include_vars:
797 849 for name_full in unique_names:
798 850 name_base = name_full.split('.',1)[0]
799 851 if name_base in frame.f_code.co_varnames:
800 852 if locals.has_key(name_base):
801 853 try:
802 854 value = repr(eval(name_full,locals))
803 855 except:
804 856 value = undefined
805 857 else:
806 858 value = undefined
807 859 name = tpl_local_var % name_full
808 860 else:
809 861 if frame.f_globals.has_key(name_base):
810 862 try:
811 863 value = repr(eval(name_full,frame.f_globals))
812 864 except:
813 865 value = undefined
814 866 else:
815 867 value = undefined
816 868 name = tpl_global_var % name_full
817 869 lvals.append(tpl_name_val % (name,value))
818 870 if lvals:
819 871 lvals = '%s%s' % (indent,em_normal.join(lvals))
820 872 else:
821 873 lvals = ''
822 874
823 875 level = '%s %s\n' % (link,call)
824 876
825 877 if index is None:
826 878 frames.append(level)
827 879 else:
828 880 frames.append('%s%s' % (level,''.join(
829 881 _format_traceback_lines(lnum,index,lines,Colors,lvals,
830 882 col_scheme))))
831 883
832 884 # Get (safely) a string form of the exception info
833 885 try:
834 886 etype_str,evalue_str = map(str,(etype,evalue))
835 887 except:
836 888 # User exception is improperly defined.
837 889 etype,evalue = str,sys.exc_info()[:2]
838 890 etype_str,evalue_str = map(str,(etype,evalue))
839 891 # ... and format it
840 892 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
841 893 ColorsNormal, evalue_str)]
842 894 if type(evalue) is types.InstanceType:
843 895 try:
844 896 names = [w for w in dir(evalue) if isinstance(w, basestring)]
845 897 except:
846 898 # Every now and then, an object with funny inernals blows up
847 899 # when dir() is called on it. We do the best we can to report
848 900 # the problem and continue
849 901 _m = '%sException reporting error (object with broken dir())%s:'
850 902 exception.append(_m % (Colors.excName,ColorsNormal))
851 903 etype_str,evalue_str = map(str,sys.exc_info()[:2])
852 904 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
853 905 ColorsNormal, evalue_str))
854 906 names = []
855 907 for name in names:
856 908 value = text_repr(getattr(evalue, name))
857 909 exception.append('\n%s%s = %s' % (indent, name, value))
858 910
859 911 # vds: >>
860 912 if records:
861 913 filepath, lnum = records[-1][1:3]
862 914 #print "file:", str(file), "linenb", str(lnum) # dbg
863 915 filepath = os.path.abspath(filepath)
864 916 ipinst = ipapi.get()
865 917 if ipinst is not None:
866 918 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
867 919 # vds: <<
868 920
869 921 # return all our info assembled as a single string
870 922 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
871 923 return [head] + frames + [''.join(exception[0])]
872
873 def text(self, etype, evalue, etb, context=5):
874 tb_list = VerboseTB.structured_traceback(
875 self, etype, evalue, etb, context
876 )
877 return '\n'.join(tb_list)
878
924
879 925 def debugger(self,force=False):
880 926 """Call up the pdb debugger if desired, always clean up the tb
881 927 reference.
882 928
883 929 Keywords:
884 930
885 931 - force(False): by default, this routine checks the instance call_pdb
886 932 flag and does not actually invoke the debugger if the flag is false.
887 933 The 'force' option forces the debugger to activate even if the flag
888 934 is false.
889 935
890 936 If the call_pdb flag is set, the pdb interactive debugger is
891 937 invoked. In all cases, the self.tb reference to the current traceback
892 938 is deleted to prevent lingering references which hamper memory
893 939 management.
894 940
895 941 Note that each call to pdb() does an 'import readline', so if your app
896 942 requires a special setup for the readline completers, you'll have to
897 943 fix that by hand after invoking the exception handler."""
898 944
899 945 if force or self.call_pdb:
900 946 if self.pdb is None:
901 947 self.pdb = debugger.Pdb(
902 948 self.color_scheme_table.active_scheme_name)
903 949 # the system displayhook may have changed, restore the original
904 950 # for pdb
905 951 display_trap = DisplayTrap(hook=sys.__displayhook__)
906 952 with display_trap:
907 953 self.pdb.reset()
908 954 # Find the right frame so we don't pop up inside ipython itself
909 955 if hasattr(self,'tb') and self.tb is not None:
910 956 etb = self.tb
911 957 else:
912 958 etb = self.tb = sys.last_traceback
913 959 while self.tb is not None and self.tb.tb_next is not None:
914 960 self.tb = self.tb.tb_next
915 961 if etb and etb.tb_next:
916 962 etb = etb.tb_next
917 963 self.pdb.botframe = etb.tb_frame
918 964 self.pdb.interaction(self.tb.tb_frame, self.tb)
919 965
920 966 if hasattr(self,'tb'):
921 967 del self.tb
922 968
923 969 def handler(self, info=None):
924 970 (etype, evalue, etb) = info or sys.exc_info()
925 971 self.tb = etb
926 IPython.utils.io.Term.cout.flush()
927 IPython.utils.io.Term.cerr.write(self.text(etype, evalue, etb))
928 IPython.utils.io.Term.cerr.write('\n')
972 io.Term.cout.flush()
973 io.Term.cerr.write(self.text(etype, evalue, etb))
974 io.Term.cerr.write('\n')
929 975
930 976 # Changed so an instance can just be called as VerboseTB_inst() and print
931 977 # out the right info on its own.
932 978 def __call__(self, etype=None, evalue=None, etb=None):
933 979 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
934 980 if etb is None:
935 981 self.handler()
936 982 else:
937 983 self.handler((etype, evalue, etb))
938 984 try:
939 985 self.debugger()
940 986 except KeyboardInterrupt:
941 987 print "\nKeyboardInterrupt"
942 988
943 989 #----------------------------------------------------------------------------
944 class FormattedTB(VerboseTB,ListTB):
990 class FormattedTB(VerboseTB, ListTB):
945 991 """Subclass ListTB but allow calling with a traceback.
946 992
947 993 It can thus be used as a sys.excepthook for Python > 2.1.
948 994
949 995 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
950 996
951 997 Allows a tb_offset to be specified. This is useful for situations where
952 998 one needs to remove a number of topmost frames from the traceback (such as
953 999 occurs with python programs that themselves execute other python code,
954 1000 like Python shells). """
955 1001
956 def __init__(self, mode = 'Plain', color_scheme='Linux',
957 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
1002 def __init__(self, mode='Plain', color_scheme='Linux',
1003 tb_offset=0, long_header=0, call_pdb=0, include_vars=0):
958 1004
959 1005 # NEVER change the order of this list. Put new modes at the end:
960 1006 self.valid_modes = ['Plain','Context','Verbose']
961 1007 self.verbose_modes = self.valid_modes[1:3]
962 1008
963 1009 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
964 1010 call_pdb=call_pdb,include_vars=include_vars)
965 1011 self.set_mode(mode)
966 1012
967 1013 def _extract_tb(self,tb):
968 1014 if tb:
969 1015 return traceback.extract_tb(tb)
970 1016 else:
971 1017 return None
972 1018
973 def structured_traceback(self, etype, value, tb, context=5, mode=None):
1019 def structured_traceback(self, etype, value, tb, tb_offset=None,
1020 context=5, mode=None):
1021 tb_offset = self.tb_offset if tb_offset is None else tb_offset
974 1022 mode = self.mode if mode is None else mode
975 1023 if mode in self.verbose_modes:
976 1024 # Verbose modes need a full traceback
977 1025 return VerboseTB.structured_traceback(
978 self, etype, value, tb, context
1026 self, etype, value, tb, tb_offset, context
979 1027 )
980 1028 else:
981 1029 # We must check the source cache because otherwise we can print
982 1030 # out-of-date source code.
983 1031 linecache.checkcache()
984 1032 # Now we can extract and format the exception
985 1033 elist = self._extract_tb(tb)
986 if len(elist) > self.tb_offset:
987 del elist[:self.tb_offset]
988 1034 return ListTB.structured_traceback(
989 self, etype, value, elist, context
1035 self, etype, value, elist, tb_offset, context
990 1036 )
991 1037
992 def text(self, etype, value, tb, context=5, mode=None):
1038 def text(self, etype, value, tb, tb_offset=None, context=5, mode=None):
993 1039 """Return formatted traceback.
994 1040
995 1041 If the optional mode parameter is given, it overrides the current
996 1042 mode."""
997 tb_list = FormattedTB.structured_traceback(
998 self, etype, value, tb, context, mode
999 )
1043
1044 mode = self.mode if mode is None else mode
1045 tb_list = self.structured_traceback(etype, value, tb, tb_offset,
1046 context, mode)
1000 1047 return '\n'.join(tb_list)
1048
1001 1049
1002 1050 def set_mode(self,mode=None):
1003 1051 """Switch to the desired mode.
1004 1052
1005 1053 If mode is not specified, cycles through the available modes."""
1006 1054
1007 1055 if not mode:
1008 1056 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1009 1057 len(self.valid_modes)
1010 1058 self.mode = self.valid_modes[new_idx]
1011 1059 elif mode not in self.valid_modes:
1012 1060 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1013 1061 'Valid modes: '+str(self.valid_modes)
1014 1062 else:
1015 1063 self.mode = mode
1016 1064 # include variable details only in 'Verbose' mode
1017 1065 self.include_vars = (self.mode == self.valid_modes[2])
1018 1066
1019 1067 # some convenient shorcuts
1020 1068 def plain(self):
1021 1069 self.set_mode(self.valid_modes[0])
1022 1070
1023 1071 def context(self):
1024 1072 self.set_mode(self.valid_modes[1])
1025 1073
1026 1074 def verbose(self):
1027 1075 self.set_mode(self.valid_modes[2])
1028 1076
1029 1077 #----------------------------------------------------------------------------
1030 1078 class AutoFormattedTB(FormattedTB):
1031 1079 """A traceback printer which can be called on the fly.
1032 1080
1033 1081 It will find out about exceptions by itself.
1034 1082
1035 1083 A brief example:
1036 1084
1037 1085 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1038 1086 try:
1039 1087 ...
1040 1088 except:
1041 1089 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1042 1090 """
1043 1091
1044 1092 def __call__(self,etype=None,evalue=None,etb=None,
1045 1093 out=None,tb_offset=None):
1046 1094 """Print out a formatted exception traceback.
1047 1095
1048 1096 Optional arguments:
1049 1097 - out: an open file-like object to direct output to.
1050 1098
1051 1099 - tb_offset: the number of frames to skip over in the stack, on a
1052 1100 per-call basis (this overrides temporarily the instance's tb_offset
1053 1101 given at initialization time. """
1054 1102
1055 1103 if out is None:
1056 1104 if self.out_stream == 'stdout':
1057 1105 out = sys.stdout
1058 1106 else:
1059 out = IPython.utils.io.Term.cerr
1107 out = io.Term.cerr
1060 1108 out.flush()
1061 if tb_offset is not None:
1062 tb_offset, self.tb_offset = self.tb_offset, tb_offset
1063 out.write(self.text(etype, evalue, etb))
1064 out.write('\n')
1065 self.tb_offset = tb_offset
1066 else:
1067 out.write(self.text(etype, evalue, etb))
1068 out.write('\n')
1109 out.write(self.text(etype, evalue, etb, tb_offset))
1110 out.write('\n')
1069 1111 out.flush()
1112 # FIXME: we should remove the auto pdb behavior from here and leave
1113 # that to the clients.
1070 1114 try:
1071 1115 self.debugger()
1072 1116 except KeyboardInterrupt:
1073 1117 print "\nKeyboardInterrupt"
1074 1118
1075 1119 def structured_traceback(self, etype=None, value=None, tb=None,
1076 context=5, mode=None):
1120 tb_offset=None, context=5, mode=None):
1077 1121 if etype is None:
1078 1122 etype,value,tb = sys.exc_info()
1079 1123 self.tb = tb
1080 1124 return FormattedTB.structured_traceback(
1081 self, etype, value, tb, context, mode
1082 )
1083
1084 def text(self, etype=None, value=None, tb=None, context=5, mode=None):
1085 tb_list = AutoFormattedTB.structured_traceback(
1086 self, etype, value, tb, context, mode
1087 )
1088 return '\n'.join(tb_list)
1125 self, etype, value, tb, tb_offset, context, mode )
1089 1126
1090 1127 #---------------------------------------------------------------------------
1091 1128
1092 1129 # A simple class to preserve Nathan's original functionality.
1093 1130 class ColorTB(FormattedTB):
1094 1131 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1095 1132 def __init__(self,color_scheme='Linux',call_pdb=0):
1096 1133 FormattedTB.__init__(self,color_scheme=color_scheme,
1097 1134 call_pdb=call_pdb)
1098 1135
1099 1136
1100 1137 class SyntaxTB(ListTB):
1101 1138 """Extension which holds some state: the last exception value"""
1102 1139
1103 1140 def __init__(self,color_scheme = 'NoColor'):
1104 1141 ListTB.__init__(self,color_scheme)
1105 1142 self.last_syntax_error = None
1106 1143
1107 1144 def __call__(self, etype, value, elist):
1108 1145 self.last_syntax_error = value
1109 1146 ListTB.__call__(self,etype,value,elist)
1110 1147
1111 1148 def clear_err_state(self):
1112 1149 """Return the current error state and clear it"""
1113 1150 e = self.last_syntax_error
1114 1151 self.last_syntax_error = None
1115 1152 return e
1116 1153
1154 def text(self, etype, value, tb, tb_offset=None, context=5):
1155 """Return formatted traceback.
1156
1157 Subclasses may override this if they add extra arguments.
1158 """
1159 tb_list = self.structured_traceback(etype, value, tb,
1160 tb_offset, context)
1161 return ''.join(tb_list)
1162
1117 1163 #----------------------------------------------------------------------------
1118 1164 # module testing (minimal)
1119 1165 if __name__ == "__main__":
1120 1166 def spam(c, (d, e)):
1121 1167 x = c + d
1122 1168 y = c * d
1123 1169 foo(x, y)
1124 1170
1125 1171 def foo(a, b, bar=1):
1126 1172 eggs(a, b + bar)
1127 1173
1128 1174 def eggs(f, g, z=globals()):
1129 1175 h = f + g
1130 1176 i = f - g
1131 1177 return h / i
1132 1178
1133 1179 print ''
1134 1180 print '*** Before ***'
1135 1181 try:
1136 1182 print spam(1, (2, 3))
1137 1183 except:
1138 1184 traceback.print_exc()
1139 1185 print ''
1140 1186
1141 1187 handler = ColorTB()
1142 1188 print '*** ColorTB ***'
1143 1189 try:
1144 1190 print spam(1, (2, 3))
1145 1191 except:
1146 1192 apply(handler, sys.exc_info() )
1147 1193 print ''
1148 1194
1149 1195 handler = VerboseTB()
1150 1196 print '*** VerboseTB ***'
1151 1197 try:
1152 1198 print spam(1, (2, 3))
1153 1199 except:
1154 1200 apply(handler, sys.exc_info() )
1155 1201 print ''
1156 1202
@@ -1,293 +1,301 b''
1 1 # Standard library imports
2 2 from subprocess import Popen
3 3
4 4 # System library imports
5 5 from PyQt4 import QtCore, QtGui
6 6
7 7 # Local imports
8 8 from IPython.core.inputsplitter import IPythonInputSplitter
9 9 from IPython.core.usage import default_banner
10 10 from frontend_widget import FrontendWidget
11 11
12 12
13 13 class IPythonPromptBlock(object):
14 14 """ An internal storage object for IPythonWidget.
15 15 """
16 16 def __init__(self, block, length, number):
17 17 self.block = block
18 18 self.length = length
19 19 self.number = number
20 20
21 21
22 22 class IPythonWidget(FrontendWidget):
23 23 """ A FrontendWidget for an IPython kernel.
24 24 """
25 25
26 26 # Signal emitted when an editor is needed for a file and the editor has been
27 27 # specified as 'custom'. See 'set_editor' for more information.
28 28 custom_edit_requested = QtCore.pyqtSignal(object, object)
29 29
30 30 # The default stylesheet: black text on a white background.
31 31 default_stylesheet = """
32 32 .error { color: red; }
33 33 .in-prompt { color: navy; }
34 34 .in-prompt-number { font-weight: bold; }
35 35 .out-prompt { color: darkred; }
36 36 .out-prompt-number { font-weight: bold; }
37 37 """
38 38
39 39 # A dark stylesheet: white text on a black background.
40 40 dark_stylesheet = """
41 41 QPlainTextEdit, QTextEdit { background-color: black; color: white }
42 42 QFrame { border: 1px solid grey; }
43 43 .error { color: red; }
44 44 .in-prompt { color: lime; }
45 45 .in-prompt-number { color: lime; font-weight: bold; }
46 46 .out-prompt { color: red; }
47 47 .out-prompt-number { color: red; font-weight: bold; }
48 48 """
49 49
50 50 # Default prompts.
51 51 in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
52 52 out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
53 53
54 54 # FrontendWidget protected class variables.
55 55 #_input_splitter_class = IPythonInputSplitter
56 56
57 57 # IPythonWidget protected class variables.
58 58 _payload_source_edit = 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic'
59 59 _payload_source_page = 'IPython.zmq.page.page'
60 60
61 61 #---------------------------------------------------------------------------
62 62 # 'object' interface
63 63 #---------------------------------------------------------------------------
64 64
65 65 def __init__(self, *args, **kw):
66 66 super(IPythonWidget, self).__init__(*args, **kw)
67 67
68 68 # IPythonWidget protected variables.
69 69 self._previous_prompt_obj = None
70 70
71 71 # Set a default editor and stylesheet.
72 72 self.set_editor('default')
73 73 self.reset_styling()
74 74
75 75 #---------------------------------------------------------------------------
76 76 # 'BaseFrontendMixin' abstract interface
77 77 #---------------------------------------------------------------------------
78 78
79 79 def _handle_pyout(self, msg):
80 80 """ Reimplemented for IPython-style "display hook".
81 81 """
82 82 if not self._hidden and self._is_from_this_session(msg):
83 83 content = msg['content']
84 84 prompt_number = content['prompt_number']
85 85 self._append_plain_text(content['output_sep'])
86 86 self._append_html(self._make_out_prompt(prompt_number))
87 87 self._append_plain_text(content['data'] + '\n' +
88 88 content['output_sep2'])
89 89
90 90 #---------------------------------------------------------------------------
91 91 # 'FrontendWidget' interface
92 92 #---------------------------------------------------------------------------
93 93
94 94 def execute_file(self, path, hidden=False):
95 95 """ Reimplemented to use the 'run' magic.
96 96 """
97 self.execute('run %s' % path, hidden=hidden)
97 self.execute('%%run %s' % path, hidden=hidden)
98 98
99 99 #---------------------------------------------------------------------------
100 100 # 'FrontendWidget' protected interface
101 101 #---------------------------------------------------------------------------
102 102
103 103 def _get_banner(self):
104 104 """ Reimplemented to return IPython's default banner.
105 105 """
106 106 return default_banner + '\n'
107 107
108 108 def _process_execute_error(self, msg):
109 109 """ Reimplemented for IPython-style traceback formatting.
110 110 """
111 111 content = msg['content']
112 traceback_lines = content['traceback'][:]
113 traceback = ''.join(traceback_lines)
114 traceback = traceback.replace(' ', '&nbsp;')
115 traceback = traceback.replace('\n', '<br/>')
116 112
117 ename = content['ename']
118 ename_styled = '<span class="error">%s</span>' % ename
119 traceback = traceback.replace(ename, ename_styled)
113 traceback = '\n'.join(content['traceback'])
120 114
121 self._append_html(traceback)
115 if 0:
116 # FIXME: for now, tracebacks come as plain text, so we can't use
117 # the html renderer yet. Once we refactor ultratb to produce
118 # properly styled tracebacks, this branch should be the default
119 traceback = traceback.replace(' ', '&nbsp;')
120 traceback = traceback.replace('\n', '<br/>')
121
122 ename = content['ename']
123 ename_styled = '<span class="error">%s</span>' % ename
124 traceback = traceback.replace(ename, ename_styled)
125
126 self._append_html(traceback)
127 else:
128 # This is the fallback for now, using plain text with ansi escapes
129 self._append_plain_text(traceback)
122 130
123 131 def _process_execute_payload(self, item):
124 132 """ Reimplemented to handle %edit and paging payloads.
125 133 """
126 134 if item['source'] == self._payload_source_edit:
127 135 self.edit(item['filename'], item['line_number'])
128 136 return True
129 137 elif item['source'] == self._payload_source_page:
130 138 self._page(item['data'])
131 139 return True
132 140 else:
133 141 return False
134 142
135 143 def _show_interpreter_prompt(self, number=None, input_sep='\n'):
136 144 """ Reimplemented for IPython-style prompts.
137 145 """
138 146 # TODO: If a number was not specified, make a prompt number request.
139 147 if number is None:
140 148 number = 0
141 149
142 150 # Show a new prompt and save information about it so that it can be
143 151 # updated later if the prompt number turns out to be wrong.
144 152 self._append_plain_text(input_sep)
145 153 self._show_prompt(self._make_in_prompt(number), html=True)
146 154 block = self._control.document().lastBlock()
147 155 length = len(self._prompt)
148 156 self._previous_prompt_obj = IPythonPromptBlock(block, length, number)
149 157
150 158 # Update continuation prompt to reflect (possibly) new prompt length.
151 159 self._set_continuation_prompt(
152 160 self._make_continuation_prompt(self._prompt), html=True)
153 161
154 162 def _show_interpreter_prompt_for_reply(self, msg):
155 163 """ Reimplemented for IPython-style prompts.
156 164 """
157 165 # Update the old prompt number if necessary.
158 166 content = msg['content']
159 167 previous_prompt_number = content['prompt_number']
160 168 if self._previous_prompt_obj and \
161 169 self._previous_prompt_obj.number != previous_prompt_number:
162 170 block = self._previous_prompt_obj.block
163 171 if block.isValid():
164 172
165 173 # Remove the old prompt and insert a new prompt.
166 174 cursor = QtGui.QTextCursor(block)
167 175 cursor.movePosition(QtGui.QTextCursor.Right,
168 176 QtGui.QTextCursor.KeepAnchor,
169 177 self._previous_prompt_obj.length)
170 178 prompt = self._make_in_prompt(previous_prompt_number)
171 179 self._prompt = self._insert_html_fetching_plain_text(
172 180 cursor, prompt)
173 181
174 182 # When the HTML is inserted, Qt blows away the syntax
175 183 # highlighting for the line, so we need to rehighlight it.
176 184 self._highlighter.rehighlightBlock(cursor.block())
177 185
178 186 self._previous_prompt_obj = None
179 187
180 188 # Show a new prompt with the kernel's estimated prompt number.
181 189 next_prompt = content['next_prompt']
182 190 self._show_interpreter_prompt(next_prompt['prompt_number'],
183 191 next_prompt['input_sep'])
184 192
185 193 #---------------------------------------------------------------------------
186 194 # 'IPythonWidget' interface
187 195 #---------------------------------------------------------------------------
188 196
189 197 def edit(self, filename, line=None):
190 198 """ Opens a Python script for editing.
191 199
192 200 Parameters:
193 201 -----------
194 202 filename : str
195 203 A path to a local system file.
196 204
197 205 line : int, optional
198 206 A line of interest in the file.
199 207
200 208 Raises:
201 209 -------
202 210 OSError
203 211 If the editor command cannot be executed.
204 212 """
205 213 if self._editor == 'default':
206 214 url = QtCore.QUrl.fromLocalFile(filename)
207 215 if not QtGui.QDesktopServices.openUrl(url):
208 216 message = 'Failed to open %s with the default application'
209 217 raise OSError(message % repr(filename))
210 218 elif self._editor is None:
211 219 self.custom_edit_requested.emit(filename, line)
212 220 else:
213 221 Popen(self._editor + [filename])
214 222
215 223 def reset_styling(self):
216 224 """ Restores the default IPythonWidget styling.
217 225 """
218 226 self.set_styling(self.default_stylesheet, syntax_style='default')
219 227 #self.set_styling(self.dark_stylesheet, syntax_style='monokai')
220 228
221 229 def set_editor(self, editor):
222 230 """ Sets the editor to use with the %edit magic.
223 231
224 232 Parameters:
225 233 -----------
226 234 editor : str or sequence of str
227 235 A command suitable for use with Popen. This command will be executed
228 236 with a single argument--a filename--when editing is requested.
229 237
230 238 This parameter also takes two special values:
231 239 'default' : Files will be edited with the system default
232 240 application for Python files.
233 241 'custom' : Emit a 'custom_edit_requested(str, int)' signal
234 242 instead of opening an editor.
235 243 """
236 244 if editor == 'default':
237 245 self._editor = 'default'
238 246 elif editor == 'custom':
239 247 self._editor = None
240 248 elif isinstance(editor, basestring):
241 249 self._editor = [ editor ]
242 250 else:
243 251 self._editor = list(editor)
244 252
245 253 def set_styling(self, stylesheet, syntax_style=None):
246 254 """ Sets the IPythonWidget styling.
247 255
248 256 Parameters:
249 257 -----------
250 258 stylesheet : str
251 259 A CSS stylesheet. The stylesheet can contain classes for:
252 260 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
253 261 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
254 262 3. IPython: .error, .in-prompt, .out-prompt, etc.
255 263
256 264 syntax_style : str or None [default None]
257 265 If specified, use the Pygments style with given name. Otherwise,
258 266 the stylesheet is queried for Pygments style information.
259 267 """
260 268 self.setStyleSheet(stylesheet)
261 269 self._control.document().setDefaultStyleSheet(stylesheet)
262 270 if self._page_control:
263 271 self._page_control.document().setDefaultStyleSheet(stylesheet)
264 272
265 273 if syntax_style is None:
266 274 self._highlighter.set_style_sheet(stylesheet)
267 275 else:
268 276 self._highlighter.set_style(syntax_style)
269 277
270 278 #---------------------------------------------------------------------------
271 279 # 'IPythonWidget' protected interface
272 280 #---------------------------------------------------------------------------
273 281
274 282 def _make_in_prompt(self, number):
275 283 """ Given a prompt number, returns an HTML In prompt.
276 284 """
277 285 body = self.in_prompt % number
278 286 return '<span class="in-prompt">%s</span>' % body
279 287
280 288 def _make_continuation_prompt(self, prompt):
281 289 """ Given a plain text version of an In prompt, returns an HTML
282 290 continuation prompt.
283 291 """
284 292 end_chars = '...: '
285 293 space_count = len(prompt.lstrip('\n')) - len(end_chars)
286 294 body = '&nbsp;' * space_count + end_chars
287 295 return '<span class="in-prompt">%s</span>' % body
288 296
289 297 def _make_out_prompt(self, number):
290 298 """ Given a prompt number, returns an HTML Out prompt.
291 299 """
292 300 body = self.out_prompt % number
293 301 return '<span class="out-prompt">%s</span>' % body
@@ -1,80 +1,84 b''
1 1 #!/usr/bin/env python
2 2
3 3 """ A minimal application using the Qt console-style IPython frontend.
4 4 """
5 5
6 6 # Systemm library imports
7 7 from PyQt4 import QtCore, QtGui
8 8
9 9 # Local imports
10 10 from IPython.external.argparse import ArgumentParser
11 11 from IPython.frontend.qt.console.frontend_widget import FrontendWidget
12 12 from IPython.frontend.qt.console.ipython_widget import IPythonWidget
13 13 from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget
14 14 from IPython.frontend.qt.kernelmanager import QtKernelManager
15 15
16 16 # Constants
17 17 LOCALHOST = '127.0.0.1'
18 18
19 19
20 20 def main():
21 21 """ Entry point for application.
22 22 """
23 23 # Parse command line arguments.
24 24 parser = ArgumentParser()
25 25 parser.add_argument('-e', '--existing', action='store_true',
26 26 help='connect to an existing kernel')
27 27 parser.add_argument('--ip', type=str, default=LOCALHOST,
28 28 help='set the kernel\'s IP address [default localhost]')
29 29 parser.add_argument('--xreq', type=int, metavar='PORT', default=0,
30 30 help='set the XREQ channel port [default random]')
31 31 parser.add_argument('--sub', type=int, metavar='PORT', default=0,
32 32 help='set the SUB channel port [default random]')
33 33 parser.add_argument('--rep', type=int, metavar='PORT', default=0,
34 34 help='set the REP channel port [default random]')
35 35 group = parser.add_mutually_exclusive_group()
36 36 group.add_argument('--pure', action='store_true', help = \
37 37 'use a pure Python kernel instead of an IPython kernel')
38 38 group.add_argument('--pylab', action='store_true',
39 39 help='use a kernel with PyLab enabled')
40 40 parser.add_argument('--rich', action='store_true',
41 41 help='use a rich text frontend')
42 42 args = parser.parse_args()
43 43
44 44 # Don't let Qt or ZMQ swallow KeyboardInterupts.
45 45 import signal
46 46 signal.signal(signal.SIGINT, signal.SIG_DFL)
47 47
48 48 # Create a KernelManager and start a kernel.
49 49 kernel_manager = QtKernelManager(xreq_address=(args.ip, args.xreq),
50 50 sub_address=(args.ip, args.sub),
51 51 rep_address=(args.ip, args.rep))
52 52 if args.ip == LOCALHOST and not args.existing:
53 53 if args.pure:
54 54 kernel_manager.start_kernel(ipython=False)
55 55 elif args.pylab:
56 56 if args.rich:
57 57 kernel_manager.start_kernel(pylab='payload-svg')
58 58 else:
59 59 kernel_manager.start_kernel(pylab='qt4')
60 60 else:
61 61 kernel_manager.start_kernel()
62 62 kernel_manager.start_channels()
63 63
64 # FIXME: this is a hack, set colors to lightbg by default in qt terminal
65 # unconditionally, regardless of user settings in config files.
66 kernel_manager.xreq_channel.execute("%colors lightbg")
67
64 68 # Launch the application.
65 69 app = QtGui.QApplication([])
66 70 if args.pure:
67 71 kind = 'rich' if args.rich else 'plain'
68 72 widget = FrontendWidget(kind=kind)
69 73 elif args.rich:
70 74 widget = RichIPythonWidget()
71 75 else:
72 76 widget = IPythonWidget()
73 77 widget.kernel_manager = kernel_manager
74 78 widget.setWindowTitle('Python' if args.pure else 'IPython')
75 79 widget.show()
76 80 app.exec_()
77 81
78 82
79 83 if __name__ == '__main__':
80 84 main()
@@ -1,281 +1,286 b''
1 1 # encoding: utf-8
2 2 """
3 3 IO related utilities.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2008-2009 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16
17 16 import sys
18 17 import tempfile
19 18
20 19 from IPython.external.Itpl import itpl, printpl
21 20
22 21 #-----------------------------------------------------------------------------
23 22 # Code
24 23 #-----------------------------------------------------------------------------
25 24
26 25
27 26 class IOStream:
28 27
29 28 def __init__(self,stream,fallback):
30 29 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
31 30 stream = fallback
32 31 self.stream = stream
33 32 self._swrite = stream.write
34 33 self.flush = stream.flush
35 34
36 35 def write(self,data):
37 36 try:
38 37 self._swrite(data)
39 38 except:
40 39 try:
41 40 # print handles some unicode issues which may trip a plain
42 41 # write() call. Attempt to emulate write() by using a
43 42 # trailing comma
44 43 print >> self.stream, data,
45 44 except:
46 45 # if we get here, something is seriously broken.
47 46 print >> sys.stderr, \
48 47 'ERROR - failed to write data to stream:', self.stream
49 48
50 49 # This class used to have a writeln method, but regular files and streams
51 50 # in Python don't have this method. We need to keep this completely
52 51 # compatible so we removed it.
53 52
54 53 def close(self):
55 54 pass
56 55
57 56
58 57 class IOTerm:
59 58 """ Term holds the file or file-like objects for handling I/O operations.
60 59
61 60 These are normally just sys.stdin, sys.stdout and sys.stderr but for
62 61 Windows they can can replaced to allow editing the strings before they are
63 62 displayed."""
64 63
65 64 # In the future, having IPython channel all its I/O operations through
66 65 # this class will make it easier to embed it into other environments which
67 66 # are not a normal terminal (such as a GUI-based shell)
68 67 def __init__(self, cin=None, cout=None, cerr=None):
69 68 self.cin = IOStream(cin, sys.stdin)
70 69 self.cout = IOStream(cout, sys.stdout)
71 70 self.cerr = IOStream(cerr, sys.stderr)
72 71
73 72
74 73 class Tee(object):
75 74 """A class to duplicate an output stream to stdout/err.
76 75
77 76 This works in a manner very similar to the Unix 'tee' command.
78 77
79 78 When the object is closed or deleted, it closes the original file given to
80 79 it for duplication.
81 80 """
82 81 # Inspired by:
83 82 # http://mail.python.org/pipermail/python-list/2007-May/442737.html
84 83
85 84 def __init__(self, file_or_name, mode=None, channel='stdout'):
86 85 """Construct a new Tee object.
87 86
88 87 Parameters
89 88 ----------
90 89 file_or_name : filename or open filehandle (writable)
91 90 File that will be duplicated
92 91
93 92 mode : optional, valid mode for open().
94 93 If a filename was give, open with this mode.
95 94
96 95 channel : str, one of ['stdout', 'stderr']
97 96 """
98 97 if channel not in ['stdout', 'stderr']:
99 98 raise ValueError('Invalid channel spec %s' % channel)
100 99
101 100 if hasattr(file, 'write') and hasattr(file, 'seek'):
102 101 self.file = file_or_name
103 102 else:
104 103 self.file = open(file_or_name, mode)
105 104 self.channel = channel
106 105 self.ostream = getattr(sys, channel)
107 106 setattr(sys, channel, self)
108 107 self._closed = False
109 108
110 109 def close(self):
111 110 """Close the file and restore the channel."""
112 111 self.flush()
113 112 setattr(sys, self.channel, self.ostream)
114 113 self.file.close()
115 114 self._closed = True
116 115
117 116 def write(self, data):
118 117 """Write data to both channels."""
119 118 self.file.write(data)
120 119 self.ostream.write(data)
121 120 self.ostream.flush()
122 121
123 122 def flush(self):
124 123 """Flush both channels."""
125 124 self.file.flush()
126 125 self.ostream.flush()
127 126
128 127 def __del__(self):
129 128 if not self._closed:
130 129 self.close()
131 130
132 131
133 132 def file_read(filename):
134 133 """Read a file and close it. Returns the file source."""
135 134 fobj = open(filename,'r');
136 135 source = fobj.read();
137 136 fobj.close()
138 137 return source
139 138
140 139
141 140 def file_readlines(filename):
142 141 """Read a file and close it. Returns the file source using readlines()."""
143 142 fobj = open(filename,'r');
144 143 lines = fobj.readlines();
145 144 fobj.close()
146 145 return lines
147 146
148 147
149 148 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
150 149 """Take multiple lines of input.
151 150
152 151 A list with each line of input as a separate element is returned when a
153 152 termination string is entered (defaults to a single '.'). Input can also
154 153 terminate via EOF (^D in Unix, ^Z-RET in Windows).
155 154
156 155 Lines of input which end in \\ are joined into single entries (and a
157 156 secondary continuation prompt is issued as long as the user terminates
158 157 lines with \\). This allows entering very long strings which are still
159 158 meant to be treated as single entities.
160 159 """
161 160
162 161 try:
163 162 if header:
164 163 header += '\n'
165 164 lines = [raw_input(header + ps1)]
166 165 except EOFError:
167 166 return []
168 167 terminate = [terminate_str]
169 168 try:
170 169 while lines[-1:] != terminate:
171 170 new_line = raw_input(ps1)
172 171 while new_line.endswith('\\'):
173 172 new_line = new_line[:-1] + raw_input(ps2)
174 173 lines.append(new_line)
175 174
176 175 return lines[:-1] # don't return the termination command
177 176 except EOFError:
178 177 print
179 178 return lines
180 179
181 180
182 181 def raw_input_ext(prompt='', ps2='... '):
183 182 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
184 183
185 184 line = raw_input(prompt)
186 185 while line.endswith('\\'):
187 186 line = line[:-1] + raw_input(ps2)
188 187 return line
189 188
190 189
191 190 def ask_yes_no(prompt,default=None):
192 191 """Asks a question and returns a boolean (y/n) answer.
193 192
194 193 If default is given (one of 'y','n'), it is used if the user input is
195 194 empty. Otherwise the question is repeated until an answer is given.
196 195
197 196 An EOF is treated as the default answer. If there is no default, an
198 197 exception is raised to prevent infinite loops.
199 198
200 199 Valid answers are: y/yes/n/no (match is not case sensitive)."""
201 200
202 201 answers = {'y':True,'n':False,'yes':True,'no':False}
203 202 ans = None
204 203 while ans not in answers.keys():
205 204 try:
206 205 ans = raw_input(prompt+' ').lower()
207 206 if not ans: # response was an empty string
208 207 ans = default
209 208 except KeyboardInterrupt:
210 209 pass
211 210 except EOFError:
212 211 if default in answers.keys():
213 212 ans = default
214 213 print
215 214 else:
216 215 raise
217 216
218 217 return answers[ans]
219 218
220 219
221 220 class NLprinter:
222 221 """Print an arbitrarily nested list, indicating index numbers.
223 222
224 223 An instance of this class called nlprint is available and callable as a
225 224 function.
226 225
227 226 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
228 227 and using 'sep' to separate the index from the value. """
229 228
230 229 def __init__(self):
231 230 self.depth = 0
232 231
233 232 def __call__(self,lst,pos='',**kw):
234 233 """Prints the nested list numbering levels."""
235 234 kw.setdefault('indent',' ')
236 235 kw.setdefault('sep',': ')
237 236 kw.setdefault('start',0)
238 237 kw.setdefault('stop',len(lst))
239 238 # we need to remove start and stop from kw so they don't propagate
240 239 # into a recursive call for a nested list.
241 240 start = kw['start']; del kw['start']
242 241 stop = kw['stop']; del kw['stop']
243 242 if self.depth == 0 and 'header' in kw.keys():
244 243 print kw['header']
245 244
246 245 for idx in range(start,stop):
247 246 elem = lst[idx]
248 247 if type(elem)==type([]):
249 248 self.depth += 1
250 249 self.__call__(elem,itpl('$pos$idx,'),**kw)
251 250 self.depth -= 1
252 251 else:
253 252 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
254 253
255 254 nlprint = NLprinter()
256 255
257 256
258 257 def temp_pyfile(src, ext='.py'):
259 258 """Make a temporary python file, return filename and filehandle.
260 259
261 260 Parameters
262 261 ----------
263 262 src : string or list of strings (no need for ending newlines if list)
264 263 Source code to be written to the file.
265 264
266 265 ext : optional, string
267 266 Extension for the generated file.
268 267
269 268 Returns
270 269 -------
271 270 (filename, open filehandle)
272 271 It is the caller's responsibility to close the open file and unlink it.
273 272 """
274 273 fname = tempfile.mkstemp(ext)[1]
275 274 f = open(fname,'w')
276 275 f.write(src)
277 276 f.flush()
278 277 return fname, f
279 278
280 279
281
280 def rprint(*info):
281 """Raw print to sys.__stderr__"""
282
283 for item in info:
284 print >> sys.__stderr__, item,
285 print >> sys.__stderr__
286 sys.__stderr__.flush()
@@ -1,378 +1,387 b''
1 1 #!/usr/bin/env python
2 2 """A simple interactive kernel that talks to a frontend over 0MQ.
3 3
4 4 Things to do:
5 5
6 6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 7 call set_parent on all the PUB objects with the message about to be executed.
8 8 * Implement random port and security key logic.
9 9 * Implement control messages.
10 10 * Implement event loop and poll version.
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 # Standard library imports.
18 18 import __builtin__
19 19 import sys
20 20 import time
21 21 import traceback
22 22
23 23 # System library imports.
24 24 import zmq
25 25
26 26 # Local imports.
27 27 from IPython.config.configurable import Configurable
28 28 from IPython.utils.traitlets import Instance
29 29 from completer import KernelCompleter
30 30 from entry_point import base_launch_kernel, make_argument_parser, make_kernel, \
31 31 start_kernel
32 32 from iostream import OutStream
33 33 from session import Session, Message
34 34 from zmqshell import ZMQInteractiveShell
35 35
36 36 #-----------------------------------------------------------------------------
37 37 # Main kernel class
38 38 #-----------------------------------------------------------------------------
39 39
40 40 class Kernel(Configurable):
41 41
42 42 #---------------------------------------------------------------------------
43 43 # Kernel interface
44 44 #---------------------------------------------------------------------------
45 45
46 46 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
47 47 session = Instance(Session)
48 48 reply_socket = Instance('zmq.Socket')
49 49 pub_socket = Instance('zmq.Socket')
50 50 req_socket = Instance('zmq.Socket')
51 51
52 52 # Maps user-friendly backend names to matplotlib backend identifiers.
53 53 _pylab_map = { 'tk': 'TkAgg',
54 54 'gtk': 'GTKAgg',
55 55 'wx': 'WXAgg',
56 56 'qt': 'Qt4Agg', # qt3 not supported
57 57 'qt4': 'Qt4Agg',
58 58 'payload-svg' : \
59 59 'module://IPython.zmq.pylab.backend_payload_svg' }
60 60
61 61 def __init__(self, **kwargs):
62 62 super(Kernel, self).__init__(**kwargs)
63 63
64 64 # Initialize the InteractiveShell subclass
65 65 self.shell = ZMQInteractiveShell.instance()
66 66 self.shell.displayhook.session = self.session
67 67 self.shell.displayhook.pub_socket = self.pub_socket
68 68
69 # TMP - hack while developing
70 self.shell._reply_content = None
71
69 72 # Build dict of handlers for message types
70 73 msg_types = [ 'execute_request', 'complete_request',
71 74 'object_info_request', 'prompt_request',
72 75 'history_request' ]
73 76 self.handlers = {}
74 77 for msg_type in msg_types:
75 78 self.handlers[msg_type] = getattr(self, msg_type)
76 79
77 80 def activate_pylab(self, backend=None, import_all=True):
78 81 """ Activates pylab in this kernel's namespace.
79 82
80 83 Parameters:
81 84 -----------
82 85 backend : str, optional
83 86 A valid backend name.
84 87
85 88 import_all : bool, optional
86 89 If true, an 'import *' is done from numpy and pylab.
87 90 """
88 91 # FIXME: This is adapted from IPython.lib.pylabtools.pylab_activate.
89 92 # Common functionality should be refactored.
90 93
91 94 # We must set the desired backend before importing pylab.
92 95 import matplotlib
93 96 if backend:
94 97 backend_id = self._pylab_map[backend]
95 98 if backend_id.startswith('module://'):
96 99 # Work around bug in matplotlib: matplotlib.use converts the
97 100 # backend_id to lowercase even if a module name is specified!
98 101 matplotlib.rcParams['backend'] = backend_id
99 102 else:
100 103 matplotlib.use(backend_id)
101 104
102 105 # Import numpy as np/pyplot as plt are conventions we're trying to
103 106 # somewhat standardize on. Making them available to users by default
104 107 # will greatly help this.
105 108 exec ("import numpy\n"
106 109 "import matplotlib\n"
107 110 "from matplotlib import pylab, mlab, pyplot\n"
108 111 "np = numpy\n"
109 112 "plt = pyplot\n"
110 113 ) in self.shell.user_ns
111 114
112 115 if import_all:
113 116 exec("from matplotlib.pylab import *\n"
114 117 "from numpy import *\n") in self.shell.user_ns
115 118
116 119 matplotlib.interactive(True)
117 120
118 121 def start(self):
119 122 """ Start the kernel main loop.
120 123 """
121 124 while True:
122 125 ident = self.reply_socket.recv()
123 126 assert self.reply_socket.rcvmore(), "Missing message part."
124 127 msg = self.reply_socket.recv_json()
125 128 omsg = Message(msg)
126 129 print>>sys.__stdout__
127 130 print>>sys.__stdout__, omsg
128 131 handler = self.handlers.get(omsg.msg_type, None)
129 132 if handler is None:
130 133 print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg
131 134 else:
132 135 handler(ident, omsg)
133 136
134 137 #---------------------------------------------------------------------------
135 138 # Kernel request handlers
136 139 #---------------------------------------------------------------------------
137 140
138 141 def execute_request(self, ident, parent):
139 142 try:
140 143 code = parent[u'content'][u'code']
141 144 except:
142 145 print>>sys.__stderr__, "Got bad msg: "
143 146 print>>sys.__stderr__, Message(parent)
144 147 return
145 148 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
146 149 self.pub_socket.send_json(pyin_msg)
147 150
148 151 try:
149 152 # Replace raw_input. Note that is not sufficient to replace
150 153 # raw_input in the user namespace.
151 154 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
152 155 __builtin__.raw_input = raw_input
153 156
154 157 # Set the parent message of the display hook and out streams.
155 158 self.shell.displayhook.set_parent(parent)
156 159 sys.stdout.set_parent(parent)
157 160 sys.stderr.set_parent(parent)
158 161
162 # FIXME: runlines calls the exception handler itself. We should
163 # clean this up.
164 self.shell._reply_content = None
159 165 self.shell.runlines(code)
160 166 except:
167 # FIXME: this code right now isn't being used yet by default,
168 # because the runlines() call above directly fires off exception
169 # reporting. This code, therefore, is only active in the scenario
170 # where runlines itself has an unhandled exception. We need to
171 # uniformize this, for all exception construction to come from a
172 # single location in the codbase.
161 173 etype, evalue, tb = sys.exc_info()
162 tb = traceback.format_exception(etype, evalue, tb)
163 exc_content = {
164 u'status' : u'error',
165 u'traceback' : tb,
166 u'ename' : unicode(etype.__name__),
167 u'evalue' : unicode(evalue)
168 }
169 exc_msg = self.session.msg(u'pyerr', exc_content, parent)
170 self.pub_socket.send_json(exc_msg)
171 reply_content = exc_content
174 tb_list = traceback.format_exception(etype, evalue, tb)
175 reply_content = self.shell._showtraceback(etype, evalue, tb_list)
172 176 else:
173 177 payload = self.shell.payload_manager.read_payload()
174 178 # Be agressive about clearing the payload because we don't want
175 179 # it to sit in memory until the next execute_request comes in.
176 180 self.shell.payload_manager.clear_payload()
177 181 reply_content = { 'status' : 'ok', 'payload' : payload }
178 182
179 183 # Compute the prompt information
180 184 prompt_number = self.shell.displayhook.prompt_count
181 185 reply_content['prompt_number'] = prompt_number
182 186 prompt_string = self.shell.displayhook.prompt1.peek_next_prompt()
183 187 next_prompt = {'prompt_string' : prompt_string,
184 188 'prompt_number' : prompt_number+1,
185 189 'input_sep' : self.shell.displayhook.input_sep}
186 190 reply_content['next_prompt'] = next_prompt
187 191
192 # TMP - fish exception info out of shell, possibly left there by
193 # runlines
194 if self.shell._reply_content is not None:
195 reply_content.update(self.shell._reply_content)
196
188 197 # Flush output before sending the reply.
189 198 sys.stderr.flush()
190 199 sys.stdout.flush()
191 200
192 201 # Send the reply.
193 202 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
194 203 print>>sys.__stdout__, Message(reply_msg)
195 204 self.reply_socket.send(ident, zmq.SNDMORE)
196 205 self.reply_socket.send_json(reply_msg)
197 206 if reply_msg['content']['status'] == u'error':
198 207 self._abort_queue()
199 208
200 209 def complete_request(self, ident, parent):
201 210 matches = {'matches' : self._complete(parent),
202 211 'status' : 'ok'}
203 212 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
204 213 matches, parent, ident)
205 214 print >> sys.__stdout__, completion_msg
206 215
207 216 def object_info_request(self, ident, parent):
208 217 context = parent['content']['oname'].split('.')
209 218 object_info = self._object_info(context)
210 219 msg = self.session.send(self.reply_socket, 'object_info_reply',
211 220 object_info, parent, ident)
212 221 print >> sys.__stdout__, msg
213 222
214 223 def prompt_request(self, ident, parent):
215 224 prompt_number = self.shell.displayhook.prompt_count
216 225 prompt_string = self.shell.displayhook.prompt1.peek_next_prompt()
217 226 content = {'prompt_string' : prompt_string,
218 227 'prompt_number' : prompt_number+1}
219 228 msg = self.session.send(self.reply_socket, 'prompt_reply',
220 229 content, parent, ident)
221 230 print >> sys.__stdout__, msg
222 231
223 232 def history_request(self, ident, parent):
224 233 output = parent['content'].get('output', True)
225 234 index = parent['content'].get('index')
226 235 raw = parent['content'].get('raw', False)
227 236 hist = self.shell.get_history(index=index, raw=raw, output=output)
228 237 content = {'history' : hist}
229 238 msg = self.session.send(self.reply_socket, 'history_reply',
230 239 content, parent, ident)
231 240 print >> sys.__stdout__, msg
232 241
233 242 #---------------------------------------------------------------------------
234 243 # Protected interface
235 244 #---------------------------------------------------------------------------
236 245
237 246 def _abort_queue(self):
238 247 while True:
239 248 try:
240 249 ident = self.reply_socket.recv(zmq.NOBLOCK)
241 250 except zmq.ZMQError, e:
242 251 if e.errno == zmq.EAGAIN:
243 252 break
244 253 else:
245 254 assert self.reply_socket.rcvmore(), "Unexpected missing message part."
246 255 msg = self.reply_socket.recv_json()
247 256 print>>sys.__stdout__, "Aborting:"
248 257 print>>sys.__stdout__, Message(msg)
249 258 msg_type = msg['msg_type']
250 259 reply_type = msg_type.split('_')[0] + '_reply'
251 260 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
252 261 print>>sys.__stdout__, Message(reply_msg)
253 262 self.reply_socket.send(ident,zmq.SNDMORE)
254 263 self.reply_socket.send_json(reply_msg)
255 264 # We need to wait a bit for requests to come in. This can probably
256 265 # be set shorter for true asynchronous clients.
257 266 time.sleep(0.1)
258 267
259 268 def _raw_input(self, prompt, ident, parent):
260 269 # Flush output before making the request.
261 270 sys.stderr.flush()
262 271 sys.stdout.flush()
263 272
264 273 # Send the input request.
265 274 content = dict(prompt=prompt)
266 275 msg = self.session.msg(u'input_request', content, parent)
267 276 self.req_socket.send_json(msg)
268 277
269 278 # Await a response.
270 279 reply = self.req_socket.recv_json()
271 280 try:
272 281 value = reply['content']['value']
273 282 except:
274 283 print>>sys.__stderr__, "Got bad raw_input reply: "
275 284 print>>sys.__stderr__, Message(parent)
276 285 value = ''
277 286 return value
278 287
279 288 def _complete(self, msg):
280 289 return self.shell.complete(msg.content.line)
281 290
282 291 def _object_info(self, context):
283 292 symbol, leftover = self._symbol_from_context(context)
284 293 if symbol is not None and not leftover:
285 294 doc = getattr(symbol, '__doc__', '')
286 295 else:
287 296 doc = ''
288 297 object_info = dict(docstring = doc)
289 298 return object_info
290 299
291 300 def _symbol_from_context(self, context):
292 301 if not context:
293 302 return None, context
294 303
295 304 base_symbol_string = context[0]
296 305 symbol = self.shell.user_ns.get(base_symbol_string, None)
297 306 if symbol is None:
298 307 symbol = __builtin__.__dict__.get(base_symbol_string, None)
299 308 if symbol is None:
300 309 return None, context
301 310
302 311 context = context[1:]
303 312 for i, name in enumerate(context):
304 313 new_symbol = getattr(symbol, name, None)
305 314 if new_symbol is None:
306 315 return symbol, context[i:]
307 316 else:
308 317 symbol = new_symbol
309 318
310 319 return symbol, []
311 320
312 321 #-----------------------------------------------------------------------------
313 322 # Kernel main and launch functions
314 323 #-----------------------------------------------------------------------------
315 324
316 325 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, independent=False,
317 326 pylab=False):
318 327 """ Launches a localhost kernel, binding to the specified ports.
319 328
320 329 Parameters
321 330 ----------
322 331 xrep_port : int, optional
323 332 The port to use for XREP channel.
324 333
325 334 pub_port : int, optional
326 335 The port to use for the SUB channel.
327 336
328 337 req_port : int, optional
329 338 The port to use for the REQ (raw input) channel.
330 339
331 340 independent : bool, optional (default False)
332 341 If set, the kernel process is guaranteed to survive if this process
333 342 dies. If not set, an effort is made to ensure that the kernel is killed
334 343 when this process dies. Note that in this case it is still good practice
335 344 to kill kernels manually before exiting.
336 345
337 346 pylab : bool or string, optional (default False)
338 347 If not False, the kernel will be launched with pylab enabled. If a
339 348 string is passed, matplotlib will use the specified backend. Otherwise,
340 349 matplotlib's default backend will be used.
341 350
342 351 Returns
343 352 -------
344 353 A tuple of form:
345 354 (kernel_process, xrep_port, pub_port, req_port)
346 355 where kernel_process is a Popen object and the ports are integers.
347 356 """
348 357 extra_arguments = []
349 358 if pylab:
350 359 extra_arguments.append('--pylab')
351 360 if isinstance(pylab, basestring):
352 361 extra_arguments.append(pylab)
353 362 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
354 363 xrep_port, pub_port, req_port, independent,
355 364 extra_arguments)
356 365
357 366 def main():
358 367 """ The IPython kernel main entry point.
359 368 """
360 369 parser = make_argument_parser()
361 370 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
362 371 const='auto', help = \
363 372 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
364 373 given, the GUI backend is matplotlib's, otherwise use one of: \
365 374 ['tk', 'gtk', 'qt', 'wx', 'payload-svg'].")
366 375 namespace = parser.parse_args()
367 376
368 377 kernel = make_kernel(namespace, Kernel, OutStream)
369 378 if namespace.pylab:
370 379 if namespace.pylab == 'auto':
371 380 kernel.activate_pylab()
372 381 else:
373 382 kernel.activate_pylab(namespace.pylab)
374 383
375 384 start_kernel(namespace, kernel)
376 385
377 386 if __name__ == '__main__':
378 387 main()
@@ -1,365 +1,389 b''
1 1 import inspect
2 2 import re
3 3 import sys
4 4 from subprocess import Popen, PIPE
5 5
6 6 from IPython.core.interactiveshell import (
7 7 InteractiveShell, InteractiveShellABC
8 8 )
9 9 from IPython.core.displayhook import DisplayHook
10 10 from IPython.core.macro import Macro
11 from IPython.utils.io import rprint
11 12 from IPython.utils.path import get_py_filename
12 13 from IPython.utils.text import StringTypes
13 14 from IPython.utils.traitlets import Instance, Type, Dict
14 15 from IPython.utils.warn import warn
15 16 from IPython.zmq.session import extract_header
16 17 from IPython.core.payloadpage import install_payload_page
17 18
18 19
19 20 # Install the payload version of page.
20 21 install_payload_page()
21 22
22 23
23 24 class ZMQDisplayHook(DisplayHook):
24 25
25 26 session = Instance('IPython.zmq.session.Session')
26 27 pub_socket = Instance('zmq.Socket')
27 28 parent_header = Dict({})
28 29
29 30 def set_parent(self, parent):
30 31 """Set the parent for outbound messages."""
31 32 self.parent_header = extract_header(parent)
32 33
33 34 def start_displayhook(self):
34 35 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
35 36
36 37 def write_output_prompt(self):
37 38 """Write the output prompt."""
38 39 if self.do_full_cache:
39 40 self.msg['content']['output_sep'] = self.output_sep
40 41 self.msg['content']['prompt_string'] = str(self.prompt_out)
41 42 self.msg['content']['prompt_number'] = self.prompt_count
42 43 self.msg['content']['output_sep2'] = self.output_sep2
43 44
44 45 def write_result_repr(self, result_repr):
45 46 self.msg['content']['data'] = result_repr
46 47
47 48 def finish_displayhook(self):
48 49 """Finish up all displayhook activities."""
49 50 self.pub_socket.send_json(self.msg)
50 51 self.msg = None
51 52
52 53
53 54 class ZMQInteractiveShell(InteractiveShell):
54 55 """A subclass of InteractiveShell for ZMQ."""
55 56
56 57 displayhook_class = Type(ZMQDisplayHook)
57 58
58 59 def system(self, cmd):
59 60 cmd = self.var_expand(cmd, depth=2)
60 61 sys.stdout.flush()
61 62 sys.stderr.flush()
62 63 p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
63 64 for line in p.stdout.read().split('\n'):
64 65 if len(line) > 0:
65 66 print line
66 67 for line in p.stderr.read().split('\n'):
67 68 if len(line) > 0:
68 69 print line
69 70 p.wait()
70 71
71 72 def init_io(self):
72 73 # This will just use sys.stdout and sys.stderr. If you want to
73 74 # override sys.stdout and sys.stderr themselves, you need to do that
74 75 # *before* instantiating this class, because Term holds onto
75 76 # references to the underlying streams.
76 77 import IPython.utils.io
77 78 Term = IPython.utils.io.IOTerm()
78 79 IPython.utils.io.Term = Term
79 80
80 81 def magic_edit(self,parameter_s='',last_call=['','']):
81 82 """Bring up an editor and execute the resulting code.
82 83
83 84 Usage:
84 85 %edit [options] [args]
85 86
86 87 %edit runs IPython's editor hook. The default version of this hook is
87 88 set to call the __IPYTHON__.rc.editor command. This is read from your
88 89 environment variable $EDITOR. If this isn't found, it will default to
89 90 vi under Linux/Unix and to notepad under Windows. See the end of this
90 91 docstring for how to change the editor hook.
91 92
92 93 You can also set the value of this editor via the command line option
93 94 '-editor' or in your ipythonrc file. This is useful if you wish to use
94 95 specifically for IPython an editor different from your typical default
95 96 (and for Windows users who typically don't set environment variables).
96 97
97 98 This command allows you to conveniently edit multi-line code right in
98 99 your IPython session.
99 100
100 101 If called without arguments, %edit opens up an empty editor with a
101 102 temporary file and will execute the contents of this file when you
102 103 close it (don't forget to save it!).
103 104
104 105
105 106 Options:
106 107
107 108 -n <number>: open the editor at a specified line number. By default,
108 109 the IPython editor hook uses the unix syntax 'editor +N filename', but
109 110 you can configure this by providing your own modified hook if your
110 111 favorite editor supports line-number specifications with a different
111 112 syntax.
112 113
113 114 -p: this will call the editor with the same data as the previous time
114 115 it was used, regardless of how long ago (in your current session) it
115 116 was.
116 117
117 118 -r: use 'raw' input. This option only applies to input taken from the
118 119 user's history. By default, the 'processed' history is used, so that
119 120 magics are loaded in their transformed version to valid Python. If
120 121 this option is given, the raw input as typed as the command line is
121 122 used instead. When you exit the editor, it will be executed by
122 123 IPython's own processor.
123 124
124 125 -x: do not execute the edited code immediately upon exit. This is
125 126 mainly useful if you are editing programs which need to be called with
126 127 command line arguments, which you can then do using %run.
127 128
128 129
129 130 Arguments:
130 131
131 132 If arguments are given, the following possibilites exist:
132 133
133 134 - The arguments are numbers or pairs of colon-separated numbers (like
134 135 1 4:8 9). These are interpreted as lines of previous input to be
135 136 loaded into the editor. The syntax is the same of the %macro command.
136 137
137 138 - If the argument doesn't start with a number, it is evaluated as a
138 139 variable and its contents loaded into the editor. You can thus edit
139 140 any string which contains python code (including the result of
140 141 previous edits).
141 142
142 143 - If the argument is the name of an object (other than a string),
143 144 IPython will try to locate the file where it was defined and open the
144 145 editor at the point where it is defined. You can use `%edit function`
145 146 to load an editor exactly at the point where 'function' is defined,
146 147 edit it and have the file be executed automatically.
147 148
148 149 If the object is a macro (see %macro for details), this opens up your
149 150 specified editor with a temporary file containing the macro's data.
150 151 Upon exit, the macro is reloaded with the contents of the file.
151 152
152 153 Note: opening at an exact line is only supported under Unix, and some
153 154 editors (like kedit and gedit up to Gnome 2.8) do not understand the
154 155 '+NUMBER' parameter necessary for this feature. Good editors like
155 156 (X)Emacs, vi, jed, pico and joe all do.
156 157
157 158 - If the argument is not found as a variable, IPython will look for a
158 159 file with that name (adding .py if necessary) and load it into the
159 160 editor. It will execute its contents with execfile() when you exit,
160 161 loading any code in the file into your interactive namespace.
161 162
162 163 After executing your code, %edit will return as output the code you
163 164 typed in the editor (except when it was an existing file). This way
164 165 you can reload the code in further invocations of %edit as a variable,
165 166 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
166 167 the output.
167 168
168 169 Note that %edit is also available through the alias %ed.
169 170
170 171 This is an example of creating a simple function inside the editor and
171 172 then modifying it. First, start up the editor:
172 173
173 174 In [1]: ed
174 175 Editing... done. Executing edited code...
175 176 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
176 177
177 178 We can then call the function foo():
178 179
179 180 In [2]: foo()
180 181 foo() was defined in an editing session
181 182
182 183 Now we edit foo. IPython automatically loads the editor with the
183 184 (temporary) file where foo() was previously defined:
184 185
185 186 In [3]: ed foo
186 187 Editing... done. Executing edited code...
187 188
188 189 And if we call foo() again we get the modified version:
189 190
190 191 In [4]: foo()
191 192 foo() has now been changed!
192 193
193 194 Here is an example of how to edit a code snippet successive
194 195 times. First we call the editor:
195 196
196 197 In [5]: ed
197 198 Editing... done. Executing edited code...
198 199 hello
199 200 Out[5]: "print 'hello'n"
200 201
201 202 Now we call it again with the previous output (stored in _):
202 203
203 204 In [6]: ed _
204 205 Editing... done. Executing edited code...
205 206 hello world
206 207 Out[6]: "print 'hello world'n"
207 208
208 209 Now we call it with the output #8 (stored in _8, also as Out[8]):
209 210
210 211 In [7]: ed _8
211 212 Editing... done. Executing edited code...
212 213 hello again
213 214 Out[7]: "print 'hello again'n"
214 215
215 216
216 217 Changing the default editor hook:
217 218
218 219 If you wish to write your own editor hook, you can put it in a
219 220 configuration file which you load at startup time. The default hook
220 221 is defined in the IPython.core.hooks module, and you can use that as a
221 222 starting example for further modifications. That file also has
222 223 general instructions on how to set a new hook for use once you've
223 224 defined it."""
224 225
225 226 # FIXME: This function has become a convoluted mess. It needs a
226 227 # ground-up rewrite with clean, simple logic.
227 228
228 229 def make_filename(arg):
229 230 "Make a filename from the given args"
230 231 try:
231 232 filename = get_py_filename(arg)
232 233 except IOError:
233 234 if args.endswith('.py'):
234 235 filename = arg
235 236 else:
236 237 filename = None
237 238 return filename
238 239
239 240 # custom exceptions
240 241 class DataIsObject(Exception): pass
241 242
242 243 opts,args = self.parse_options(parameter_s,'prn:')
243 244 # Set a few locals from the options for convenience:
244 245 opts_p = opts.has_key('p')
245 246 opts_r = opts.has_key('r')
246 247
247 248 # Default line number value
248 249 lineno = opts.get('n',None)
249 250 if lineno is not None:
250 251 try:
251 252 lineno = int(lineno)
252 253 except:
253 254 warn("The -n argument must be an integer.")
254 255 return
255 256
256 257 if opts_p:
257 258 args = '_%s' % last_call[0]
258 259 if not self.shell.user_ns.has_key(args):
259 260 args = last_call[1]
260 261
261 262 # use last_call to remember the state of the previous call, but don't
262 263 # let it be clobbered by successive '-p' calls.
263 264 try:
264 265 last_call[0] = self.shell.displayhook.prompt_count
265 266 if not opts_p:
266 267 last_call[1] = parameter_s
267 268 except:
268 269 pass
269 270
270 271 # by default this is done with temp files, except when the given
271 272 # arg is a filename
272 273 use_temp = 1
273 274
274 275 if re.match(r'\d',args):
275 276 # Mode where user specifies ranges of lines, like in %macro.
276 277 # This means that you can't edit files whose names begin with
277 278 # numbers this way. Tough.
278 279 ranges = args.split()
279 280 data = ''.join(self.extract_input_slices(ranges,opts_r))
280 281 elif args.endswith('.py'):
281 282 filename = make_filename(args)
282 283 data = ''
283 284 use_temp = 0
284 285 elif args:
285 286 try:
286 287 # Load the parameter given as a variable. If not a string,
287 288 # process it as an object instead (below)
288 289
289 290 #print '*** args',args,'type',type(args) # dbg
290 291 data = eval(args,self.shell.user_ns)
291 292 if not type(data) in StringTypes:
292 293 raise DataIsObject
293 294
294 295 except (NameError,SyntaxError):
295 296 # given argument is not a variable, try as a filename
296 297 filename = make_filename(args)
297 298 if filename is None:
298 299 warn("Argument given (%s) can't be found as a variable "
299 300 "or as a filename." % args)
300 301 return
301 302
302 303 data = ''
303 304 use_temp = 0
304 305 except DataIsObject:
305 306
306 307 # macros have a special edit function
307 308 if isinstance(data,Macro):
308 309 self._edit_macro(args,data)
309 310 return
310 311
311 312 # For objects, try to edit the file where they are defined
312 313 try:
313 314 filename = inspect.getabsfile(data)
314 315 if 'fakemodule' in filename.lower() and inspect.isclass(data):
315 316 # class created by %edit? Try to find source
316 317 # by looking for method definitions instead, the
317 318 # __module__ in those classes is FakeModule.
318 319 attrs = [getattr(data, aname) for aname in dir(data)]
319 320 for attr in attrs:
320 321 if not inspect.ismethod(attr):
321 322 continue
322 323 filename = inspect.getabsfile(attr)
323 324 if filename and 'fakemodule' not in filename.lower():
324 325 # change the attribute to be the edit target instead
325 326 data = attr
326 327 break
327 328
328 329 datafile = 1
329 330 except TypeError:
330 331 filename = make_filename(args)
331 332 datafile = 1
332 333 warn('Could not find file where `%s` is defined.\n'
333 334 'Opening a file named `%s`' % (args,filename))
334 335 # Now, make sure we can actually read the source (if it was in
335 336 # a temp file it's gone by now).
336 337 if datafile:
337 338 try:
338 339 if lineno is None:
339 340 lineno = inspect.getsourcelines(data)[1]
340 341 except IOError:
341 342 filename = make_filename(args)
342 343 if filename is None:
343 344 warn('The file `%s` where `%s` was defined cannot '
344 345 'be read.' % (filename,data))
345 346 return
346 347 use_temp = 0
347 348 else:
348 349 data = ''
349 350
350 351 if use_temp:
351 352 filename = self.shell.mktempfile(data)
352 353 print 'IPython will make a temporary file named:',filename
353 354
354 355 payload = {
355 356 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
356 357 'filename' : filename,
357 358 'line_number' : lineno
358 359 }
359 360 self.payload_manager.write_payload(payload)
360 361
361 362
362 InteractiveShellABC.register(ZMQInteractiveShell)
363 def _showtraceback(self, etype, evalue, stb):
363 364
365 exc_content = {
366 u'status' : u'error',
367 u'traceback' : stb,
368 u'ename' : unicode(etype.__name__),
369 u'evalue' : unicode(evalue)
370 }
364 371
372 dh = self.displayhook
373 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
374 # Send exception info over pub socket for other clients than the caller
375 # to pick up
376 dh.pub_socket.send_json(exc_msg)
377
378 # FIXME - Hack: store exception info in shell object. Right now, the
379 # caller is reading this info after the fact, we need to fix this logic
380 # to remove this hack.
381 self._reply_content = exc_content
382 # /FIXME
383
384 return exc_content
365 385
386 def runlines(self, lines, clean=False):
387 return InteractiveShell.runlines(self, lines, clean)
388
389 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now