##// END OF EJS Templates
Fixes to docs and InteractiveShell.instance()...
Brian Granger -
Show More
@@ -1,2102 +1,2108 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 32 from IPython.core import debugger, oinspect
33 33 from IPython.core import history as ipcorehist
34 34 from IPython.core import prefilter
35 35 from IPython.core import shadowns
36 36 from IPython.core import ultratb
37 37 from IPython.core.alias import AliasManager
38 38 from IPython.core.builtin_trap import BuiltinTrap
39 39 from IPython.config.configurable import Configurable
40 40 from IPython.core.display_trap import DisplayTrap
41 41 from IPython.core.error import UsageError
42 42 from IPython.core.extensions import ExtensionManager
43 43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 44 from IPython.core.inputlist import InputList
45 45 from IPython.core.logger import Logger
46 46 from IPython.core.magic import Magic
47 47 from IPython.core.plugin import PluginManager
48 48 from IPython.core.prefilter import PrefilterManager
49 49 from IPython.core.displayhook import DisplayHook
50 50 import IPython.core.hooks
51 51 from IPython.external.Itpl import ItplNS
52 52 from IPython.utils import PyColorize
53 53 from IPython.utils import pickleshare
54 54 from IPython.utils.doctestreload import doctest_reload
55 55 from IPython.utils.ipstruct import Struct
56 56 import IPython.utils.io
57 57 from IPython.utils.io import ask_yes_no
58 58 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
59 59 from IPython.utils.process import getoutput, getoutputerror
60 60 from IPython.utils.strdispatch import StrDispatch
61 61 from IPython.utils.syspathcontext import prepended_to_syspath
62 62 from IPython.utils.text import num_ini_spaces
63 63 from IPython.utils.warn import warn, error, fatal
64 64 from IPython.utils.traitlets import (
65 65 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance, Type
66 66 )
67 67
68 68 # from IPython.utils import growl
69 69 # growl.start("IPython")
70 70
71 71 #-----------------------------------------------------------------------------
72 72 # Globals
73 73 #-----------------------------------------------------------------------------
74 74
75 75 # compiled regexps for autoindent management
76 76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 77
78 78 #-----------------------------------------------------------------------------
79 79 # Utilities
80 80 #-----------------------------------------------------------------------------
81 81
82 82 # store the builtin raw_input globally, and use this always, in case user code
83 83 # overwrites it (like wx.py.PyShell does)
84 84 raw_input_original = raw_input
85 85
86 86 def softspace(file, newvalue):
87 87 """Copied from code.py, to remove the dependency"""
88 88
89 89 oldvalue = 0
90 90 try:
91 91 oldvalue = file.softspace
92 92 except AttributeError:
93 93 pass
94 94 try:
95 95 file.softspace = newvalue
96 96 except (AttributeError, TypeError):
97 97 # "attribute-less object" or "read-only attributes"
98 98 pass
99 99 return oldvalue
100 100
101 101
102 102 def no_op(*a, **kw): pass
103 103
104 104 class SpaceInInput(exceptions.Exception): pass
105 105
106 106 class Bunch: pass
107 107
108 108
109 109 def get_default_colors():
110 110 if sys.platform=='darwin':
111 111 return "LightBG"
112 112 elif os.name=='nt':
113 113 return 'Linux'
114 114 else:
115 115 return 'Linux'
116 116
117 117
118 118 class SeparateStr(Str):
119 119 """A Str subclass to validate separate_in, separate_out, etc.
120 120
121 121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 122 """
123 123
124 124 def validate(self, obj, value):
125 125 if value == '0': value = ''
126 126 value = value.replace('\\n','\n')
127 127 return super(SeparateStr, self).validate(obj, value)
128 128
129 class MultipleInstanceError(Exception):
130 pass
131
129 132
130 133 #-----------------------------------------------------------------------------
131 134 # Main IPython class
132 135 #-----------------------------------------------------------------------------
133 136
134 137
135 138 class InteractiveShell(Configurable, Magic):
136 139 """An enhanced, interactive shell for Python."""
137 140
138 141 autocall = Enum((0,1,2), default_value=1, config=True)
139 142 # TODO: remove all autoindent logic and put into frontends.
140 143 # We can't do this yet because even runlines uses the autoindent.
141 144 autoindent = CBool(True, config=True)
142 145 automagic = CBool(True, config=True)
143 146 cache_size = Int(1000, config=True)
144 147 color_info = CBool(True, config=True)
145 148 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
146 149 default_value=get_default_colors(), config=True)
147 150 debug = CBool(False, config=True)
148 151 deep_reload = CBool(False, config=True)
149 152 displayhook_class = Type(DisplayHook)
150 153 filename = Str("<ipython console>")
151 154 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
152 155 logstart = CBool(False, config=True)
153 156 logfile = Str('', config=True)
154 157 logappend = Str('', config=True)
155 158 object_info_string_level = Enum((0,1,2), default_value=0,
156 159 config=True)
157 160 pdb = CBool(False, config=True)
158 161 pprint = CBool(True, config=True)
159 162 profile = Str('', config=True)
160 163 prompt_in1 = Str('In [\\#]: ', config=True)
161 164 prompt_in2 = Str(' .\\D.: ', config=True)
162 165 prompt_out = Str('Out[\\#]: ', config=True)
163 166 prompts_pad_left = CBool(True, config=True)
164 167 quiet = CBool(False, config=True)
165 168
166 169 # The readline stuff will eventually be moved to the terminal subclass
167 170 # but for now, we can't do that as readline is welded in everywhere.
168 171 readline_use = CBool(True, config=True)
169 172 readline_merge_completions = CBool(True, config=True)
170 173 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
171 174 readline_remove_delims = Str('-/~', config=True)
172 175 readline_parse_and_bind = List([
173 176 'tab: complete',
174 177 '"\C-l": clear-screen',
175 178 'set show-all-if-ambiguous on',
176 179 '"\C-o": tab-insert',
177 180 '"\M-i": " "',
178 181 '"\M-o": "\d\d\d\d"',
179 182 '"\M-I": "\d\d\d\d"',
180 183 '"\C-r": reverse-search-history',
181 184 '"\C-s": forward-search-history',
182 185 '"\C-p": history-search-backward',
183 186 '"\C-n": history-search-forward',
184 187 '"\e[A": history-search-backward',
185 188 '"\e[B": history-search-forward',
186 189 '"\C-k": kill-line',
187 190 '"\C-u": unix-line-discard',
188 191 ], allow_none=False, config=True)
189 192
190 193 # TODO: this part of prompt management should be moved to the frontends.
191 194 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
192 195 separate_in = SeparateStr('\n', config=True)
193 196 separate_out = SeparateStr('\n', config=True)
194 197 separate_out2 = SeparateStr('\n', config=True)
195 198 system_header = Str('IPython system call: ', config=True)
196 199 system_verbose = CBool(False, config=True)
197 200 wildcards_case_sensitive = CBool(True, config=True)
198 201 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
199 202 default_value='Context', config=True)
200 203
201 204 # Subcomponents of InteractiveShell
202 205 alias_manager = Instance('IPython.core.alias.AliasManager')
203 206 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
204 207 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
205 208 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
206 209 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
207 210 plugin_manager = Instance('IPython.core.plugin.PluginManager')
208 211
209 212 def __init__(self, config=None, ipython_dir=None,
210 213 user_ns=None, user_global_ns=None,
211 214 custom_exceptions=((),None)):
212 215
213 216 # This is where traits with a config_key argument are updated
214 217 # from the values on config.
215 218 super(InteractiveShell, self).__init__(config=config)
216 219
217 220 # These are relatively independent and stateless
218 221 self.init_ipython_dir(ipython_dir)
219 222 self.init_instance_attrs()
220 223
221 224 # Create namespaces (user_ns, user_global_ns, etc.)
222 225 self.init_create_namespaces(user_ns, user_global_ns)
223 226 # This has to be done after init_create_namespaces because it uses
224 227 # something in self.user_ns, but before init_sys_modules, which
225 228 # is the first thing to modify sys.
226 229 self.save_sys_module_state()
227 230 self.init_sys_modules()
228 231
229 232 self.init_history()
230 233 self.init_encoding()
231 234 self.init_prefilter()
232 235
233 236 Magic.__init__(self, self)
234 237
235 238 self.init_syntax_highlighting()
236 239 self.init_hooks()
237 240 self.init_pushd_popd_magic()
238 241 # TODO: init_io() needs to happen before init_traceback handlers
239 242 # because the traceback handlers hardcode the stdout/stderr streams.
240 243 # This logic in in debugger.Pdb and should eventually be changed.
241 244 self.init_io()
242 245 self.init_traceback_handlers(custom_exceptions)
243 246 self.init_user_ns()
244 247 self.init_logger()
245 248 self.init_alias()
246 249 self.init_builtins()
247 250
248 251 # pre_config_initialization
249 252 self.init_shadow_hist()
250 253
251 254 # The next section should contain averything that was in ipmaker.
252 255 self.init_logstart()
253 256
254 257 # The following was in post_config_initialization
255 258 self.init_inspector()
256 259 self.init_readline()
257 260 self.init_prompts()
258 261 self.init_displayhook()
259 262 self.init_reload_doctest()
260 263 self.init_magics()
261 264 self.init_pdb()
262 265 self.init_extension_manager()
263 266 self.init_plugin_manager()
264 267 self.hooks.late_startup_hook()
265 268
266 269 @classmethod
267 270 def instance(cls, *args, **kwargs):
268 271 """Returns a global InteractiveShell instance."""
269 272 if not hasattr(cls, "_instance"):
270 273 cls._instance = cls(*args, **kwargs)
271 print cls
272 print cls._instance
273 274 # Now make sure that the instance will also be returned by
274 275 # the subclasses instance attribute.
275 for subclass in cls.mro():
276 for subclass in cls.mro()[1:]:
276 277 if issubclass(subclass, InteractiveShell):
277 print subclass
278 subclass._instance = cls._instance
278 if not hasattr(subclass, '_instance'):
279 subclass._instance = cls._instance
280 else:
281 raise MultipleInstanceError(
282 'Multiple conflicting subclass of '
283 'InteractiveShell have been created.'
284 )
279 285 return cls._instance
280 286
281 287 @classmethod
282 288 def initialized(cls):
283 289 return hasattr(cls, "_instance")
284 290
285 291 def get_ipython(self):
286 292 """Return the currently running IPython instance."""
287 293 return self
288 294
289 295 #-------------------------------------------------------------------------
290 296 # Trait changed handlers
291 297 #-------------------------------------------------------------------------
292 298
293 299 def _ipython_dir_changed(self, name, new):
294 300 if not os.path.isdir(new):
295 301 os.makedirs(new, mode = 0777)
296 302
297 303 def set_autoindent(self,value=None):
298 304 """Set the autoindent flag, checking for readline support.
299 305
300 306 If called with no arguments, it acts as a toggle."""
301 307
302 308 if not self.has_readline:
303 309 if os.name == 'posix':
304 310 warn("The auto-indent feature requires the readline library")
305 311 self.autoindent = 0
306 312 return
307 313 if value is None:
308 314 self.autoindent = not self.autoindent
309 315 else:
310 316 self.autoindent = value
311 317
312 318 #-------------------------------------------------------------------------
313 319 # init_* methods called by __init__
314 320 #-------------------------------------------------------------------------
315 321
316 322 def init_ipython_dir(self, ipython_dir):
317 323 if ipython_dir is not None:
318 324 self.ipython_dir = ipython_dir
319 325 self.config.Global.ipython_dir = self.ipython_dir
320 326 return
321 327
322 328 if hasattr(self.config.Global, 'ipython_dir'):
323 329 self.ipython_dir = self.config.Global.ipython_dir
324 330 else:
325 331 self.ipython_dir = get_ipython_dir()
326 332
327 333 # All children can just read this
328 334 self.config.Global.ipython_dir = self.ipython_dir
329 335
330 336 def init_instance_attrs(self):
331 337 self.more = False
332 338
333 339 # command compiler
334 340 self.compile = codeop.CommandCompiler()
335 341
336 342 # User input buffer
337 343 self.buffer = []
338 344
339 345 # Make an empty namespace, which extension writers can rely on both
340 346 # existing and NEVER being used by ipython itself. This gives them a
341 347 # convenient location for storing additional information and state
342 348 # their extensions may require, without fear of collisions with other
343 349 # ipython names that may develop later.
344 350 self.meta = Struct()
345 351
346 352 # Object variable to store code object waiting execution. This is
347 353 # used mainly by the multithreaded shells, but it can come in handy in
348 354 # other situations. No need to use a Queue here, since it's a single
349 355 # item which gets cleared once run.
350 356 self.code_to_run = None
351 357
352 358 # Temporary files used for various purposes. Deleted at exit.
353 359 self.tempfiles = []
354 360
355 361 # Keep track of readline usage (later set by init_readline)
356 362 self.has_readline = False
357 363
358 364 # keep track of where we started running (mainly for crash post-mortem)
359 365 # This is not being used anywhere currently.
360 366 self.starting_dir = os.getcwd()
361 367
362 368 # Indentation management
363 369 self.indent_current_nsp = 0
364 370
365 371 def init_encoding(self):
366 372 # Get system encoding at startup time. Certain terminals (like Emacs
367 373 # under Win32 have it set to None, and we need to have a known valid
368 374 # encoding to use in the raw_input() method
369 375 try:
370 376 self.stdin_encoding = sys.stdin.encoding or 'ascii'
371 377 except AttributeError:
372 378 self.stdin_encoding = 'ascii'
373 379
374 380 def init_syntax_highlighting(self):
375 381 # Python source parser/formatter for syntax highlighting
376 382 pyformat = PyColorize.Parser().format
377 383 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
378 384
379 385 def init_pushd_popd_magic(self):
380 386 # for pushd/popd management
381 387 try:
382 388 self.home_dir = get_home_dir()
383 389 except HomeDirError, msg:
384 390 fatal(msg)
385 391
386 392 self.dir_stack = []
387 393
388 394 def init_logger(self):
389 395 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
390 396 # local shortcut, this is used a LOT
391 397 self.log = self.logger.log
392 398
393 399 def init_logstart(self):
394 400 if self.logappend:
395 401 self.magic_logstart(self.logappend + ' append')
396 402 elif self.logfile:
397 403 self.magic_logstart(self.logfile)
398 404 elif self.logstart:
399 405 self.magic_logstart()
400 406
401 407 def init_builtins(self):
402 408 self.builtin_trap = BuiltinTrap(shell=self)
403 409
404 410 def init_inspector(self):
405 411 # Object inspector
406 412 self.inspector = oinspect.Inspector(oinspect.InspectColors,
407 413 PyColorize.ANSICodeColors,
408 414 'NoColor',
409 415 self.object_info_string_level)
410 416
411 417 def init_io(self):
412 418 import IPython.utils.io
413 419 if sys.platform == 'win32' and readline.have_readline and \
414 420 self.readline_use:
415 421 Term = IPython.utils.io.IOTerm(
416 422 cout=readline._outputfile,cerr=readline._outputfile
417 423 )
418 424 else:
419 425 Term = IPython.utils.io.IOTerm()
420 426 IPython.utils.io.Term = Term
421 427
422 428 def init_prompts(self):
423 429 # TODO: This is a pass for now because the prompts are managed inside
424 430 # the DisplayHook. Once there is a separate prompt manager, this
425 431 # will initialize that object and all prompt related information.
426 432 pass
427 433
428 434 def init_displayhook(self):
429 435 # Initialize displayhook, set in/out prompts and printing system
430 436 self.displayhook = self.displayhook_class(
431 437 shell=self,
432 438 cache_size=self.cache_size,
433 439 input_sep = self.separate_in,
434 440 output_sep = self.separate_out,
435 441 output_sep2 = self.separate_out2,
436 442 ps1 = self.prompt_in1,
437 443 ps2 = self.prompt_in2,
438 444 ps_out = self.prompt_out,
439 445 pad_left = self.prompts_pad_left
440 446 )
441 447 # This is a context manager that installs/revmoes the displayhook at
442 448 # the appropriate time.
443 449 self.display_trap = DisplayTrap(hook=self.displayhook)
444 450
445 451 def init_reload_doctest(self):
446 452 # Do a proper resetting of doctest, including the necessary displayhook
447 453 # monkeypatching
448 454 try:
449 455 doctest_reload()
450 456 except ImportError:
451 457 warn("doctest module does not exist.")
452 458
453 459 #-------------------------------------------------------------------------
454 460 # Things related to injections into the sys module
455 461 #-------------------------------------------------------------------------
456 462
457 463 def save_sys_module_state(self):
458 464 """Save the state of hooks in the sys module.
459 465
460 466 This has to be called after self.user_ns is created.
461 467 """
462 468 self._orig_sys_module_state = {}
463 469 self._orig_sys_module_state['stdin'] = sys.stdin
464 470 self._orig_sys_module_state['stdout'] = sys.stdout
465 471 self._orig_sys_module_state['stderr'] = sys.stderr
466 472 self._orig_sys_module_state['excepthook'] = sys.excepthook
467 473 try:
468 474 self._orig_sys_modules_main_name = self.user_ns['__name__']
469 475 except KeyError:
470 476 pass
471 477
472 478 def restore_sys_module_state(self):
473 479 """Restore the state of the sys module."""
474 480 try:
475 481 for k, v in self._orig_sys_module_state.items():
476 482 setattr(sys, k, v)
477 483 except AttributeError:
478 484 pass
479 485 try:
480 486 delattr(sys, 'ipcompleter')
481 487 except AttributeError:
482 488 pass
483 489 # Reset what what done in self.init_sys_modules
484 490 try:
485 491 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
486 492 except (AttributeError, KeyError):
487 493 pass
488 494
489 495 #-------------------------------------------------------------------------
490 496 # Things related to hooks
491 497 #-------------------------------------------------------------------------
492 498
493 499 def init_hooks(self):
494 500 # hooks holds pointers used for user-side customizations
495 501 self.hooks = Struct()
496 502
497 503 self.strdispatchers = {}
498 504
499 505 # Set all default hooks, defined in the IPython.hooks module.
500 506 hooks = IPython.core.hooks
501 507 for hook_name in hooks.__all__:
502 508 # default hooks have priority 100, i.e. low; user hooks should have
503 509 # 0-100 priority
504 510 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
505 511
506 512 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
507 513 """set_hook(name,hook) -> sets an internal IPython hook.
508 514
509 515 IPython exposes some of its internal API as user-modifiable hooks. By
510 516 adding your function to one of these hooks, you can modify IPython's
511 517 behavior to call at runtime your own routines."""
512 518
513 519 # At some point in the future, this should validate the hook before it
514 520 # accepts it. Probably at least check that the hook takes the number
515 521 # of args it's supposed to.
516 522
517 523 f = new.instancemethod(hook,self,self.__class__)
518 524
519 525 # check if the hook is for strdispatcher first
520 526 if str_key is not None:
521 527 sdp = self.strdispatchers.get(name, StrDispatch())
522 528 sdp.add_s(str_key, f, priority )
523 529 self.strdispatchers[name] = sdp
524 530 return
525 531 if re_key is not None:
526 532 sdp = self.strdispatchers.get(name, StrDispatch())
527 533 sdp.add_re(re.compile(re_key), f, priority )
528 534 self.strdispatchers[name] = sdp
529 535 return
530 536
531 537 dp = getattr(self.hooks, name, None)
532 538 if name not in IPython.core.hooks.__all__:
533 539 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
534 540 if not dp:
535 541 dp = IPython.core.hooks.CommandChainDispatcher()
536 542
537 543 try:
538 544 dp.add(f,priority)
539 545 except AttributeError:
540 546 # it was not commandchain, plain old func - replace
541 547 dp = f
542 548
543 549 setattr(self.hooks,name, dp)
544 550
545 551 #-------------------------------------------------------------------------
546 552 # Things related to the "main" module
547 553 #-------------------------------------------------------------------------
548 554
549 555 def new_main_mod(self,ns=None):
550 556 """Return a new 'main' module object for user code execution.
551 557 """
552 558 main_mod = self._user_main_module
553 559 init_fakemod_dict(main_mod,ns)
554 560 return main_mod
555 561
556 562 def cache_main_mod(self,ns,fname):
557 563 """Cache a main module's namespace.
558 564
559 565 When scripts are executed via %run, we must keep a reference to the
560 566 namespace of their __main__ module (a FakeModule instance) around so
561 567 that Python doesn't clear it, rendering objects defined therein
562 568 useless.
563 569
564 570 This method keeps said reference in a private dict, keyed by the
565 571 absolute path of the module object (which corresponds to the script
566 572 path). This way, for multiple executions of the same script we only
567 573 keep one copy of the namespace (the last one), thus preventing memory
568 574 leaks from old references while allowing the objects from the last
569 575 execution to be accessible.
570 576
571 577 Note: we can not allow the actual FakeModule instances to be deleted,
572 578 because of how Python tears down modules (it hard-sets all their
573 579 references to None without regard for reference counts). This method
574 580 must therefore make a *copy* of the given namespace, to allow the
575 581 original module's __dict__ to be cleared and reused.
576 582
577 583
578 584 Parameters
579 585 ----------
580 586 ns : a namespace (a dict, typically)
581 587
582 588 fname : str
583 589 Filename associated with the namespace.
584 590
585 591 Examples
586 592 --------
587 593
588 594 In [10]: import IPython
589 595
590 596 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
591 597
592 598 In [12]: IPython.__file__ in _ip._main_ns_cache
593 599 Out[12]: True
594 600 """
595 601 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
596 602
597 603 def clear_main_mod_cache(self):
598 604 """Clear the cache of main modules.
599 605
600 606 Mainly for use by utilities like %reset.
601 607
602 608 Examples
603 609 --------
604 610
605 611 In [15]: import IPython
606 612
607 613 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
608 614
609 615 In [17]: len(_ip._main_ns_cache) > 0
610 616 Out[17]: True
611 617
612 618 In [18]: _ip.clear_main_mod_cache()
613 619
614 620 In [19]: len(_ip._main_ns_cache) == 0
615 621 Out[19]: True
616 622 """
617 623 self._main_ns_cache.clear()
618 624
619 625 #-------------------------------------------------------------------------
620 626 # Things related to debugging
621 627 #-------------------------------------------------------------------------
622 628
623 629 def init_pdb(self):
624 630 # Set calling of pdb on exceptions
625 631 # self.call_pdb is a property
626 632 self.call_pdb = self.pdb
627 633
628 634 def _get_call_pdb(self):
629 635 return self._call_pdb
630 636
631 637 def _set_call_pdb(self,val):
632 638
633 639 if val not in (0,1,False,True):
634 640 raise ValueError,'new call_pdb value must be boolean'
635 641
636 642 # store value in instance
637 643 self._call_pdb = val
638 644
639 645 # notify the actual exception handlers
640 646 self.InteractiveTB.call_pdb = val
641 647
642 648 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
643 649 'Control auto-activation of pdb at exceptions')
644 650
645 651 def debugger(self,force=False):
646 652 """Call the pydb/pdb debugger.
647 653
648 654 Keywords:
649 655
650 656 - force(False): by default, this routine checks the instance call_pdb
651 657 flag and does not actually invoke the debugger if the flag is false.
652 658 The 'force' option forces the debugger to activate even if the flag
653 659 is false.
654 660 """
655 661
656 662 if not (force or self.call_pdb):
657 663 return
658 664
659 665 if not hasattr(sys,'last_traceback'):
660 666 error('No traceback has been produced, nothing to debug.')
661 667 return
662 668
663 669 # use pydb if available
664 670 if debugger.has_pydb:
665 671 from pydb import pm
666 672 else:
667 673 # fallback to our internal debugger
668 674 pm = lambda : self.InteractiveTB.debugger(force=True)
669 675 self.history_saving_wrapper(pm)()
670 676
671 677 #-------------------------------------------------------------------------
672 678 # Things related to IPython's various namespaces
673 679 #-------------------------------------------------------------------------
674 680
675 681 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
676 682 # Create the namespace where the user will operate. user_ns is
677 683 # normally the only one used, and it is passed to the exec calls as
678 684 # the locals argument. But we do carry a user_global_ns namespace
679 685 # given as the exec 'globals' argument, This is useful in embedding
680 686 # situations where the ipython shell opens in a context where the
681 687 # distinction between locals and globals is meaningful. For
682 688 # non-embedded contexts, it is just the same object as the user_ns dict.
683 689
684 690 # FIXME. For some strange reason, __builtins__ is showing up at user
685 691 # level as a dict instead of a module. This is a manual fix, but I
686 692 # should really track down where the problem is coming from. Alex
687 693 # Schmolck reported this problem first.
688 694
689 695 # A useful post by Alex Martelli on this topic:
690 696 # Re: inconsistent value from __builtins__
691 697 # Von: Alex Martelli <aleaxit@yahoo.com>
692 698 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
693 699 # Gruppen: comp.lang.python
694 700
695 701 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
696 702 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
697 703 # > <type 'dict'>
698 704 # > >>> print type(__builtins__)
699 705 # > <type 'module'>
700 706 # > Is this difference in return value intentional?
701 707
702 708 # Well, it's documented that '__builtins__' can be either a dictionary
703 709 # or a module, and it's been that way for a long time. Whether it's
704 710 # intentional (or sensible), I don't know. In any case, the idea is
705 711 # that if you need to access the built-in namespace directly, you
706 712 # should start with "import __builtin__" (note, no 's') which will
707 713 # definitely give you a module. Yeah, it's somewhat confusing:-(.
708 714
709 715 # These routines return properly built dicts as needed by the rest of
710 716 # the code, and can also be used by extension writers to generate
711 717 # properly initialized namespaces.
712 718 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
713 719
714 720 # Assign namespaces
715 721 # This is the namespace where all normal user variables live
716 722 self.user_ns = user_ns
717 723 self.user_global_ns = user_global_ns
718 724
719 725 # An auxiliary namespace that checks what parts of the user_ns were
720 726 # loaded at startup, so we can list later only variables defined in
721 727 # actual interactive use. Since it is always a subset of user_ns, it
722 728 # doesn't need to be separately tracked in the ns_table.
723 729 self.user_ns_hidden = {}
724 730
725 731 # A namespace to keep track of internal data structures to prevent
726 732 # them from cluttering user-visible stuff. Will be updated later
727 733 self.internal_ns = {}
728 734
729 735 # Now that FakeModule produces a real module, we've run into a nasty
730 736 # problem: after script execution (via %run), the module where the user
731 737 # code ran is deleted. Now that this object is a true module (needed
732 738 # so docetst and other tools work correctly), the Python module
733 739 # teardown mechanism runs over it, and sets to None every variable
734 740 # present in that module. Top-level references to objects from the
735 741 # script survive, because the user_ns is updated with them. However,
736 742 # calling functions defined in the script that use other things from
737 743 # the script will fail, because the function's closure had references
738 744 # to the original objects, which are now all None. So we must protect
739 745 # these modules from deletion by keeping a cache.
740 746 #
741 747 # To avoid keeping stale modules around (we only need the one from the
742 748 # last run), we use a dict keyed with the full path to the script, so
743 749 # only the last version of the module is held in the cache. Note,
744 750 # however, that we must cache the module *namespace contents* (their
745 751 # __dict__). Because if we try to cache the actual modules, old ones
746 752 # (uncached) could be destroyed while still holding references (such as
747 753 # those held by GUI objects that tend to be long-lived)>
748 754 #
749 755 # The %reset command will flush this cache. See the cache_main_mod()
750 756 # and clear_main_mod_cache() methods for details on use.
751 757
752 758 # This is the cache used for 'main' namespaces
753 759 self._main_ns_cache = {}
754 760 # And this is the single instance of FakeModule whose __dict__ we keep
755 761 # copying and clearing for reuse on each %run
756 762 self._user_main_module = FakeModule()
757 763
758 764 # A table holding all the namespaces IPython deals with, so that
759 765 # introspection facilities can search easily.
760 766 self.ns_table = {'user':user_ns,
761 767 'user_global':user_global_ns,
762 768 'internal':self.internal_ns,
763 769 'builtin':__builtin__.__dict__
764 770 }
765 771
766 772 # Similarly, track all namespaces where references can be held and that
767 773 # we can safely clear (so it can NOT include builtin). This one can be
768 774 # a simple list.
769 775 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
770 776 self.internal_ns, self._main_ns_cache ]
771 777
772 778 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
773 779 """Return a valid local and global user interactive namespaces.
774 780
775 781 This builds a dict with the minimal information needed to operate as a
776 782 valid IPython user namespace, which you can pass to the various
777 783 embedding classes in ipython. The default implementation returns the
778 784 same dict for both the locals and the globals to allow functions to
779 785 refer to variables in the namespace. Customized implementations can
780 786 return different dicts. The locals dictionary can actually be anything
781 787 following the basic mapping protocol of a dict, but the globals dict
782 788 must be a true dict, not even a subclass. It is recommended that any
783 789 custom object for the locals namespace synchronize with the globals
784 790 dict somehow.
785 791
786 792 Raises TypeError if the provided globals namespace is not a true dict.
787 793
788 794 Parameters
789 795 ----------
790 796 user_ns : dict-like, optional
791 797 The current user namespace. The items in this namespace should
792 798 be included in the output. If None, an appropriate blank
793 799 namespace should be created.
794 800 user_global_ns : dict, optional
795 801 The current user global namespace. The items in this namespace
796 802 should be included in the output. If None, an appropriate
797 803 blank namespace should be created.
798 804
799 805 Returns
800 806 -------
801 807 A pair of dictionary-like object to be used as the local namespace
802 808 of the interpreter and a dict to be used as the global namespace.
803 809 """
804 810
805 811
806 812 # We must ensure that __builtin__ (without the final 's') is always
807 813 # available and pointing to the __builtin__ *module*. For more details:
808 814 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
809 815
810 816 if user_ns is None:
811 817 # Set __name__ to __main__ to better match the behavior of the
812 818 # normal interpreter.
813 819 user_ns = {'__name__' :'__main__',
814 820 '__builtin__' : __builtin__,
815 821 '__builtins__' : __builtin__,
816 822 }
817 823 else:
818 824 user_ns.setdefault('__name__','__main__')
819 825 user_ns.setdefault('__builtin__',__builtin__)
820 826 user_ns.setdefault('__builtins__',__builtin__)
821 827
822 828 if user_global_ns is None:
823 829 user_global_ns = user_ns
824 830 if type(user_global_ns) is not dict:
825 831 raise TypeError("user_global_ns must be a true dict; got %r"
826 832 % type(user_global_ns))
827 833
828 834 return user_ns, user_global_ns
829 835
830 836 def init_sys_modules(self):
831 837 # We need to insert into sys.modules something that looks like a
832 838 # module but which accesses the IPython namespace, for shelve and
833 839 # pickle to work interactively. Normally they rely on getting
834 840 # everything out of __main__, but for embedding purposes each IPython
835 841 # instance has its own private namespace, so we can't go shoving
836 842 # everything into __main__.
837 843
838 844 # note, however, that we should only do this for non-embedded
839 845 # ipythons, which really mimic the __main__.__dict__ with their own
840 846 # namespace. Embedded instances, on the other hand, should not do
841 847 # this because they need to manage the user local/global namespaces
842 848 # only, but they live within a 'normal' __main__ (meaning, they
843 849 # shouldn't overtake the execution environment of the script they're
844 850 # embedded in).
845 851
846 852 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
847 853
848 854 try:
849 855 main_name = self.user_ns['__name__']
850 856 except KeyError:
851 857 raise KeyError('user_ns dictionary MUST have a "__name__" key')
852 858 else:
853 859 sys.modules[main_name] = FakeModule(self.user_ns)
854 860
855 861 def init_user_ns(self):
856 862 """Initialize all user-visible namespaces to their minimum defaults.
857 863
858 864 Certain history lists are also initialized here, as they effectively
859 865 act as user namespaces.
860 866
861 867 Notes
862 868 -----
863 869 All data structures here are only filled in, they are NOT reset by this
864 870 method. If they were not empty before, data will simply be added to
865 871 therm.
866 872 """
867 873 # This function works in two parts: first we put a few things in
868 874 # user_ns, and we sync that contents into user_ns_hidden so that these
869 875 # initial variables aren't shown by %who. After the sync, we add the
870 876 # rest of what we *do* want the user to see with %who even on a new
871 877 # session (probably nothing, so theye really only see their own stuff)
872 878
873 879 # The user dict must *always* have a __builtin__ reference to the
874 880 # Python standard __builtin__ namespace, which must be imported.
875 881 # This is so that certain operations in prompt evaluation can be
876 882 # reliably executed with builtins. Note that we can NOT use
877 883 # __builtins__ (note the 's'), because that can either be a dict or a
878 884 # module, and can even mutate at runtime, depending on the context
879 885 # (Python makes no guarantees on it). In contrast, __builtin__ is
880 886 # always a module object, though it must be explicitly imported.
881 887
882 888 # For more details:
883 889 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
884 890 ns = dict(__builtin__ = __builtin__)
885 891
886 892 # Put 'help' in the user namespace
887 893 try:
888 894 from site import _Helper
889 895 ns['help'] = _Helper()
890 896 except ImportError:
891 897 warn('help() not available - check site.py')
892 898
893 899 # make global variables for user access to the histories
894 900 ns['_ih'] = self.input_hist
895 901 ns['_oh'] = self.output_hist
896 902 ns['_dh'] = self.dir_hist
897 903
898 904 ns['_sh'] = shadowns
899 905
900 906 # user aliases to input and output histories. These shouldn't show up
901 907 # in %who, as they can have very large reprs.
902 908 ns['In'] = self.input_hist
903 909 ns['Out'] = self.output_hist
904 910
905 911 # Store myself as the public api!!!
906 912 ns['get_ipython'] = self.get_ipython
907 913
908 914 # Sync what we've added so far to user_ns_hidden so these aren't seen
909 915 # by %who
910 916 self.user_ns_hidden.update(ns)
911 917
912 918 # Anything put into ns now would show up in %who. Think twice before
913 919 # putting anything here, as we really want %who to show the user their
914 920 # stuff, not our variables.
915 921
916 922 # Finally, update the real user's namespace
917 923 self.user_ns.update(ns)
918 924
919 925
920 926 def reset(self):
921 927 """Clear all internal namespaces.
922 928
923 929 Note that this is much more aggressive than %reset, since it clears
924 930 fully all namespaces, as well as all input/output lists.
925 931 """
926 932 for ns in self.ns_refs_table:
927 933 ns.clear()
928 934
929 935 self.alias_manager.clear_aliases()
930 936
931 937 # Clear input and output histories
932 938 self.input_hist[:] = []
933 939 self.input_hist_raw[:] = []
934 940 self.output_hist.clear()
935 941
936 942 # Restore the user namespaces to minimal usability
937 943 self.init_user_ns()
938 944
939 945 # Restore the default and user aliases
940 946 self.alias_manager.init_aliases()
941 947
942 948 def reset_selective(self, regex=None):
943 949 """Clear selective variables from internal namespaces based on a specified regular expression.
944 950
945 951 Parameters
946 952 ----------
947 953 regex : string or compiled pattern, optional
948 954 A regular expression pattern that will be used in searching variable names in the users
949 955 namespaces.
950 956 """
951 957 if regex is not None:
952 958 try:
953 959 m = re.compile(regex)
954 960 except TypeError:
955 961 raise TypeError('regex must be a string or compiled pattern')
956 962 # Search for keys in each namespace that match the given regex
957 963 # If a match is found, delete the key/value pair.
958 964 for ns in self.ns_refs_table:
959 965 for var in ns:
960 966 if m.search(var):
961 967 del ns[var]
962 968
963 969 def push(self, variables, interactive=True):
964 970 """Inject a group of variables into the IPython user namespace.
965 971
966 972 Parameters
967 973 ----------
968 974 variables : dict, str or list/tuple of str
969 975 The variables to inject into the user's namespace. If a dict,
970 976 a simple update is done. If a str, the string is assumed to
971 977 have variable names separated by spaces. A list/tuple of str
972 978 can also be used to give the variable names. If just the variable
973 979 names are give (list/tuple/str) then the variable values looked
974 980 up in the callers frame.
975 981 interactive : bool
976 982 If True (default), the variables will be listed with the ``who``
977 983 magic.
978 984 """
979 985 vdict = None
980 986
981 987 # We need a dict of name/value pairs to do namespace updates.
982 988 if isinstance(variables, dict):
983 989 vdict = variables
984 990 elif isinstance(variables, (basestring, list, tuple)):
985 991 if isinstance(variables, basestring):
986 992 vlist = variables.split()
987 993 else:
988 994 vlist = variables
989 995 vdict = {}
990 996 cf = sys._getframe(1)
991 997 for name in vlist:
992 998 try:
993 999 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
994 1000 except:
995 1001 print ('Could not get variable %s from %s' %
996 1002 (name,cf.f_code.co_name))
997 1003 else:
998 1004 raise ValueError('variables must be a dict/str/list/tuple')
999 1005
1000 1006 # Propagate variables to user namespace
1001 1007 self.user_ns.update(vdict)
1002 1008
1003 1009 # And configure interactive visibility
1004 1010 config_ns = self.user_ns_hidden
1005 1011 if interactive:
1006 1012 for name, val in vdict.iteritems():
1007 1013 config_ns.pop(name, None)
1008 1014 else:
1009 1015 for name,val in vdict.iteritems():
1010 1016 config_ns[name] = val
1011 1017
1012 1018 #-------------------------------------------------------------------------
1013 1019 # Things related to history management
1014 1020 #-------------------------------------------------------------------------
1015 1021
1016 1022 def init_history(self):
1017 1023 # List of input with multi-line handling.
1018 1024 self.input_hist = InputList()
1019 1025 # This one will hold the 'raw' input history, without any
1020 1026 # pre-processing. This will allow users to retrieve the input just as
1021 1027 # it was exactly typed in by the user, with %hist -r.
1022 1028 self.input_hist_raw = InputList()
1023 1029
1024 1030 # list of visited directories
1025 1031 try:
1026 1032 self.dir_hist = [os.getcwd()]
1027 1033 except OSError:
1028 1034 self.dir_hist = []
1029 1035
1030 1036 # dict of output history
1031 1037 self.output_hist = {}
1032 1038
1033 1039 # Now the history file
1034 1040 if self.profile:
1035 1041 histfname = 'history-%s' % self.profile
1036 1042 else:
1037 1043 histfname = 'history'
1038 1044 self.histfile = os.path.join(self.ipython_dir, histfname)
1039 1045
1040 1046 # Fill the history zero entry, user counter starts at 1
1041 1047 self.input_hist.append('\n')
1042 1048 self.input_hist_raw.append('\n')
1043 1049
1044 1050 def init_shadow_hist(self):
1045 1051 try:
1046 1052 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1047 1053 except exceptions.UnicodeDecodeError:
1048 1054 print "Your ipython_dir can't be decoded to unicode!"
1049 1055 print "Please set HOME environment variable to something that"
1050 1056 print r"only has ASCII characters, e.g. c:\home"
1051 1057 print "Now it is", self.ipython_dir
1052 1058 sys.exit()
1053 1059 self.shadowhist = ipcorehist.ShadowHist(self.db)
1054 1060
1055 1061 def savehist(self):
1056 1062 """Save input history to a file (via readline library)."""
1057 1063
1058 1064 try:
1059 1065 self.readline.write_history_file(self.histfile)
1060 1066 except:
1061 1067 print 'Unable to save IPython command history to file: ' + \
1062 1068 `self.histfile`
1063 1069
1064 1070 def reloadhist(self):
1065 1071 """Reload the input history from disk file."""
1066 1072
1067 1073 try:
1068 1074 self.readline.clear_history()
1069 1075 self.readline.read_history_file(self.shell.histfile)
1070 1076 except AttributeError:
1071 1077 pass
1072 1078
1073 1079 def history_saving_wrapper(self, func):
1074 1080 """ Wrap func for readline history saving
1075 1081
1076 1082 Convert func into callable that saves & restores
1077 1083 history around the call """
1078 1084
1079 1085 if self.has_readline:
1080 1086 from IPython.utils import rlineimpl as readline
1081 1087 else:
1082 1088 return func
1083 1089
1084 1090 def wrapper():
1085 1091 self.savehist()
1086 1092 try:
1087 1093 func()
1088 1094 finally:
1089 1095 readline.read_history_file(self.histfile)
1090 1096 return wrapper
1091 1097
1092 1098 def get_history(self, index=None, raw=False, output=True):
1093 1099 """Get the history list.
1094 1100
1095 1101 Get the input and output history.
1096 1102
1097 1103 Parameters
1098 1104 ----------
1099 1105 index : n or (n1, n2) or None
1100 1106 If n, then the last entries. If a tuple, then all in
1101 1107 range(n1, n2). If None, then all entries. Raises IndexError if
1102 1108 the format of index is incorrect.
1103 1109 raw : bool
1104 1110 If True, return the raw input.
1105 1111 output : bool
1106 1112 If True, then return the output as well.
1107 1113
1108 1114 Returns
1109 1115 -------
1110 1116 If output is True, then return a dict of tuples, keyed by the prompt
1111 1117 numbers and with values of (input, output). If output is False, then
1112 1118 a dict, keyed by the prompt number with the values of input. Raises
1113 1119 IndexError if no history is found.
1114 1120 """
1115 1121 if raw:
1116 1122 input_hist = self.input_hist_raw
1117 1123 else:
1118 1124 input_hist = self.input_hist
1119 1125 if output:
1120 1126 output_hist = self.user_ns['Out']
1121 1127 n = len(input_hist)
1122 1128 if index is None:
1123 1129 start=0; stop=n
1124 1130 elif isinstance(index, int):
1125 1131 start=n-index; stop=n
1126 1132 elif isinstance(index, tuple) and len(index) == 2:
1127 1133 start=index[0]; stop=index[1]
1128 1134 else:
1129 1135 raise IndexError('Not a valid index for the input history: %r' % index)
1130 1136 hist = {}
1131 1137 for i in range(start, stop):
1132 1138 if output:
1133 1139 hist[i] = (input_hist[i], output_hist.get(i))
1134 1140 else:
1135 1141 hist[i] = input_hist[i]
1136 1142 if len(hist)==0:
1137 1143 raise IndexError('No history for range of indices: %r' % index)
1138 1144 return hist
1139 1145
1140 1146 #-------------------------------------------------------------------------
1141 1147 # Things related to exception handling and tracebacks (not debugging)
1142 1148 #-------------------------------------------------------------------------
1143 1149
1144 1150 def init_traceback_handlers(self, custom_exceptions):
1145 1151 # Syntax error handler.
1146 1152 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1147 1153
1148 1154 # The interactive one is initialized with an offset, meaning we always
1149 1155 # want to remove the topmost item in the traceback, which is our own
1150 1156 # internal code. Valid modes: ['Plain','Context','Verbose']
1151 1157 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1152 1158 color_scheme='NoColor',
1153 1159 tb_offset = 1)
1154 1160
1155 1161 # The instance will store a pointer to the system-wide exception hook,
1156 1162 # so that runtime code (such as magics) can access it. This is because
1157 1163 # during the read-eval loop, it may get temporarily overwritten.
1158 1164 self.sys_excepthook = sys.excepthook
1159 1165
1160 1166 # and add any custom exception handlers the user may have specified
1161 1167 self.set_custom_exc(*custom_exceptions)
1162 1168
1163 1169 # Set the exception mode
1164 1170 self.InteractiveTB.set_mode(mode=self.xmode)
1165 1171
1166 1172 def set_custom_exc(self,exc_tuple,handler):
1167 1173 """set_custom_exc(exc_tuple,handler)
1168 1174
1169 1175 Set a custom exception handler, which will be called if any of the
1170 1176 exceptions in exc_tuple occur in the mainloop (specifically, in the
1171 1177 runcode() method.
1172 1178
1173 1179 Inputs:
1174 1180
1175 1181 - exc_tuple: a *tuple* of valid exceptions to call the defined
1176 1182 handler for. It is very important that you use a tuple, and NOT A
1177 1183 LIST here, because of the way Python's except statement works. If
1178 1184 you only want to trap a single exception, use a singleton tuple:
1179 1185
1180 1186 exc_tuple == (MyCustomException,)
1181 1187
1182 1188 - handler: this must be defined as a function with the following
1183 1189 basic interface: def my_handler(self,etype,value,tb).
1184 1190
1185 1191 This will be made into an instance method (via new.instancemethod)
1186 1192 of IPython itself, and it will be called if any of the exceptions
1187 1193 listed in the exc_tuple are caught. If the handler is None, an
1188 1194 internal basic one is used, which just prints basic info.
1189 1195
1190 1196 WARNING: by putting in your own exception handler into IPython's main
1191 1197 execution loop, you run a very good chance of nasty crashes. This
1192 1198 facility should only be used if you really know what you are doing."""
1193 1199
1194 1200 assert type(exc_tuple)==type(()) , \
1195 1201 "The custom exceptions must be given AS A TUPLE."
1196 1202
1197 1203 def dummy_handler(self,etype,value,tb):
1198 1204 print '*** Simple custom exception handler ***'
1199 1205 print 'Exception type :',etype
1200 1206 print 'Exception value:',value
1201 1207 print 'Traceback :',tb
1202 1208 print 'Source code :','\n'.join(self.buffer)
1203 1209
1204 1210 if handler is None: handler = dummy_handler
1205 1211
1206 1212 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1207 1213 self.custom_exceptions = exc_tuple
1208 1214
1209 1215 def excepthook(self, etype, value, tb):
1210 1216 """One more defense for GUI apps that call sys.excepthook.
1211 1217
1212 1218 GUI frameworks like wxPython trap exceptions and call
1213 1219 sys.excepthook themselves. I guess this is a feature that
1214 1220 enables them to keep running after exceptions that would
1215 1221 otherwise kill their mainloop. This is a bother for IPython
1216 1222 which excepts to catch all of the program exceptions with a try:
1217 1223 except: statement.
1218 1224
1219 1225 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1220 1226 any app directly invokes sys.excepthook, it will look to the user like
1221 1227 IPython crashed. In order to work around this, we can disable the
1222 1228 CrashHandler and replace it with this excepthook instead, which prints a
1223 1229 regular traceback using our InteractiveTB. In this fashion, apps which
1224 1230 call sys.excepthook will generate a regular-looking exception from
1225 1231 IPython, and the CrashHandler will only be triggered by real IPython
1226 1232 crashes.
1227 1233
1228 1234 This hook should be used sparingly, only in places which are not likely
1229 1235 to be true IPython errors.
1230 1236 """
1231 1237 self.showtraceback((etype,value,tb),tb_offset=0)
1232 1238
1233 1239 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1234 1240 exception_only=False):
1235 1241 """Display the exception that just occurred.
1236 1242
1237 1243 If nothing is known about the exception, this is the method which
1238 1244 should be used throughout the code for presenting user tracebacks,
1239 1245 rather than directly invoking the InteractiveTB object.
1240 1246
1241 1247 A specific showsyntaxerror() also exists, but this method can take
1242 1248 care of calling it if needed, so unless you are explicitly catching a
1243 1249 SyntaxError exception, don't try to analyze the stack manually and
1244 1250 simply call this method."""
1245 1251
1246 1252 try:
1247 1253 if exc_tuple is None:
1248 1254 etype, value, tb = sys.exc_info()
1249 1255 else:
1250 1256 etype, value, tb = exc_tuple
1251 1257
1252 1258 if etype is None:
1253 1259 if hasattr(sys, 'last_type'):
1254 1260 etype, value, tb = sys.last_type, sys.last_value, \
1255 1261 sys.last_traceback
1256 1262 else:
1257 1263 self.write('No traceback available to show.\n')
1258 1264 return
1259 1265
1260 1266 if etype is SyntaxError:
1261 1267 # Though this won't be called by syntax errors in the input
1262 1268 # line, there may be SyntaxError cases whith imported code.
1263 1269 self.showsyntaxerror(filename)
1264 1270 elif etype is UsageError:
1265 1271 print "UsageError:", value
1266 1272 else:
1267 1273 # WARNING: these variables are somewhat deprecated and not
1268 1274 # necessarily safe to use in a threaded environment, but tools
1269 1275 # like pdb depend on their existence, so let's set them. If we
1270 1276 # find problems in the field, we'll need to revisit their use.
1271 1277 sys.last_type = etype
1272 1278 sys.last_value = value
1273 1279 sys.last_traceback = tb
1274 1280
1275 1281 if etype in self.custom_exceptions:
1276 1282 self.CustomTB(etype,value,tb)
1277 1283 else:
1278 1284 if exception_only:
1279 1285 m = ('An exception has occurred, use %tb to see the '
1280 1286 'full traceback.')
1281 1287 print m
1282 1288 self.InteractiveTB.show_exception_only(etype, value)
1283 1289 else:
1284 1290 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1285 1291 if self.InteractiveTB.call_pdb:
1286 1292 # pdb mucks up readline, fix it back
1287 1293 self.set_completer()
1288 1294
1289 1295 except KeyboardInterrupt:
1290 1296 self.write("\nKeyboardInterrupt\n")
1291 1297
1292 1298
1293 1299 def showsyntaxerror(self, filename=None):
1294 1300 """Display the syntax error that just occurred.
1295 1301
1296 1302 This doesn't display a stack trace because there isn't one.
1297 1303
1298 1304 If a filename is given, it is stuffed in the exception instead
1299 1305 of what was there before (because Python's parser always uses
1300 1306 "<string>" when reading from a string).
1301 1307 """
1302 1308 etype, value, last_traceback = sys.exc_info()
1303 1309
1304 1310 # See note about these variables in showtraceback() above
1305 1311 sys.last_type = etype
1306 1312 sys.last_value = value
1307 1313 sys.last_traceback = last_traceback
1308 1314
1309 1315 if filename and etype is SyntaxError:
1310 1316 # Work hard to stuff the correct filename in the exception
1311 1317 try:
1312 1318 msg, (dummy_filename, lineno, offset, line) = value
1313 1319 except:
1314 1320 # Not the format we expect; leave it alone
1315 1321 pass
1316 1322 else:
1317 1323 # Stuff in the right filename
1318 1324 try:
1319 1325 # Assume SyntaxError is a class exception
1320 1326 value = SyntaxError(msg, (filename, lineno, offset, line))
1321 1327 except:
1322 1328 # If that failed, assume SyntaxError is a string
1323 1329 value = msg, (filename, lineno, offset, line)
1324 1330 self.SyntaxTB(etype,value,[])
1325 1331
1326 1332 #-------------------------------------------------------------------------
1327 1333 # Things related to tab completion
1328 1334 #-------------------------------------------------------------------------
1329 1335
1330 1336 def complete(self, text):
1331 1337 """Return a sorted list of all possible completions on text.
1332 1338
1333 1339 Inputs:
1334 1340
1335 1341 - text: a string of text to be completed on.
1336 1342
1337 1343 This is a wrapper around the completion mechanism, similar to what
1338 1344 readline does at the command line when the TAB key is hit. By
1339 1345 exposing it as a method, it can be used by other non-readline
1340 1346 environments (such as GUIs) for text completion.
1341 1347
1342 1348 Simple usage example:
1343 1349
1344 1350 In [7]: x = 'hello'
1345 1351
1346 1352 In [8]: x
1347 1353 Out[8]: 'hello'
1348 1354
1349 1355 In [9]: print x
1350 1356 hello
1351 1357
1352 1358 In [10]: _ip.complete('x.l')
1353 1359 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1354 1360 """
1355 1361
1356 1362 # Inject names into __builtin__ so we can complete on the added names.
1357 1363 with self.builtin_trap:
1358 1364 complete = self.Completer.complete
1359 1365 state = 0
1360 1366 # use a dict so we get unique keys, since ipyhton's multiple
1361 1367 # completers can return duplicates. When we make 2.4 a requirement,
1362 1368 # start using sets instead, which are faster.
1363 1369 comps = {}
1364 1370 while True:
1365 1371 newcomp = complete(text,state,line_buffer=text)
1366 1372 if newcomp is None:
1367 1373 break
1368 1374 comps[newcomp] = 1
1369 1375 state += 1
1370 1376 outcomps = comps.keys()
1371 1377 outcomps.sort()
1372 1378 #print "T:",text,"OC:",outcomps # dbg
1373 1379 #print "vars:",self.user_ns.keys()
1374 1380 return outcomps
1375 1381
1376 1382 def set_custom_completer(self,completer,pos=0):
1377 1383 """Adds a new custom completer function.
1378 1384
1379 1385 The position argument (defaults to 0) is the index in the completers
1380 1386 list where you want the completer to be inserted."""
1381 1387
1382 1388 newcomp = new.instancemethod(completer,self.Completer,
1383 1389 self.Completer.__class__)
1384 1390 self.Completer.matchers.insert(pos,newcomp)
1385 1391
1386 1392 def set_completer(self):
1387 1393 """Reset readline's completer to be our own."""
1388 1394 self.readline.set_completer(self.Completer.complete)
1389 1395
1390 1396 def set_completer_frame(self, frame=None):
1391 1397 """Set the frame of the completer."""
1392 1398 if frame:
1393 1399 self.Completer.namespace = frame.f_locals
1394 1400 self.Completer.global_namespace = frame.f_globals
1395 1401 else:
1396 1402 self.Completer.namespace = self.user_ns
1397 1403 self.Completer.global_namespace = self.user_global_ns
1398 1404
1399 1405 #-------------------------------------------------------------------------
1400 1406 # Things related to readline
1401 1407 #-------------------------------------------------------------------------
1402 1408
1403 1409 def init_readline(self):
1404 1410 """Command history completion/saving/reloading."""
1405 1411
1406 1412 if self.readline_use:
1407 1413 import IPython.utils.rlineimpl as readline
1408 1414
1409 1415 self.rl_next_input = None
1410 1416 self.rl_do_indent = False
1411 1417
1412 1418 if not self.readline_use or not readline.have_readline:
1413 1419 self.has_readline = False
1414 1420 self.readline = None
1415 1421 # Set a number of methods that depend on readline to be no-op
1416 1422 self.savehist = no_op
1417 1423 self.reloadhist = no_op
1418 1424 self.set_completer = no_op
1419 1425 self.set_custom_completer = no_op
1420 1426 self.set_completer_frame = no_op
1421 1427 warn('Readline services not available or not loaded.')
1422 1428 else:
1423 1429 self.has_readline = True
1424 1430 self.readline = readline
1425 1431 sys.modules['readline'] = readline
1426 1432 import atexit
1427 1433 from IPython.core.completer import IPCompleter
1428 1434 self.Completer = IPCompleter(self,
1429 1435 self.user_ns,
1430 1436 self.user_global_ns,
1431 1437 self.readline_omit__names,
1432 1438 self.alias_manager.alias_table)
1433 1439 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1434 1440 self.strdispatchers['complete_command'] = sdisp
1435 1441 self.Completer.custom_completers = sdisp
1436 1442 # Platform-specific configuration
1437 1443 if os.name == 'nt':
1438 1444 self.readline_startup_hook = readline.set_pre_input_hook
1439 1445 else:
1440 1446 self.readline_startup_hook = readline.set_startup_hook
1441 1447
1442 1448 # Load user's initrc file (readline config)
1443 1449 # Or if libedit is used, load editrc.
1444 1450 inputrc_name = os.environ.get('INPUTRC')
1445 1451 if inputrc_name is None:
1446 1452 home_dir = get_home_dir()
1447 1453 if home_dir is not None:
1448 1454 inputrc_name = '.inputrc'
1449 1455 if readline.uses_libedit:
1450 1456 inputrc_name = '.editrc'
1451 1457 inputrc_name = os.path.join(home_dir, inputrc_name)
1452 1458 if os.path.isfile(inputrc_name):
1453 1459 try:
1454 1460 readline.read_init_file(inputrc_name)
1455 1461 except:
1456 1462 warn('Problems reading readline initialization file <%s>'
1457 1463 % inputrc_name)
1458 1464
1459 1465 # save this in sys so embedded copies can restore it properly
1460 1466 sys.ipcompleter = self.Completer.complete
1461 1467 self.set_completer()
1462 1468
1463 1469 # Configure readline according to user's prefs
1464 1470 # This is only done if GNU readline is being used. If libedit
1465 1471 # is being used (as on Leopard) the readline config is
1466 1472 # not run as the syntax for libedit is different.
1467 1473 if not readline.uses_libedit:
1468 1474 for rlcommand in self.readline_parse_and_bind:
1469 1475 #print "loading rl:",rlcommand # dbg
1470 1476 readline.parse_and_bind(rlcommand)
1471 1477
1472 1478 # Remove some chars from the delimiters list. If we encounter
1473 1479 # unicode chars, discard them.
1474 1480 delims = readline.get_completer_delims().encode("ascii", "ignore")
1475 1481 delims = delims.translate(string._idmap,
1476 1482 self.readline_remove_delims)
1477 1483 readline.set_completer_delims(delims)
1478 1484 # otherwise we end up with a monster history after a while:
1479 1485 readline.set_history_length(1000)
1480 1486 try:
1481 1487 #print '*** Reading readline history' # dbg
1482 1488 readline.read_history_file(self.histfile)
1483 1489 except IOError:
1484 1490 pass # It doesn't exist yet.
1485 1491
1486 1492 atexit.register(self.atexit_operations)
1487 1493 del atexit
1488 1494
1489 1495 # Configure auto-indent for all platforms
1490 1496 self.set_autoindent(self.autoindent)
1491 1497
1492 1498 def set_next_input(self, s):
1493 1499 """ Sets the 'default' input string for the next command line.
1494 1500
1495 1501 Requires readline.
1496 1502
1497 1503 Example:
1498 1504
1499 1505 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1500 1506 [D:\ipython]|2> Hello Word_ # cursor is here
1501 1507 """
1502 1508
1503 1509 self.rl_next_input = s
1504 1510
1505 1511 # Maybe move this to the terminal subclass?
1506 1512 def pre_readline(self):
1507 1513 """readline hook to be used at the start of each line.
1508 1514
1509 1515 Currently it handles auto-indent only."""
1510 1516
1511 1517 if self.rl_do_indent:
1512 1518 self.readline.insert_text(self._indent_current_str())
1513 1519 if self.rl_next_input is not None:
1514 1520 self.readline.insert_text(self.rl_next_input)
1515 1521 self.rl_next_input = None
1516 1522
1517 1523 def _indent_current_str(self):
1518 1524 """return the current level of indentation as a string"""
1519 1525 return self.indent_current_nsp * ' '
1520 1526
1521 1527 #-------------------------------------------------------------------------
1522 1528 # Things related to magics
1523 1529 #-------------------------------------------------------------------------
1524 1530
1525 1531 def init_magics(self):
1526 1532 # FIXME: Move the color initialization to the DisplayHook, which
1527 1533 # should be split into a prompt manager and displayhook. We probably
1528 1534 # even need a centralize colors management object.
1529 1535 self.magic_colors(self.colors)
1530 1536 # History was moved to a separate module
1531 1537 from . import history
1532 1538 history.init_ipython(self)
1533 1539
1534 1540 def magic(self,arg_s):
1535 1541 """Call a magic function by name.
1536 1542
1537 1543 Input: a string containing the name of the magic function to call and any
1538 1544 additional arguments to be passed to the magic.
1539 1545
1540 1546 magic('name -opt foo bar') is equivalent to typing at the ipython
1541 1547 prompt:
1542 1548
1543 1549 In[1]: %name -opt foo bar
1544 1550
1545 1551 To call a magic without arguments, simply use magic('name').
1546 1552
1547 1553 This provides a proper Python function to call IPython's magics in any
1548 1554 valid Python code you can type at the interpreter, including loops and
1549 1555 compound statements.
1550 1556 """
1551 1557 args = arg_s.split(' ',1)
1552 1558 magic_name = args[0]
1553 1559 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1554 1560
1555 1561 try:
1556 1562 magic_args = args[1]
1557 1563 except IndexError:
1558 1564 magic_args = ''
1559 1565 fn = getattr(self,'magic_'+magic_name,None)
1560 1566 if fn is None:
1561 1567 error("Magic function `%s` not found." % magic_name)
1562 1568 else:
1563 1569 magic_args = self.var_expand(magic_args,1)
1564 1570 with nested(self.builtin_trap,):
1565 1571 result = fn(magic_args)
1566 1572 return result
1567 1573
1568 1574 def define_magic(self, magicname, func):
1569 1575 """Expose own function as magic function for ipython
1570 1576
1571 1577 def foo_impl(self,parameter_s=''):
1572 1578 'My very own magic!. (Use docstrings, IPython reads them).'
1573 1579 print 'Magic function. Passed parameter is between < >:'
1574 1580 print '<%s>' % parameter_s
1575 1581 print 'The self object is:',self
1576 1582
1577 1583 self.define_magic('foo',foo_impl)
1578 1584 """
1579 1585
1580 1586 import new
1581 1587 im = new.instancemethod(func,self, self.__class__)
1582 1588 old = getattr(self, "magic_" + magicname, None)
1583 1589 setattr(self, "magic_" + magicname, im)
1584 1590 return old
1585 1591
1586 1592 #-------------------------------------------------------------------------
1587 1593 # Things related to macros
1588 1594 #-------------------------------------------------------------------------
1589 1595
1590 1596 def define_macro(self, name, themacro):
1591 1597 """Define a new macro
1592 1598
1593 1599 Parameters
1594 1600 ----------
1595 1601 name : str
1596 1602 The name of the macro.
1597 1603 themacro : str or Macro
1598 1604 The action to do upon invoking the macro. If a string, a new
1599 1605 Macro object is created by passing the string to it.
1600 1606 """
1601 1607
1602 1608 from IPython.core import macro
1603 1609
1604 1610 if isinstance(themacro, basestring):
1605 1611 themacro = macro.Macro(themacro)
1606 1612 if not isinstance(themacro, macro.Macro):
1607 1613 raise ValueError('A macro must be a string or a Macro instance.')
1608 1614 self.user_ns[name] = themacro
1609 1615
1610 1616 #-------------------------------------------------------------------------
1611 1617 # Things related to the running of system commands
1612 1618 #-------------------------------------------------------------------------
1613 1619
1614 1620 def system(self, cmd):
1615 1621 """Make a system call, using IPython."""
1616 1622 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1617 1623
1618 1624 #-------------------------------------------------------------------------
1619 1625 # Things related to aliases
1620 1626 #-------------------------------------------------------------------------
1621 1627
1622 1628 def init_alias(self):
1623 1629 self.alias_manager = AliasManager(shell=self, config=self.config)
1624 1630 self.ns_table['alias'] = self.alias_manager.alias_table,
1625 1631
1626 1632 #-------------------------------------------------------------------------
1627 1633 # Things related to extensions and plugins
1628 1634 #-------------------------------------------------------------------------
1629 1635
1630 1636 def init_extension_manager(self):
1631 1637 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1632 1638
1633 1639 def init_plugin_manager(self):
1634 1640 self.plugin_manager = PluginManager(config=self.config)
1635 1641
1636 1642 #-------------------------------------------------------------------------
1637 1643 # Things related to the prefilter
1638 1644 #-------------------------------------------------------------------------
1639 1645
1640 1646 def init_prefilter(self):
1641 1647 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1642 1648 # Ultimately this will be refactored in the new interpreter code, but
1643 1649 # for now, we should expose the main prefilter method (there's legacy
1644 1650 # code out there that may rely on this).
1645 1651 self.prefilter = self.prefilter_manager.prefilter_lines
1646 1652
1647 1653 #-------------------------------------------------------------------------
1648 1654 # Things related to the running of code
1649 1655 #-------------------------------------------------------------------------
1650 1656
1651 1657 def ex(self, cmd):
1652 1658 """Execute a normal python statement in user namespace."""
1653 1659 with nested(self.builtin_trap,):
1654 1660 exec cmd in self.user_global_ns, self.user_ns
1655 1661
1656 1662 def ev(self, expr):
1657 1663 """Evaluate python expression expr in user namespace.
1658 1664
1659 1665 Returns the result of evaluation
1660 1666 """
1661 1667 with nested(self.builtin_trap,):
1662 1668 return eval(expr, self.user_global_ns, self.user_ns)
1663 1669
1664 1670 def safe_execfile(self, fname, *where, **kw):
1665 1671 """A safe version of the builtin execfile().
1666 1672
1667 1673 This version will never throw an exception, but instead print
1668 1674 helpful error messages to the screen. This only works on pure
1669 1675 Python files with the .py extension.
1670 1676
1671 1677 Parameters
1672 1678 ----------
1673 1679 fname : string
1674 1680 The name of the file to be executed.
1675 1681 where : tuple
1676 1682 One or two namespaces, passed to execfile() as (globals,locals).
1677 1683 If only one is given, it is passed as both.
1678 1684 exit_ignore : bool (False)
1679 1685 If True, then silence SystemExit for non-zero status (it is always
1680 1686 silenced for zero status, as it is so common).
1681 1687 """
1682 1688 kw.setdefault('exit_ignore', False)
1683 1689
1684 1690 fname = os.path.abspath(os.path.expanduser(fname))
1685 1691
1686 1692 # Make sure we have a .py file
1687 1693 if not fname.endswith('.py'):
1688 1694 warn('File must end with .py to be run using execfile: <%s>' % fname)
1689 1695
1690 1696 # Make sure we can open the file
1691 1697 try:
1692 1698 with open(fname) as thefile:
1693 1699 pass
1694 1700 except:
1695 1701 warn('Could not open file <%s> for safe execution.' % fname)
1696 1702 return
1697 1703
1698 1704 # Find things also in current directory. This is needed to mimic the
1699 1705 # behavior of running a script from the system command line, where
1700 1706 # Python inserts the script's directory into sys.path
1701 1707 dname = os.path.dirname(fname)
1702 1708
1703 1709 with prepended_to_syspath(dname):
1704 1710 try:
1705 1711 execfile(fname,*where)
1706 1712 except SystemExit, status:
1707 1713 # If the call was made with 0 or None exit status (sys.exit(0)
1708 1714 # or sys.exit() ), don't bother showing a traceback, as both of
1709 1715 # these are considered normal by the OS:
1710 1716 # > python -c'import sys;sys.exit(0)'; echo $?
1711 1717 # 0
1712 1718 # > python -c'import sys;sys.exit()'; echo $?
1713 1719 # 0
1714 1720 # For other exit status, we show the exception unless
1715 1721 # explicitly silenced, but only in short form.
1716 1722 if status.code not in (0, None) and not kw['exit_ignore']:
1717 1723 self.showtraceback(exception_only=True)
1718 1724 except:
1719 1725 self.showtraceback()
1720 1726
1721 1727 def safe_execfile_ipy(self, fname):
1722 1728 """Like safe_execfile, but for .ipy files with IPython syntax.
1723 1729
1724 1730 Parameters
1725 1731 ----------
1726 1732 fname : str
1727 1733 The name of the file to execute. The filename must have a
1728 1734 .ipy extension.
1729 1735 """
1730 1736 fname = os.path.abspath(os.path.expanduser(fname))
1731 1737
1732 1738 # Make sure we have a .py file
1733 1739 if not fname.endswith('.ipy'):
1734 1740 warn('File must end with .py to be run using execfile: <%s>' % fname)
1735 1741
1736 1742 # Make sure we can open the file
1737 1743 try:
1738 1744 with open(fname) as thefile:
1739 1745 pass
1740 1746 except:
1741 1747 warn('Could not open file <%s> for safe execution.' % fname)
1742 1748 return
1743 1749
1744 1750 # Find things also in current directory. This is needed to mimic the
1745 1751 # behavior of running a script from the system command line, where
1746 1752 # Python inserts the script's directory into sys.path
1747 1753 dname = os.path.dirname(fname)
1748 1754
1749 1755 with prepended_to_syspath(dname):
1750 1756 try:
1751 1757 with open(fname) as thefile:
1752 1758 script = thefile.read()
1753 1759 # self.runlines currently captures all exceptions
1754 1760 # raise in user code. It would be nice if there were
1755 1761 # versions of runlines, execfile that did raise, so
1756 1762 # we could catch the errors.
1757 1763 self.runlines(script, clean=True)
1758 1764 except:
1759 1765 self.showtraceback()
1760 1766 warn('Unknown failure executing file: <%s>' % fname)
1761 1767
1762 1768 def runlines(self, lines, clean=False):
1763 1769 """Run a string of one or more lines of source.
1764 1770
1765 1771 This method is capable of running a string containing multiple source
1766 1772 lines, as if they had been entered at the IPython prompt. Since it
1767 1773 exposes IPython's processing machinery, the given strings can contain
1768 1774 magic calls (%magic), special shell access (!cmd), etc.
1769 1775 """
1770 1776
1771 1777 if isinstance(lines, (list, tuple)):
1772 1778 lines = '\n'.join(lines)
1773 1779
1774 1780 if clean:
1775 1781 lines = self._cleanup_ipy_script(lines)
1776 1782
1777 1783 # We must start with a clean buffer, in case this is run from an
1778 1784 # interactive IPython session (via a magic, for example).
1779 1785 self.resetbuffer()
1780 1786 lines = lines.splitlines()
1781 1787 more = 0
1782 1788
1783 1789 with nested(self.builtin_trap, self.display_trap):
1784 1790 for line in lines:
1785 1791 # skip blank lines so we don't mess up the prompt counter, but do
1786 1792 # NOT skip even a blank line if we are in a code block (more is
1787 1793 # true)
1788 1794
1789 1795 if line or more:
1790 1796 # push to raw history, so hist line numbers stay in sync
1791 1797 self.input_hist_raw.append("# " + line + "\n")
1792 1798 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1793 1799 more = self.push_line(prefiltered)
1794 1800 # IPython's runsource returns None if there was an error
1795 1801 # compiling the code. This allows us to stop processing right
1796 1802 # away, so the user gets the error message at the right place.
1797 1803 if more is None:
1798 1804 break
1799 1805 else:
1800 1806 self.input_hist_raw.append("\n")
1801 1807 # final newline in case the input didn't have it, so that the code
1802 1808 # actually does get executed
1803 1809 if more:
1804 1810 self.push_line('\n')
1805 1811
1806 1812 def runsource(self, source, filename='<input>', symbol='single'):
1807 1813 """Compile and run some source in the interpreter.
1808 1814
1809 1815 Arguments are as for compile_command().
1810 1816
1811 1817 One several things can happen:
1812 1818
1813 1819 1) The input is incorrect; compile_command() raised an
1814 1820 exception (SyntaxError or OverflowError). A syntax traceback
1815 1821 will be printed by calling the showsyntaxerror() method.
1816 1822
1817 1823 2) The input is incomplete, and more input is required;
1818 1824 compile_command() returned None. Nothing happens.
1819 1825
1820 1826 3) The input is complete; compile_command() returned a code
1821 1827 object. The code is executed by calling self.runcode() (which
1822 1828 also handles run-time exceptions, except for SystemExit).
1823 1829
1824 1830 The return value is:
1825 1831
1826 1832 - True in case 2
1827 1833
1828 1834 - False in the other cases, unless an exception is raised, where
1829 1835 None is returned instead. This can be used by external callers to
1830 1836 know whether to continue feeding input or not.
1831 1837
1832 1838 The return value can be used to decide whether to use sys.ps1 or
1833 1839 sys.ps2 to prompt the next line."""
1834 1840
1835 1841 # if the source code has leading blanks, add 'if 1:\n' to it
1836 1842 # this allows execution of indented pasted code. It is tempting
1837 1843 # to add '\n' at the end of source to run commands like ' a=1'
1838 1844 # directly, but this fails for more complicated scenarios
1839 1845 source=source.encode(self.stdin_encoding)
1840 1846 if source[:1] in [' ', '\t']:
1841 1847 source = 'if 1:\n%s' % source
1842 1848
1843 1849 try:
1844 1850 code = self.compile(source,filename,symbol)
1845 1851 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1846 1852 # Case 1
1847 1853 self.showsyntaxerror(filename)
1848 1854 return None
1849 1855
1850 1856 if code is None:
1851 1857 # Case 2
1852 1858 return True
1853 1859
1854 1860 # Case 3
1855 1861 # We store the code object so that threaded shells and
1856 1862 # custom exception handlers can access all this info if needed.
1857 1863 # The source corresponding to this can be obtained from the
1858 1864 # buffer attribute as '\n'.join(self.buffer).
1859 1865 self.code_to_run = code
1860 1866 # now actually execute the code object
1861 1867 if self.runcode(code) == 0:
1862 1868 return False
1863 1869 else:
1864 1870 return None
1865 1871
1866 1872 def runcode(self,code_obj):
1867 1873 """Execute a code object.
1868 1874
1869 1875 When an exception occurs, self.showtraceback() is called to display a
1870 1876 traceback.
1871 1877
1872 1878 Return value: a flag indicating whether the code to be run completed
1873 1879 successfully:
1874 1880
1875 1881 - 0: successful execution.
1876 1882 - 1: an error occurred.
1877 1883 """
1878 1884
1879 1885 # Set our own excepthook in case the user code tries to call it
1880 1886 # directly, so that the IPython crash handler doesn't get triggered
1881 1887 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1882 1888
1883 1889 # we save the original sys.excepthook in the instance, in case config
1884 1890 # code (such as magics) needs access to it.
1885 1891 self.sys_excepthook = old_excepthook
1886 1892 outflag = 1 # happens in more places, so it's easier as default
1887 1893 try:
1888 1894 try:
1889 1895 self.hooks.pre_runcode_hook()
1890 1896 exec code_obj in self.user_global_ns, self.user_ns
1891 1897 finally:
1892 1898 # Reset our crash handler in place
1893 1899 sys.excepthook = old_excepthook
1894 1900 except SystemExit:
1895 1901 self.resetbuffer()
1896 1902 self.showtraceback(exception_only=True)
1897 1903 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1898 1904 except self.custom_exceptions:
1899 1905 etype,value,tb = sys.exc_info()
1900 1906 self.CustomTB(etype,value,tb)
1901 1907 except:
1902 1908 self.showtraceback()
1903 1909 else:
1904 1910 outflag = 0
1905 1911 if softspace(sys.stdout, 0):
1906 1912 print
1907 1913 # Flush out code object which has been run (and source)
1908 1914 self.code_to_run = None
1909 1915 return outflag
1910 1916
1911 1917 def push_line(self, line):
1912 1918 """Push a line to the interpreter.
1913 1919
1914 1920 The line should not have a trailing newline; it may have
1915 1921 internal newlines. The line is appended to a buffer and the
1916 1922 interpreter's runsource() method is called with the
1917 1923 concatenated contents of the buffer as source. If this
1918 1924 indicates that the command was executed or invalid, the buffer
1919 1925 is reset; otherwise, the command is incomplete, and the buffer
1920 1926 is left as it was after the line was appended. The return
1921 1927 value is 1 if more input is required, 0 if the line was dealt
1922 1928 with in some way (this is the same as runsource()).
1923 1929 """
1924 1930
1925 1931 # autoindent management should be done here, and not in the
1926 1932 # interactive loop, since that one is only seen by keyboard input. We
1927 1933 # need this done correctly even for code run via runlines (which uses
1928 1934 # push).
1929 1935
1930 1936 #print 'push line: <%s>' % line # dbg
1931 1937 for subline in line.splitlines():
1932 1938 self._autoindent_update(subline)
1933 1939 self.buffer.append(line)
1934 1940 more = self.runsource('\n'.join(self.buffer), self.filename)
1935 1941 if not more:
1936 1942 self.resetbuffer()
1937 1943 return more
1938 1944
1939 1945 def resetbuffer(self):
1940 1946 """Reset the input buffer."""
1941 1947 self.buffer[:] = []
1942 1948
1943 1949 def _is_secondary_block_start(self, s):
1944 1950 if not s.endswith(':'):
1945 1951 return False
1946 1952 if (s.startswith('elif') or
1947 1953 s.startswith('else') or
1948 1954 s.startswith('except') or
1949 1955 s.startswith('finally')):
1950 1956 return True
1951 1957
1952 1958 def _cleanup_ipy_script(self, script):
1953 1959 """Make a script safe for self.runlines()
1954 1960
1955 1961 Currently, IPython is lines based, with blocks being detected by
1956 1962 empty lines. This is a problem for block based scripts that may
1957 1963 not have empty lines after blocks. This script adds those empty
1958 1964 lines to make scripts safe for running in the current line based
1959 1965 IPython.
1960 1966 """
1961 1967 res = []
1962 1968 lines = script.splitlines()
1963 1969 level = 0
1964 1970
1965 1971 for l in lines:
1966 1972 lstripped = l.lstrip()
1967 1973 stripped = l.strip()
1968 1974 if not stripped:
1969 1975 continue
1970 1976 newlevel = len(l) - len(lstripped)
1971 1977 if level > 0 and newlevel == 0 and \
1972 1978 not self._is_secondary_block_start(stripped):
1973 1979 # add empty line
1974 1980 res.append('')
1975 1981 res.append(l)
1976 1982 level = newlevel
1977 1983
1978 1984 return '\n'.join(res) + '\n'
1979 1985
1980 1986 def _autoindent_update(self,line):
1981 1987 """Keep track of the indent level."""
1982 1988
1983 1989 #debugx('line')
1984 1990 #debugx('self.indent_current_nsp')
1985 1991 if self.autoindent:
1986 1992 if line:
1987 1993 inisp = num_ini_spaces(line)
1988 1994 if inisp < self.indent_current_nsp:
1989 1995 self.indent_current_nsp = inisp
1990 1996
1991 1997 if line[-1] == ':':
1992 1998 self.indent_current_nsp += 4
1993 1999 elif dedent_re.match(line):
1994 2000 self.indent_current_nsp -= 4
1995 2001 else:
1996 2002 self.indent_current_nsp = 0
1997 2003
1998 2004 #-------------------------------------------------------------------------
1999 2005 # Things related to GUI support and pylab
2000 2006 #-------------------------------------------------------------------------
2001 2007
2002 2008 def enable_pylab(self, gui=None):
2003 2009 raise NotImplementedError('Implement enable_pylab in a subclass')
2004 2010
2005 2011 #-------------------------------------------------------------------------
2006 2012 # Utilities
2007 2013 #-------------------------------------------------------------------------
2008 2014
2009 2015 def getoutput(self, cmd):
2010 2016 return getoutput(self.var_expand(cmd,depth=2),
2011 2017 header=self.system_header,
2012 2018 verbose=self.system_verbose)
2013 2019
2014 2020 def getoutputerror(self, cmd):
2015 2021 return getoutputerror(self.var_expand(cmd,depth=2),
2016 2022 header=self.system_header,
2017 2023 verbose=self.system_verbose)
2018 2024
2019 2025 def var_expand(self,cmd,depth=0):
2020 2026 """Expand python variables in a string.
2021 2027
2022 2028 The depth argument indicates how many frames above the caller should
2023 2029 be walked to look for the local namespace where to expand variables.
2024 2030
2025 2031 The global namespace for expansion is always the user's interactive
2026 2032 namespace.
2027 2033 """
2028 2034
2029 2035 return str(ItplNS(cmd,
2030 2036 self.user_ns, # globals
2031 2037 # Skip our own frame in searching for locals:
2032 2038 sys._getframe(depth+1).f_locals # locals
2033 2039 ))
2034 2040
2035 2041 def mktempfile(self,data=None):
2036 2042 """Make a new tempfile and return its filename.
2037 2043
2038 2044 This makes a call to tempfile.mktemp, but it registers the created
2039 2045 filename internally so ipython cleans it up at exit time.
2040 2046
2041 2047 Optional inputs:
2042 2048
2043 2049 - data(None): if data is given, it gets written out to the temp file
2044 2050 immediately, and the file is closed again."""
2045 2051
2046 2052 filename = tempfile.mktemp('.py','ipython_edit_')
2047 2053 self.tempfiles.append(filename)
2048 2054
2049 2055 if data:
2050 2056 tmp_file = open(filename,'w')
2051 2057 tmp_file.write(data)
2052 2058 tmp_file.close()
2053 2059 return filename
2054 2060
2055 2061 # TODO: This should be removed when Term is refactored.
2056 2062 def write(self,data):
2057 2063 """Write a string to the default output"""
2058 2064 IPython.utils.io.Term.cout.write(data)
2059 2065
2060 2066 # TODO: This should be removed when Term is refactored.
2061 2067 def write_err(self,data):
2062 2068 """Write a string to the default error output"""
2063 2069 IPython.utils.io.Term.cerr.write(data)
2064 2070
2065 2071 def ask_yes_no(self,prompt,default=True):
2066 2072 if self.quiet:
2067 2073 return True
2068 2074 return ask_yes_no(prompt,default)
2069 2075
2070 2076 #-------------------------------------------------------------------------
2071 2077 # Things related to IPython exiting
2072 2078 #-------------------------------------------------------------------------
2073 2079
2074 2080 def atexit_operations(self):
2075 2081 """This will be executed at the time of exit.
2076 2082
2077 2083 Saving of persistent data should be performed here.
2078 2084 """
2079 2085 self.savehist()
2080 2086
2081 2087 # Cleanup all tempfiles left around
2082 2088 for tfile in self.tempfiles:
2083 2089 try:
2084 2090 os.unlink(tfile)
2085 2091 except OSError:
2086 2092 pass
2087 2093
2088 2094 # Clear all user namespaces to release all references cleanly.
2089 2095 self.reset()
2090 2096
2091 2097 # Run user hooks
2092 2098 self.hooks.shutdown_hook()
2093 2099
2094 2100 def cleanup(self):
2095 2101 self.restore_sys_module_state()
2096 2102
2097 2103
2098 2104 class InteractiveShellABC(object):
2099 2105 """An abstract base class for InteractiveShell."""
2100 2106 __metaclass__ = abc.ABCMeta
2101 2107
2102 2108 InteractiveShellABC.register(InteractiveShell)
@@ -1,579 +1,577 b''
1 1 ======================
2 2 Messaging in IPython
3 3 ======================
4 4
5 5
6 6 Introduction
7 7 ============
8 8
9 9 This document explains the basic communications design and messaging
10 10 specification for how the various IPython objects interact over a network
11 11 transport. The current implementation uses the ZeroMQ_ library for messaging
12 12 within and between hosts.
13 13
14 14 .. Note::
15 15
16 16 This document should be considered the authoritative description of the
17 17 IPython messaging protocol, and all developers are strongly encouraged to
18 18 keep it updated as the implementation evolves, so that we have a single
19 19 common reference for all protocol details.
20 20
21 21 The basic design is explained in the following diagram:
22 22
23 23 .. image:: frontend-kernel.png
24 24 :width: 450px
25 25 :alt: IPython kernel/frontend messaging architecture.
26 26 :align: center
27 27 :target: ../_images/frontend-kernel.png
28 28
29 29 A single kernel can be simultaneously connected to one or more frontends. The
30 30 kernel has three sockets that serve the following functions:
31 31
32 32 1. REQ: this socket is connected to a *single* frontend at a time, and it allows
33 33 the kernel to request input from a frontend when :func:`raw_input` is called.
34 34 The frontend holding the matching REP socket acts as a 'virtual keyboard'
35 35 for the kernel while this communication is happening (illustrated in the
36 36 figure by the black outline around the central keyboard). In practice,
37 37 frontends may display such kernel requests using a special input widget or
38 38 otherwise indicating that the user is to type input for the kernel instead
39 39 of normal commands in the frontend.
40 40
41 41 2. XREP: this single sockets allows multiple incoming connections from
42 42 frontends, and this is the socket where requests for code execution, object
43 43 information, prompts, etc. are made to the kernel by any frontend. The
44 44 communication on this socket is a sequence of request/reply actions from
45 45 each frontend and the kernel.
46 46
47 47 3. PUB: this socket is the 'broadcast channel' where the kernel publishes all
48 48 side effects (stdout, stderr, etc.) as well as the requests coming from any
49 49 client over the XREP socket and its own requests on the REP socket. There
50 50 are a number of actions in Python which generate side effects: :func:`print`
51 51 writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in
52 52 a multi-client scenario, we want all frontends to be able to know what each
53 53 other has sent to the kernel (this can be useful in collaborative scenarios,
54 54 for example). This socket allows both side effects and the information
55 55 about communications taking place with one client over the XREQ/XREP channel
56 56 to be made available to all clients in a uniform manner.
57 57
58 58 All messages are tagged with enough information (details below) for clients
59 59 to know which messages come from their own interaction with the kernel and
60 60 which ones are from other clients, so they can display each type
61 61 appropriately.
62 62
63 63 The actual format of the messages allowed on each of these channels is
64 64 specified below. Messages are dicts of dicts with string keys and values that
65 65 are reasonably representable in JSON. Our current implementation uses JSON
66 66 explicitly as its message format, but this shouldn't be considered a permanent
67 67 feature. As we've discovered that JSON has non-trivial performance issues due
68 68 to excessive copying, we may in the future move to a pure pickle-based raw
69 69 message format. However, it should be possible to easily convert from the raw
70 70 objects to JSON, since we may have non-python clients (e.g. a web frontend).
71 71 As long as it's easy to make a JSON version of the objects that is a faithful
72 72 representation of all the data, we can communicate with such clients.
73 73
74 74 .. Note::
75 75
76 76 Not all of these have yet been fully fleshed out, but the key ones are, see
77 77 kernel and frontend files for actual implementation details.
78 78
79 79
80 80 Python functional API
81 81 =====================
82 82
83 83 As messages are dicts, they map naturally to a ``func(**kw)`` call form. We
84 84 should develop, at a few key points, functional forms of all the requests that
85 85 take arguments in this manner and automatically construct the necessary dict
86 86 for sending.
87 87
88 88
89 89 General Message Format
90 90 ======================
91 91
92 92 All messages send or received by any IPython process should have the following
93 93 generic structure::
94 94
95 95 {
96 96 # The message header contains a pair of unique identifiers for the
97 97 # originating session and the actual message id, in addition to the
98 98 # username for the process that generated the message. This is useful in
99 99 # collaborative settings where multiple users may be interacting with the
100 100 # same kernel simultaneously, so that frontends can label the various
101 101 # messages in a meaningful way.
102 102 'header' : { 'msg_id' : uuid,
103 103 'username' : str,
104 104 'session' : uuid
105 105 },
106 106
107 107 # In a chain of messages, the header from the parent is copied so that
108 108 # clients can track where messages come from.
109 109 'parent_header' : dict,
110 110
111 111 # All recognized message type strings are listed below.
112 112 'msg_type' : str,
113 113
114 114 # The actual content of the message must be a dict, whose structure
115 115 # depends on the message type.x
116 116 'content' : dict,
117 117 }
118 118
119 119 For each message type, the actual content will differ and all existing message
120 120 types are specified in what follows of this document.
121 121
122 122
123 123 Messages on the XREP/XREQ socket
124 124 ================================
125 125
126 126 .. _execute:
127 127
128 128 Execute
129 129 -------
130 130
131 131 The execution request contains a single string, but this may be a multiline
132 132 string. The kernel is responsible for splitting this into possibly more than
133 133 one block and deciding whether to compile these in 'single' or 'exec' mode.
134 134 We're still sorting out this policy. The current inputsplitter is capable of
135 135 splitting the input for blocks that can all be run as 'single', but in the long
136 136 run it may prove cleaner to only use 'single' mode for truly single-line
137 137 inputs, and run all multiline input in 'exec' mode. This would preserve the
138 138 natural behavior of single-line inputs while allowing long cells to behave more
139 139 likea a script. This design will be refined as we complete the implementation.
140 140
141 141 Message type: ``execute_request``::
142 142
143 143 content = {
144 144 # Source code to be executed by the kernel, one or more lines.
145 145 'code' : str,
146 146
147 147 # A boolean flag which, if True, signals the kernel to execute this
148 148 # code as quietly as possible. This means that the kernel will compile
149 149 # the code with 'exec' instead of 'single' (so sys.displayhook will not
150 150 # fire), and will *not*:
151 151 # - broadcast exceptions on the PUB socket
152 152 # - do any logging
153 153 # - populate any history
154 154 # The default is False.
155 155 'silent' : bool,
156 156 }
157 157
158 158 Upon execution, the kernel *always* sends a reply, with a status code
159 159 indicating what happened and additional data depending on the outcome.
160 160
161 161 Message type: ``execute_reply``::
162 162
163 163 content = {
164 164 # One of: 'ok' OR 'error' OR 'abort'
165 165 'status' : str,
166 166
167 # Any additional data depends on status value
168 }
169
170 When status is 'ok', the following extra fields are present::
171
172 {
173 167 # This has the same structure as the output of a prompt request, but is
174 168 # for the client to set up the *next* prompt (with identical limitations
175 169 # to a prompt request)
176 170 'next_prompt' : {
177 171 'prompt_string' : str,
178 172 'prompt_number' : int,
179 173 },
180 174
181 175 # The prompt number of the actual execution for this code, which may be
182 176 # different from the one used when the code was typed, which was the
183 177 # 'next_prompt' field of the *previous* request. They will differ in the
184 178 # case where there is more than one client talking simultaneously to a
185 179 # kernel, since the numbers can go out of sync. GUI clients can use this
186 180 # to correct the previously written number in-place, terminal ones may
187 181 # re-print a corrected one if desired.
188 182 'prompt_number' : int,
183 }
184
185 When status is 'ok', the following extra fields are present::
189 186
187 {
190 188 # The kernel will often transform the input provided to it. This
191 189 # contains the transformed code, which is what was actually executed.
192 190 'transformed_code' : str,
193 191
194 192 # The execution payload is a dict with string keys that may have been
195 193 # produced by the code being executed. It is retrieved by the kernel at
196 194 # the end of the execution and sent back to the front end, which can take
197 195 # action on it as needed. See main text for further details.
198 196 'payload' : dict,
199 197 }
200 198
201 199 .. admonition:: Execution payloads
202 200
203 201 The notion of an 'execution payload' is different from a return value of a
204 202 given set of code, which normally is just displayed on the pyout stream
205 203 through the PUB socket. The idea of a payload is to allow special types of
206 204 code, typically magics, to populate a data container in the IPython kernel
207 205 that will be shipped back to the caller via this channel. The kernel will
208 206 have an API for this, probably something along the lines of::
209 207
210 208 ip.exec_payload_add(key, value)
211 209
212 210 though this API is still in the design stages. The data returned in this
213 211 payload will allow frontends to present special views of what just happened.
214 212
215 213
216 214 When status is 'error', the following extra fields are present::
217 215
218 216 {
219 217 'exc_name' : str, # Exception name, as a string
220 218 'exc_value' : str, # Exception value, as a string
221 219
222 220 # The traceback will contain a list of frames, represented each as a
223 221 # string. For now we'll stick to the existing design of ultraTB, which
224 222 # controls exception level of detail statefully. But eventually we'll
225 223 # want to grow into a model where more information is collected and
226 224 # packed into the traceback object, with clients deciding how little or
227 225 # how much of it to unpack. But for now, let's start with a simple list
228 226 # of strings, since that requires only minimal changes to ultratb as
229 227 # written.
230 228 'traceback' : list,
231 229 }
232 230
233 231
234 232 When status is 'abort', there are for now no additional data fields. This
235 233 happens when the kernel was interrupted by a signal.
236 234
237 235
238 236 Prompt
239 237 ------
240 238
241 239 A simple request for a current prompt string.
242 240
243 241 Message type: ``prompt_request``::
244 242
245 243 content = {}
246 244
247 245 In the reply, the prompt string comes back with the prompt number placeholder
248 246 *unevaluated*. The message format is:
249 247
250 248 Message type: ``prompt_reply``::
251 249
252 250 content = {
253 251 'prompt_string' : str,
254 252 'prompt_number' : int,
255 253 }
256 254
257 255 Clients can produce a prompt with ``prompt_string.format(prompt_number)``, but
258 256 they should be aware that the actual prompt number for that input could change
259 257 later, in the case where multiple clients are interacting with a single
260 258 kernel.
261 259
262 260
263 261 Object information
264 262 ------------------
265 263
266 264 One of IPython's most used capabilities is the introspection of Python objects
267 265 in the user's namespace, typically invoked via the ``?`` and ``??`` characters
268 266 (which in reality are shorthands for the ``%pinfo`` magic). This is used often
269 267 enough that it warrants an explicit message type, especially because frontends
270 268 may want to get object information in response to user keystrokes (like Tab or
271 269 F1) besides from the user explicitly typing code like ``x??``.
272 270
273 271 Message type: ``object_info_request``::
274 272
275 273 content = {
276 274 # The (possibly dotted) name of the object to be searched in all
277 275 # relevant namespaces
278 276 'name' : str,
279 277
280 278 # The level of detail desired. The default (0) is equivalent to typing
281 279 # 'x?' at the prompt, 1 is equivalent to 'x??'.
282 280 'detail_level' : int,
283 281 }
284 282
285 283 The returned information will be a dictionary with keys very similar to the
286 284 field names that IPython prints at the terminal.
287 285
288 286 Message type: ``object_info_reply``::
289 287
290 288 content = {
291 289 # Flags for magics and system aliases
292 290 'ismagic' : bool,
293 291 'isalias' : bool,
294 292
295 293 # The name of the namespace where the object was found ('builtin',
296 294 # 'magics', 'alias', 'interactive', etc.)
297 295 'namespace' : str,
298 296
299 297 # The type name will be type.__name__ for normal Python objects, but it
300 298 # can also be a string like 'Magic function' or 'System alias'
301 299 'type_name' : str,
302 300
303 301 'string_form' : str,
304 302
305 303 # For objects with a __class__ attribute this will be set
306 304 'base_class' : str,
307 305
308 306 # For objects with a __len__ attribute this will be set
309 307 'length' : int,
310 308
311 309 # If the object is a function, class or method whose file we can find,
312 310 # we give its full path
313 311 'file' : str,
314 312
315 313 # For pure Python callable objects, we can reconstruct the object
316 314 # definition line which provides its call signature
317 315 'definition' : str,
318 316
319 317 # For instances, provide the constructor signature (the definition of
320 318 # the __init__ method):
321 319 'init_definition' : str,
322 320
323 321 # Docstrings: for any object (function, method, module, package) with a
324 322 # docstring, we show it. But in addition, we may provide additional
325 323 # docstrings. For example, for instances we will show the constructor
326 324 # and class docstrings as well, if available.
327 325 'docstring' : str,
328 326
329 327 # For instances, provide the constructor and class docstrings
330 328 'init_docstring' : str,
331 329 'class_docstring' : str,
332 330
333 331 # If detail_level was 1, we also try to find the source code that
334 332 # defines the object, if possible. The string 'None' will indicate
335 333 # that no source was found.
336 334 'source' : str,
337 335 }
338 336
339 337
340 338 Complete
341 339 --------
342 340
343 341 Message type: ``complete_request``::
344 342
345 343 content = {
346 344 # The text to be completed, such as 'a.is'
347 345 'text' : str,
348 346
349 347 # The full line, such as 'print a.is'. This allows completers to
350 348 # make decisions that may require information about more than just the
351 349 # current word.
352 350 'line' : str,
353 351 }
354 352
355 353 Message type: ``complete_reply``::
356 354
357 355 content = {
358 356 # The list of all matches to the completion request, such as
359 357 # ['a.isalnum', 'a.isalpha'] for the above example.
360 358 'matches' : list
361 359 }
362 360
363 361
364 362 History
365 363 -------
366 364
367 365 For clients to explicitly request history from a kernel. The kernel has all
368 366 the actual execution history stored in a single location, so clients can
369 367 request it from the kernel when needed.
370 368
371 369 Message type: ``history_request``::
372 370
373 371 content = {
374 372
375 373 # If True, also return output history in the resulting dict.
376 374 'output' : bool,
377 375
378 376 # If True, return the raw input history, else the transformed input.
379 377 'raw' : bool,
380 378
381 379 # This parameter can be one of: A number, a pair of numbers, None
382 380 # If not given, last 40 are returned.
383 381 # - number n: return the last n entries.
384 382 # - pair n1, n2: return entries in the range(n1, n2).
385 383 # - None: return all history
386 384 'range' : n or (n1, n2) or None,
387 385
388 386 # If a filter is given, it is treated as a regular expression and only
389 387 # matching entries are returned. re.search() is used to find matches.
390 388 'filter' : str,
391 389 }
392 390
393 391 Message type: ``history_reply``::
394 392
395 393 content = {
396 394 # A dict with prompt numbers as keys and either (input, output) or input
397 395 # as the value depending on whether output was True or False,
398 396 # respectively.
399 397 'history' : dict,
400 398 }
401 399 Messages on the PUB/SUB socket
402 400 ==============================
403 401
404 402 Streams (stdout, stderr, etc)
405 403 ------------------------------
406 404
407 405 Message type: ``stream``::
408 406
409 407 content = {
410 408 # The name of the stream is one of 'stdin', 'stdout', 'stderr'
411 409 'name' : str,
412 410
413 411 # The data is an arbitrary string to be written to that stream
414 412 'data' : str,
415 413 }
416 414
417 415 When a kernel receives a raw_input call, it should also broadcast it on the pub
418 416 socket with the names 'stdin' and 'stdin_reply'. This will allow other clients
419 417 to monitor/display kernel interactions and possibly replay them to their user
420 418 or otherwise expose them.
421 419
422 420 Python inputs
423 421 -------------
424 422
425 423 These messages are the re-broadcast of the ``execute_request``.
426 424
427 425 Message type: ``pyin``::
428 426
429 427 content = {
430 428 # Source code to be executed, one or more lines
431 429 'code' : str
432 430 }
433 431
434 432 Python outputs
435 433 --------------
436 434
437 435 When Python produces output from code that has been compiled in with the
438 436 'single' flag to :func:`compile`, any expression that produces a value (such as
439 437 ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with
440 438 this value whatever it wants. The default behavior of ``sys.displayhook`` in
441 439 the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of
442 440 the value as long as it is not ``None`` (which isn't printed at all). In our
443 441 case, the kernel instantiates as ``sys.displayhook`` an object which has
444 442 similar behavior, but which instead of printing to stdout, broadcasts these
445 443 values as ``pyout`` messages for clients to display appropriately.
446 444
447 445 Message type: ``pyout``::
448 446
449 447 content = {
450 448 # The data is typically the repr() of the object.
451 449 'data' : str,
452 450
453 451 # The prompt number for this execution is also provided so that clients
454 452 # can display it, since IPython automatically creates variables called
455 453 # _N (for prompt N).
456 454 'prompt_number' : int,
457 455 }
458 456
459 457 Python errors
460 458 -------------
461 459
462 460 When an error occurs during code execution
463 461
464 462 Message type: ``pyerr``::
465 463
466 464 content = {
467 465 # Similar content to the execute_reply messages for the 'error' case,
468 466 # except the 'status' field is omitted.
469 467 }
470 468
471 469 Kernel crashes
472 470 --------------
473 471
474 472 When the kernel has an unexpected exception, caught by the last-resort
475 473 sys.excepthook, we should broadcast the crash handler's output before exiting.
476 474 This will allow clients to notice that a kernel died, inform the user and
477 475 propose further actions.
478 476
479 477 Message type: ``crash``::
480 478
481 479 content = {
482 480 # Similarly to the 'error' case for execute_reply messages, this will
483 481 # contain exc_name, exc_type and traceback fields.
484 482
485 483 # An additional field with supplementary information such as where to
486 484 # send the crash message
487 485 'info' : str,
488 486 }
489 487
490 488
491 489 Future ideas
492 490 ------------
493 491
494 492 Other potential message types, currently unimplemented, listed below as ideas.
495 493
496 494 Message type: ``file``::
497 495
498 496 content = {
499 497 'path' : 'cool.jpg',
500 498 'mimetype' : str,
501 499 'data' : str,
502 500 }
503 501
504 502
505 503 Messages on the REQ/REP socket
506 504 ==============================
507 505
508 506 This is a socket that goes in the opposite direction: from the kernel to a
509 507 *single* frontend, and its purpose is to allow ``raw_input`` and similar
510 508 operations that read from ``sys.stdin`` on the kernel to be fulfilled by the
511 509 client. For now we will keep these messages as simple as possible, since they
512 510 basically only mean to convey the ``raw_input(prompt)`` call.
513 511
514 512 Message type: ``input_request``::
515 513
516 514 content = { 'prompt' : str }
517 515
518 516 Message type: ``input_reply``::
519 517
520 518 content = { 'value' : str }
521 519
522 520 .. Note::
523 521
524 522 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
525 523 practice the kernel should behave like an interactive program. When a
526 524 program is opened on the console, the keyboard effectively takes over the
527 525 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
528 526 Since the IPython kernel effectively behaves like a console program (albeit
529 527 one whose "keyboard" is actually living in a separate process and
530 528 transported over the zmq connection), raw ``stdin`` isn't expected to be
531 529 available.
532 530
533 531
534 532 Heartbeat for kernels
535 533 =====================
536 534
537 535 Initially we had considered using messages like those above over ZMQ for a
538 536 kernel 'heartbeat' (a way to detect quickly and reliably whether a kernel is
539 537 alive at all, even if it may be busy executing user code). But this has the
540 538 problem that if the kernel is locked inside extension code, it wouldn't execute
541 539 the python heartbeat code. But it turns out that we can implement a basic
542 540 heartbeat with pure ZMQ, without using any Python messaging at all.
543 541
544 542 The monitor sends out a single zmq message (right now, it is a str of the
545 543 monitor's lifetime in seconds), and gets the same message right back, prefixed
546 544 with the zmq identity of the XREQ socket in the heartbeat process. This can be
547 545 a uuid, or even a full message, but there doesn't seem to be a need for packing
548 546 up a message when the sender and receiver are the exact same Python object.
549 547
550 548 The model is this::
551 549
552 550 monitor.send(str(self.lifetime)) # '1.2345678910'
553 551
554 552 and the monitor receives some number of messages of the form::
555 553
556 554 ['uuid-abcd-dead-beef', '1.2345678910']
557 555
558 556 where the first part is the zmq.IDENTITY of the heart's XREQ on the engine, and
559 557 the rest is the message sent by the monitor. No Python code ever has any
560 558 access to the message between the monitor's send, and the monitor's recv.
561 559
562 560
563 561 ToDo
564 562 ====
565 563
566 564 Missing things include:
567 565
568 566 * Important: finish thinking through the payload concept and API.
569 567
570 568 * Important: ensure that we have a good solution for magics like %edit. It's
571 569 likely that with the payload concept we can build a full solution, but not
572 570 100% clear yet.
573 571
574 572 * Finishing the details of the heartbeat protocol.
575 573
576 574 * Signal handling: specify what kind of information kernel should broadcast (or
577 575 not) when it receives signals.
578 576
579 577 .. include:: ../links.rst
General Comments 0
You need to be logged in to leave comments. Login now