##// END OF EJS Templates
Mostly final version of display data....
Brian Granger -
Show More
@@ -1,40 +1,103 b''
1 1 # -*- coding: utf-8 -*-
2 """An interface for publishing data related to the display of objects.
2 """An interface for publishing rich data to frontends.
3 3
4 4 Authors:
5 5
6 6 * Brian Granger
7 7 """
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (C) 2008-2010 The IPython Development Team
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #-----------------------------------------------------------------------------
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Imports
18 18 #-----------------------------------------------------------------------------
19 19
20 20 from IPython.config.configurable import Configurable
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Main payload class
24 24 #-----------------------------------------------------------------------------
25 25
26 26 class DisplayPublisher(Configurable):
27 27
28 28 def _validate_data(self, source, data, metadata=None):
29 29 if not isinstance(source, str):
30 30 raise TypeError('source must be a str, got: %r' % source)
31 31 if not isinstance(data, dict):
32 32 raise TypeError('data must be a dict, got: %r' % data)
33 33 if metadata is not None:
34 34 if not isinstance(metadata, dict):
35 35 raise TypeError('metadata must be a dict, got: %r' % data)
36 36
37 37 def publish(self, source, data, metadata=None):
38 """Publish data and metadata to all frontends."""
39 pass
38 """Publish data and metadata to all frontends.
40 39
40 See the ``display_data`` message in the messaging documentation for
41 more details about this message type.
42
43 Parameters
44 ----------
45 source : str
46 A string that give the function or method that created the data,
47 such as 'IPython.core.page'.
48 data : dict
49 A dictionary having keys that are valid MIME types (like
50 'text/plain' or 'image/svg+xml') and values that are the data for
51 that MIME type. The data itself must be a JSON'able data
52 structure. Minimally all data should have the 'text/plain' data,
53 which can be displayed by all frontends. If more than the plain
54 text is given, it is up to the frontend to decide which
55 representation to use.
56 metadata : dict
57 A dictionary for metadata related to the data. This can contain
58 arbitrary key, value pairs that frontends can use to interpret
59 the data.
60 """
61 from IPython.utils import io
62 # The default is to simply write the plain text data using io.Term.
63 if data.has_key('text/plain'):
64 print >>io.Term.cout, data['text/plain']
65
66
67 def publish_display_data(source, text, svg=None, png=None,
68 html=None, metadata=None):
69 """Publish a display data to the frontends.
70
71 This function is a high level helper for the publishing of display data.
72 It handle a number of common MIME types in a clean API. For other MIME
73 types, use ``get_ipython().display_pub.publish`` directly.
74
75 Parameters
76 ----------
77 text : str/unicode
78 The string representation of the plot.
79
80 svn : str/unicode
81 The raw svg data of the plot.
82
83 png : ???
84 The raw png data of the plot.
85
86 metadata : dict, optional [default empty]
87 Allows for specification of additional information about the plot data.
88 """
89 from IPython.core.interactiveshell import InteractiveShell
90
91 data_dict = {}
92 data_dict['text/plain'] = text
93 if svg is not None:
94 data_dict['image/svg+xml'] = svg
95 if png is not None:
96 data_dict['image/png'] = png
97 if html is not None:
98 data_dict['text/html'] = html
99 InteractiveShell.instance().display_pub.publish(
100 source,
101 data_dict,
102 metadata
103 )
@@ -1,2543 +1,2550 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 __future__
22 22 import abc
23 23 import atexit
24 24 import codeop
25 25 import os
26 26 import re
27 27 import sys
28 28 import tempfile
29 29 import types
30 30 from contextlib import nested
31 31
32 32 from IPython.config.configurable import Configurable
33 33 from IPython.core import debugger, oinspect
34 34 from IPython.core import history as ipcorehist
35 35 from IPython.core import page
36 36 from IPython.core import prefilter
37 37 from IPython.core import shadowns
38 38 from IPython.core import ultratb
39 39 from IPython.core.alias import AliasManager
40 40 from IPython.core.builtin_trap import BuiltinTrap
41 41 from IPython.core.compilerop import CachingCompiler
42 42 from IPython.core.display_trap import DisplayTrap
43 43 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displaypub import DisplayPublisher
44 45 from IPython.core.error import TryNext, UsageError
45 46 from IPython.core.extensions import ExtensionManager
46 47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 48 from IPython.core.history import HistoryManager
48 49 from IPython.core.inputsplitter import IPythonInputSplitter
49 50 from IPython.core.logger import Logger
50 51 from IPython.core.magic import Magic
51 52 from IPython.core.payload import PayloadManager
52 53 from IPython.core.plugin import PluginManager
53 54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 55 from IPython.external.Itpl import ItplNS
55 56 from IPython.utils import PyColorize
56 57 from IPython.utils import io
57 58 from IPython.utils import pickleshare
58 59 from IPython.utils.doctestreload import doctest_reload
59 60 from IPython.utils.io import ask_yes_no, rprint
60 61 from IPython.utils.ipstruct import Struct
61 62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 63 from IPython.utils.process import system, getoutput
63 64 from IPython.utils.strdispatch import StrDispatch
64 65 from IPython.utils.syspathcontext import prepended_to_syspath
65 66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
66 67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 68 List, Unicode, Instance, Type)
68 69 from IPython.utils.warn import warn, error, fatal
69 70 import IPython.core.hooks
70 71
71 72 #-----------------------------------------------------------------------------
72 73 # Globals
73 74 #-----------------------------------------------------------------------------
74 75
75 76 # compiled regexps for autoindent management
76 77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 78
78 79 #-----------------------------------------------------------------------------
79 80 # Utilities
80 81 #-----------------------------------------------------------------------------
81 82
82 83 # store the builtin raw_input globally, and use this always, in case user code
83 84 # overwrites it (like wx.py.PyShell does)
84 85 raw_input_original = raw_input
85 86
86 87 def softspace(file, newvalue):
87 88 """Copied from code.py, to remove the dependency"""
88 89
89 90 oldvalue = 0
90 91 try:
91 92 oldvalue = file.softspace
92 93 except AttributeError:
93 94 pass
94 95 try:
95 96 file.softspace = newvalue
96 97 except (AttributeError, TypeError):
97 98 # "attribute-less object" or "read-only attributes"
98 99 pass
99 100 return oldvalue
100 101
101 102
102 103 def no_op(*a, **kw): pass
103 104
104 105 class SpaceInInput(Exception): pass
105 106
106 107 class Bunch: pass
107 108
108 109
109 110 def get_default_colors():
110 111 if sys.platform=='darwin':
111 112 return "LightBG"
112 113 elif os.name=='nt':
113 114 return 'Linux'
114 115 else:
115 116 return 'Linux'
116 117
117 118
118 119 class SeparateStr(Str):
119 120 """A Str subclass to validate separate_in, separate_out, etc.
120 121
121 122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 123 """
123 124
124 125 def validate(self, obj, value):
125 126 if value == '0': value = ''
126 127 value = value.replace('\\n','\n')
127 128 return super(SeparateStr, self).validate(obj, value)
128 129
129 130 class MultipleInstanceError(Exception):
130 131 pass
131 132
132 133
133 134 #-----------------------------------------------------------------------------
134 135 # Main IPython class
135 136 #-----------------------------------------------------------------------------
136 137
137 138 class InteractiveShell(Configurable, Magic):
138 139 """An enhanced, interactive shell for Python."""
139 140
140 141 _instance = None
141 142 autocall = Enum((0,1,2), default_value=1, config=True)
142 143 # TODO: remove all autoindent logic and put into frontends.
143 144 # We can't do this yet because even runlines uses the autoindent.
144 145 autoindent = CBool(True, config=True)
145 146 automagic = CBool(True, config=True)
146 147 cache_size = Int(1000, config=True)
147 148 color_info = CBool(True, config=True)
148 149 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
149 150 default_value=get_default_colors(), config=True)
150 151 debug = CBool(False, config=True)
151 152 deep_reload = CBool(False, config=True)
152 153 displayhook_class = Type(DisplayHook)
154 display_pub_class = Type(DisplayPublisher)
155
153 156 exit_now = CBool(False)
154 157 # Monotonically increasing execution counter
155 158 execution_count = Int(1)
156 159 filename = Str("<ipython console>")
157 160 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 161
159 162 # Input splitter, to split entire cells of input into either individual
160 163 # interactive statements or whole blocks.
161 164 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 165 (), {})
163 166 logstart = CBool(False, config=True)
164 167 logfile = Str('', config=True)
165 168 logappend = Str('', config=True)
166 169 object_info_string_level = Enum((0,1,2), default_value=0,
167 170 config=True)
168 171 pdb = CBool(False, config=True)
169 172
170 173 pprint = CBool(True, config=True)
171 174 profile = Str('', config=True)
172 175 prompt_in1 = Str('In [\\#]: ', config=True)
173 176 prompt_in2 = Str(' .\\D.: ', config=True)
174 177 prompt_out = Str('Out[\\#]: ', config=True)
175 178 prompts_pad_left = CBool(True, config=True)
176 179 quiet = CBool(False, config=True)
177 180
178 181 history_length = Int(10000, config=True)
179 182
180 183 # The readline stuff will eventually be moved to the terminal subclass
181 184 # but for now, we can't do that as readline is welded in everywhere.
182 185 readline_use = CBool(True, config=True)
183 186 readline_merge_completions = CBool(True, config=True)
184 187 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
185 188 readline_remove_delims = Str('-/~', config=True)
186 189 readline_parse_and_bind = List([
187 190 'tab: complete',
188 191 '"\C-l": clear-screen',
189 192 'set show-all-if-ambiguous on',
190 193 '"\C-o": tab-insert',
191 194 '"\M-i": " "',
192 195 '"\M-o": "\d\d\d\d"',
193 196 '"\M-I": "\d\d\d\d"',
194 197 '"\C-r": reverse-search-history',
195 198 '"\C-s": forward-search-history',
196 199 '"\C-p": history-search-backward',
197 200 '"\C-n": history-search-forward',
198 201 '"\e[A": history-search-backward',
199 202 '"\e[B": history-search-forward',
200 203 '"\C-k": kill-line',
201 204 '"\C-u": unix-line-discard',
202 205 ], allow_none=False, config=True)
203 206
204 207 # TODO: this part of prompt management should be moved to the frontends.
205 208 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
206 209 separate_in = SeparateStr('\n', config=True)
207 210 separate_out = SeparateStr('', config=True)
208 211 separate_out2 = SeparateStr('', config=True)
209 212 wildcards_case_sensitive = CBool(True, config=True)
210 213 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
211 214 default_value='Context', config=True)
212 215
213 216 # Subcomponents of InteractiveShell
214 217 alias_manager = Instance('IPython.core.alias.AliasManager')
215 218 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
216 219 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
217 220 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
218 221 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
219 222 plugin_manager = Instance('IPython.core.plugin.PluginManager')
220 223 payload_manager = Instance('IPython.core.payload.PayloadManager')
221 224 history_manager = Instance('IPython.core.history.HistoryManager')
222 225
223 226 # Private interface
224 227 _post_execute = set()
225 228
226 229 def __init__(self, config=None, ipython_dir=None,
227 230 user_ns=None, user_global_ns=None,
228 231 custom_exceptions=((), None)):
229 232
230 233 # This is where traits with a config_key argument are updated
231 234 # from the values on config.
232 235 super(InteractiveShell, self).__init__(config=config)
233 236
234 237 # These are relatively independent and stateless
235 238 self.init_ipython_dir(ipython_dir)
236 239 self.init_instance_attrs()
237 240 self.init_environment()
238 241
239 242 # Create namespaces (user_ns, user_global_ns, etc.)
240 243 self.init_create_namespaces(user_ns, user_global_ns)
241 244 # This has to be done after init_create_namespaces because it uses
242 245 # something in self.user_ns, but before init_sys_modules, which
243 246 # is the first thing to modify sys.
244 247 # TODO: When we override sys.stdout and sys.stderr before this class
245 248 # is created, we are saving the overridden ones here. Not sure if this
246 249 # is what we want to do.
247 250 self.save_sys_module_state()
248 251 self.init_sys_modules()
249 252
250 253 self.init_history()
251 254 self.init_encoding()
252 255 self.init_prefilter()
253 256
254 257 Magic.__init__(self, self)
255 258
256 259 self.init_syntax_highlighting()
257 260 self.init_hooks()
258 261 self.init_pushd_popd_magic()
259 262 # self.init_traceback_handlers use to be here, but we moved it below
260 263 # because it and init_io have to come after init_readline.
261 264 self.init_user_ns()
262 265 self.init_logger()
263 266 self.init_alias()
264 267 self.init_builtins()
265 268
266 269 # pre_config_initialization
267 270
268 271 # The next section should contain everything that was in ipmaker.
269 272 self.init_logstart()
270 273
271 274 # The following was in post_config_initialization
272 275 self.init_inspector()
273 276 # init_readline() must come before init_io(), because init_io uses
274 277 # readline related things.
275 278 self.init_readline()
276 279 # init_completer must come after init_readline, because it needs to
277 280 # know whether readline is present or not system-wide to configure the
278 281 # completers, since the completion machinery can now operate
279 282 # independently of readline (e.g. over the network)
280 283 self.init_completer()
281 284 # TODO: init_io() needs to happen before init_traceback handlers
282 285 # because the traceback handlers hardcode the stdout/stderr streams.
283 286 # This logic in in debugger.Pdb and should eventually be changed.
284 287 self.init_io()
285 288 self.init_traceback_handlers(custom_exceptions)
286 289 self.init_prompts()
290 self.init_display_pub()
287 291 self.init_displayhook()
288 292 self.init_reload_doctest()
289 293 self.init_magics()
290 294 self.init_pdb()
291 295 self.init_extension_manager()
292 296 self.init_plugin_manager()
293 297 self.init_payload()
294 298 self.hooks.late_startup_hook()
295 299 atexit.register(self.atexit_operations)
296 300
297 301 # While we're trying to have each part of the code directly access what it
298 302 # needs without keeping redundant references to objects, we have too much
299 303 # legacy code that expects ip.db to exist, so let's make it a property that
300 304 # retrieves the underlying object from our new history manager.
301 305 @property
302 306 def db(self):
303 307 return self.history_manager.shadow_db
304 308
305 309 @classmethod
306 310 def instance(cls, *args, **kwargs):
307 311 """Returns a global InteractiveShell instance."""
308 312 if cls._instance is None:
309 313 inst = cls(*args, **kwargs)
310 314 # Now make sure that the instance will also be returned by
311 315 # the subclasses instance attribute.
312 316 for subclass in cls.mro():
313 317 if issubclass(cls, subclass) and \
314 318 issubclass(subclass, InteractiveShell):
315 319 subclass._instance = inst
316 320 else:
317 321 break
318 322 if isinstance(cls._instance, cls):
319 323 return cls._instance
320 324 else:
321 325 raise MultipleInstanceError(
322 326 'Multiple incompatible subclass instances of '
323 327 'InteractiveShell are being created.'
324 328 )
325 329
326 330 @classmethod
327 331 def initialized(cls):
328 332 return hasattr(cls, "_instance")
329 333
330 334 def get_ipython(self):
331 335 """Return the currently running IPython instance."""
332 336 return self
333 337
334 338 #-------------------------------------------------------------------------
335 339 # Trait changed handlers
336 340 #-------------------------------------------------------------------------
337 341
338 342 def _ipython_dir_changed(self, name, new):
339 343 if not os.path.isdir(new):
340 344 os.makedirs(new, mode = 0777)
341 345
342 346 def set_autoindent(self,value=None):
343 347 """Set the autoindent flag, checking for readline support.
344 348
345 349 If called with no arguments, it acts as a toggle."""
346 350
347 351 if not self.has_readline:
348 352 if os.name == 'posix':
349 353 warn("The auto-indent feature requires the readline library")
350 354 self.autoindent = 0
351 355 return
352 356 if value is None:
353 357 self.autoindent = not self.autoindent
354 358 else:
355 359 self.autoindent = value
356 360
357 361 #-------------------------------------------------------------------------
358 362 # init_* methods called by __init__
359 363 #-------------------------------------------------------------------------
360 364
361 365 def init_ipython_dir(self, ipython_dir):
362 366 if ipython_dir is not None:
363 367 self.ipython_dir = ipython_dir
364 368 self.config.Global.ipython_dir = self.ipython_dir
365 369 return
366 370
367 371 if hasattr(self.config.Global, 'ipython_dir'):
368 372 self.ipython_dir = self.config.Global.ipython_dir
369 373 else:
370 374 self.ipython_dir = get_ipython_dir()
371 375
372 376 # All children can just read this
373 377 self.config.Global.ipython_dir = self.ipython_dir
374 378
375 379 def init_instance_attrs(self):
376 380 self.more = False
377 381
378 382 # command compiler
379 383 self.compile = CachingCompiler()
380 384
381 385 # User input buffers
382 386 # NOTE: these variables are slated for full removal, once we are 100%
383 387 # sure that the new execution logic is solid. We will delte runlines,
384 388 # push_line and these buffers, as all input will be managed by the
385 389 # frontends via an inputsplitter instance.
386 390 self.buffer = []
387 391 self.buffer_raw = []
388 392
389 393 # Make an empty namespace, which extension writers can rely on both
390 394 # existing and NEVER being used by ipython itself. This gives them a
391 395 # convenient location for storing additional information and state
392 396 # their extensions may require, without fear of collisions with other
393 397 # ipython names that may develop later.
394 398 self.meta = Struct()
395 399
396 400 # Object variable to store code object waiting execution. This is
397 401 # used mainly by the multithreaded shells, but it can come in handy in
398 402 # other situations. No need to use a Queue here, since it's a single
399 403 # item which gets cleared once run.
400 404 self.code_to_run = None
401 405
402 406 # Temporary files used for various purposes. Deleted at exit.
403 407 self.tempfiles = []
404 408
405 409 # Keep track of readline usage (later set by init_readline)
406 410 self.has_readline = False
407 411
408 412 # keep track of where we started running (mainly for crash post-mortem)
409 413 # This is not being used anywhere currently.
410 414 self.starting_dir = os.getcwd()
411 415
412 416 # Indentation management
413 417 self.indent_current_nsp = 0
414 418
415 419 def init_environment(self):
416 420 """Any changes we need to make to the user's environment."""
417 421 pass
418 422
419 423 def init_encoding(self):
420 424 # Get system encoding at startup time. Certain terminals (like Emacs
421 425 # under Win32 have it set to None, and we need to have a known valid
422 426 # encoding to use in the raw_input() method
423 427 try:
424 428 self.stdin_encoding = sys.stdin.encoding or 'ascii'
425 429 except AttributeError:
426 430 self.stdin_encoding = 'ascii'
427 431
428 432 def init_syntax_highlighting(self):
429 433 # Python source parser/formatter for syntax highlighting
430 434 pyformat = PyColorize.Parser().format
431 435 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
432 436
433 437 def init_pushd_popd_magic(self):
434 438 # for pushd/popd management
435 439 try:
436 440 self.home_dir = get_home_dir()
437 441 except HomeDirError, msg:
438 442 fatal(msg)
439 443
440 444 self.dir_stack = []
441 445
442 446 def init_logger(self):
443 447 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
444 448 logmode='rotate')
445 449
446 450 def init_logstart(self):
447 451 """Initialize logging in case it was requested at the command line.
448 452 """
449 453 if self.logappend:
450 454 self.magic_logstart(self.logappend + ' append')
451 455 elif self.logfile:
452 456 self.magic_logstart(self.logfile)
453 457 elif self.logstart:
454 458 self.magic_logstart()
455 459
456 460 def init_builtins(self):
457 461 self.builtin_trap = BuiltinTrap(shell=self)
458 462
459 463 def init_inspector(self):
460 464 # Object inspector
461 465 self.inspector = oinspect.Inspector(oinspect.InspectColors,
462 466 PyColorize.ANSICodeColors,
463 467 'NoColor',
464 468 self.object_info_string_level)
465 469
466 470 def init_io(self):
467 471 # This will just use sys.stdout and sys.stderr. If you want to
468 472 # override sys.stdout and sys.stderr themselves, you need to do that
469 473 # *before* instantiating this class, because Term holds onto
470 474 # references to the underlying streams.
471 475 if sys.platform == 'win32' and self.has_readline:
472 476 Term = io.IOTerm(cout=self.readline._outputfile,
473 477 cerr=self.readline._outputfile)
474 478 else:
475 479 Term = io.IOTerm()
476 480 io.Term = Term
477 481
478 482 def init_prompts(self):
479 483 # TODO: This is a pass for now because the prompts are managed inside
480 484 # the DisplayHook. Once there is a separate prompt manager, this
481 485 # will initialize that object and all prompt related information.
482 486 pass
483 487
488 def init_display_pub(self):
489 self.display_pub = self.display_pub_class(config=self.config)
490
484 491 def init_displayhook(self):
485 492 # Initialize displayhook, set in/out prompts and printing system
486 493 self.displayhook = self.displayhook_class(
487 494 config=self.config,
488 495 shell=self,
489 496 cache_size=self.cache_size,
490 497 input_sep = self.separate_in,
491 498 output_sep = self.separate_out,
492 499 output_sep2 = self.separate_out2,
493 500 ps1 = self.prompt_in1,
494 501 ps2 = self.prompt_in2,
495 502 ps_out = self.prompt_out,
496 503 pad_left = self.prompts_pad_left
497 504 )
498 505 # This is a context manager that installs/revmoes the displayhook at
499 506 # the appropriate time.
500 507 self.display_trap = DisplayTrap(hook=self.displayhook)
501 508
502 509 def init_reload_doctest(self):
503 510 # Do a proper resetting of doctest, including the necessary displayhook
504 511 # monkeypatching
505 512 try:
506 513 doctest_reload()
507 514 except ImportError:
508 515 warn("doctest module does not exist.")
509 516
510 517 #-------------------------------------------------------------------------
511 518 # Things related to injections into the sys module
512 519 #-------------------------------------------------------------------------
513 520
514 521 def save_sys_module_state(self):
515 522 """Save the state of hooks in the sys module.
516 523
517 524 This has to be called after self.user_ns is created.
518 525 """
519 526 self._orig_sys_module_state = {}
520 527 self._orig_sys_module_state['stdin'] = sys.stdin
521 528 self._orig_sys_module_state['stdout'] = sys.stdout
522 529 self._orig_sys_module_state['stderr'] = sys.stderr
523 530 self._orig_sys_module_state['excepthook'] = sys.excepthook
524 531 try:
525 532 self._orig_sys_modules_main_name = self.user_ns['__name__']
526 533 except KeyError:
527 534 pass
528 535
529 536 def restore_sys_module_state(self):
530 537 """Restore the state of the sys module."""
531 538 try:
532 539 for k, v in self._orig_sys_module_state.iteritems():
533 540 setattr(sys, k, v)
534 541 except AttributeError:
535 542 pass
536 543 # Reset what what done in self.init_sys_modules
537 544 try:
538 545 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
539 546 except (AttributeError, KeyError):
540 547 pass
541 548
542 549 #-------------------------------------------------------------------------
543 550 # Things related to hooks
544 551 #-------------------------------------------------------------------------
545 552
546 553 def init_hooks(self):
547 554 # hooks holds pointers used for user-side customizations
548 555 self.hooks = Struct()
549 556
550 557 self.strdispatchers = {}
551 558
552 559 # Set all default hooks, defined in the IPython.hooks module.
553 560 hooks = IPython.core.hooks
554 561 for hook_name in hooks.__all__:
555 562 # default hooks have priority 100, i.e. low; user hooks should have
556 563 # 0-100 priority
557 564 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
558 565
559 566 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
560 567 """set_hook(name,hook) -> sets an internal IPython hook.
561 568
562 569 IPython exposes some of its internal API as user-modifiable hooks. By
563 570 adding your function to one of these hooks, you can modify IPython's
564 571 behavior to call at runtime your own routines."""
565 572
566 573 # At some point in the future, this should validate the hook before it
567 574 # accepts it. Probably at least check that the hook takes the number
568 575 # of args it's supposed to.
569 576
570 577 f = types.MethodType(hook,self)
571 578
572 579 # check if the hook is for strdispatcher first
573 580 if str_key is not None:
574 581 sdp = self.strdispatchers.get(name, StrDispatch())
575 582 sdp.add_s(str_key, f, priority )
576 583 self.strdispatchers[name] = sdp
577 584 return
578 585 if re_key is not None:
579 586 sdp = self.strdispatchers.get(name, StrDispatch())
580 587 sdp.add_re(re.compile(re_key), f, priority )
581 588 self.strdispatchers[name] = sdp
582 589 return
583 590
584 591 dp = getattr(self.hooks, name, None)
585 592 if name not in IPython.core.hooks.__all__:
586 593 print "Warning! Hook '%s' is not one of %s" % \
587 594 (name, IPython.core.hooks.__all__ )
588 595 if not dp:
589 596 dp = IPython.core.hooks.CommandChainDispatcher()
590 597
591 598 try:
592 599 dp.add(f,priority)
593 600 except AttributeError:
594 601 # it was not commandchain, plain old func - replace
595 602 dp = f
596 603
597 604 setattr(self.hooks,name, dp)
598 605
599 606 def register_post_execute(self, func):
600 607 """Register a function for calling after code execution.
601 608 """
602 609 if not callable(func):
603 610 raise ValueError('argument %s must be callable' % func)
604 611 self._post_execute.add(func)
605 612
606 613 #-------------------------------------------------------------------------
607 614 # Things related to the "main" module
608 615 #-------------------------------------------------------------------------
609 616
610 617 def new_main_mod(self,ns=None):
611 618 """Return a new 'main' module object for user code execution.
612 619 """
613 620 main_mod = self._user_main_module
614 621 init_fakemod_dict(main_mod,ns)
615 622 return main_mod
616 623
617 624 def cache_main_mod(self,ns,fname):
618 625 """Cache a main module's namespace.
619 626
620 627 When scripts are executed via %run, we must keep a reference to the
621 628 namespace of their __main__ module (a FakeModule instance) around so
622 629 that Python doesn't clear it, rendering objects defined therein
623 630 useless.
624 631
625 632 This method keeps said reference in a private dict, keyed by the
626 633 absolute path of the module object (which corresponds to the script
627 634 path). This way, for multiple executions of the same script we only
628 635 keep one copy of the namespace (the last one), thus preventing memory
629 636 leaks from old references while allowing the objects from the last
630 637 execution to be accessible.
631 638
632 639 Note: we can not allow the actual FakeModule instances to be deleted,
633 640 because of how Python tears down modules (it hard-sets all their
634 641 references to None without regard for reference counts). This method
635 642 must therefore make a *copy* of the given namespace, to allow the
636 643 original module's __dict__ to be cleared and reused.
637 644
638 645
639 646 Parameters
640 647 ----------
641 648 ns : a namespace (a dict, typically)
642 649
643 650 fname : str
644 651 Filename associated with the namespace.
645 652
646 653 Examples
647 654 --------
648 655
649 656 In [10]: import IPython
650 657
651 658 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
652 659
653 660 In [12]: IPython.__file__ in _ip._main_ns_cache
654 661 Out[12]: True
655 662 """
656 663 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
657 664
658 665 def clear_main_mod_cache(self):
659 666 """Clear the cache of main modules.
660 667
661 668 Mainly for use by utilities like %reset.
662 669
663 670 Examples
664 671 --------
665 672
666 673 In [15]: import IPython
667 674
668 675 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
669 676
670 677 In [17]: len(_ip._main_ns_cache) > 0
671 678 Out[17]: True
672 679
673 680 In [18]: _ip.clear_main_mod_cache()
674 681
675 682 In [19]: len(_ip._main_ns_cache) == 0
676 683 Out[19]: True
677 684 """
678 685 self._main_ns_cache.clear()
679 686
680 687 #-------------------------------------------------------------------------
681 688 # Things related to debugging
682 689 #-------------------------------------------------------------------------
683 690
684 691 def init_pdb(self):
685 692 # Set calling of pdb on exceptions
686 693 # self.call_pdb is a property
687 694 self.call_pdb = self.pdb
688 695
689 696 def _get_call_pdb(self):
690 697 return self._call_pdb
691 698
692 699 def _set_call_pdb(self,val):
693 700
694 701 if val not in (0,1,False,True):
695 702 raise ValueError,'new call_pdb value must be boolean'
696 703
697 704 # store value in instance
698 705 self._call_pdb = val
699 706
700 707 # notify the actual exception handlers
701 708 self.InteractiveTB.call_pdb = val
702 709
703 710 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
704 711 'Control auto-activation of pdb at exceptions')
705 712
706 713 def debugger(self,force=False):
707 714 """Call the pydb/pdb debugger.
708 715
709 716 Keywords:
710 717
711 718 - force(False): by default, this routine checks the instance call_pdb
712 719 flag and does not actually invoke the debugger if the flag is false.
713 720 The 'force' option forces the debugger to activate even if the flag
714 721 is false.
715 722 """
716 723
717 724 if not (force or self.call_pdb):
718 725 return
719 726
720 727 if not hasattr(sys,'last_traceback'):
721 728 error('No traceback has been produced, nothing to debug.')
722 729 return
723 730
724 731 # use pydb if available
725 732 if debugger.has_pydb:
726 733 from pydb import pm
727 734 else:
728 735 # fallback to our internal debugger
729 736 pm = lambda : self.InteractiveTB.debugger(force=True)
730 737 self.history_saving_wrapper(pm)()
731 738
732 739 #-------------------------------------------------------------------------
733 740 # Things related to IPython's various namespaces
734 741 #-------------------------------------------------------------------------
735 742
736 743 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
737 744 # Create the namespace where the user will operate. user_ns is
738 745 # normally the only one used, and it is passed to the exec calls as
739 746 # the locals argument. But we do carry a user_global_ns namespace
740 747 # given as the exec 'globals' argument, This is useful in embedding
741 748 # situations where the ipython shell opens in a context where the
742 749 # distinction between locals and globals is meaningful. For
743 750 # non-embedded contexts, it is just the same object as the user_ns dict.
744 751
745 752 # FIXME. For some strange reason, __builtins__ is showing up at user
746 753 # level as a dict instead of a module. This is a manual fix, but I
747 754 # should really track down where the problem is coming from. Alex
748 755 # Schmolck reported this problem first.
749 756
750 757 # A useful post by Alex Martelli on this topic:
751 758 # Re: inconsistent value from __builtins__
752 759 # Von: Alex Martelli <aleaxit@yahoo.com>
753 760 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
754 761 # Gruppen: comp.lang.python
755 762
756 763 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
757 764 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
758 765 # > <type 'dict'>
759 766 # > >>> print type(__builtins__)
760 767 # > <type 'module'>
761 768 # > Is this difference in return value intentional?
762 769
763 770 # Well, it's documented that '__builtins__' can be either a dictionary
764 771 # or a module, and it's been that way for a long time. Whether it's
765 772 # intentional (or sensible), I don't know. In any case, the idea is
766 773 # that if you need to access the built-in namespace directly, you
767 774 # should start with "import __builtin__" (note, no 's') which will
768 775 # definitely give you a module. Yeah, it's somewhat confusing:-(.
769 776
770 777 # These routines return properly built dicts as needed by the rest of
771 778 # the code, and can also be used by extension writers to generate
772 779 # properly initialized namespaces.
773 780 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
774 781 user_global_ns)
775 782
776 783 # Assign namespaces
777 784 # This is the namespace where all normal user variables live
778 785 self.user_ns = user_ns
779 786 self.user_global_ns = user_global_ns
780 787
781 788 # An auxiliary namespace that checks what parts of the user_ns were
782 789 # loaded at startup, so we can list later only variables defined in
783 790 # actual interactive use. Since it is always a subset of user_ns, it
784 791 # doesn't need to be separately tracked in the ns_table.
785 792 self.user_ns_hidden = {}
786 793
787 794 # A namespace to keep track of internal data structures to prevent
788 795 # them from cluttering user-visible stuff. Will be updated later
789 796 self.internal_ns = {}
790 797
791 798 # Now that FakeModule produces a real module, we've run into a nasty
792 799 # problem: after script execution (via %run), the module where the user
793 800 # code ran is deleted. Now that this object is a true module (needed
794 801 # so docetst and other tools work correctly), the Python module
795 802 # teardown mechanism runs over it, and sets to None every variable
796 803 # present in that module. Top-level references to objects from the
797 804 # script survive, because the user_ns is updated with them. However,
798 805 # calling functions defined in the script that use other things from
799 806 # the script will fail, because the function's closure had references
800 807 # to the original objects, which are now all None. So we must protect
801 808 # these modules from deletion by keeping a cache.
802 809 #
803 810 # To avoid keeping stale modules around (we only need the one from the
804 811 # last run), we use a dict keyed with the full path to the script, so
805 812 # only the last version of the module is held in the cache. Note,
806 813 # however, that we must cache the module *namespace contents* (their
807 814 # __dict__). Because if we try to cache the actual modules, old ones
808 815 # (uncached) could be destroyed while still holding references (such as
809 816 # those held by GUI objects that tend to be long-lived)>
810 817 #
811 818 # The %reset command will flush this cache. See the cache_main_mod()
812 819 # and clear_main_mod_cache() methods for details on use.
813 820
814 821 # This is the cache used for 'main' namespaces
815 822 self._main_ns_cache = {}
816 823 # And this is the single instance of FakeModule whose __dict__ we keep
817 824 # copying and clearing for reuse on each %run
818 825 self._user_main_module = FakeModule()
819 826
820 827 # A table holding all the namespaces IPython deals with, so that
821 828 # introspection facilities can search easily.
822 829 self.ns_table = {'user':user_ns,
823 830 'user_global':user_global_ns,
824 831 'internal':self.internal_ns,
825 832 'builtin':__builtin__.__dict__
826 833 }
827 834
828 835 # Similarly, track all namespaces where references can be held and that
829 836 # we can safely clear (so it can NOT include builtin). This one can be
830 837 # a simple list. Note that the main execution namespaces, user_ns and
831 838 # user_global_ns, can NOT be listed here, as clearing them blindly
832 839 # causes errors in object __del__ methods. Instead, the reset() method
833 840 # clears them manually and carefully.
834 841 self.ns_refs_table = [ self.user_ns_hidden,
835 842 self.internal_ns, self._main_ns_cache ]
836 843
837 844 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
838 845 """Return a valid local and global user interactive namespaces.
839 846
840 847 This builds a dict with the minimal information needed to operate as a
841 848 valid IPython user namespace, which you can pass to the various
842 849 embedding classes in ipython. The default implementation returns the
843 850 same dict for both the locals and the globals to allow functions to
844 851 refer to variables in the namespace. Customized implementations can
845 852 return different dicts. The locals dictionary can actually be anything
846 853 following the basic mapping protocol of a dict, but the globals dict
847 854 must be a true dict, not even a subclass. It is recommended that any
848 855 custom object for the locals namespace synchronize with the globals
849 856 dict somehow.
850 857
851 858 Raises TypeError if the provided globals namespace is not a true dict.
852 859
853 860 Parameters
854 861 ----------
855 862 user_ns : dict-like, optional
856 863 The current user namespace. The items in this namespace should
857 864 be included in the output. If None, an appropriate blank
858 865 namespace should be created.
859 866 user_global_ns : dict, optional
860 867 The current user global namespace. The items in this namespace
861 868 should be included in the output. If None, an appropriate
862 869 blank namespace should be created.
863 870
864 871 Returns
865 872 -------
866 873 A pair of dictionary-like object to be used as the local namespace
867 874 of the interpreter and a dict to be used as the global namespace.
868 875 """
869 876
870 877
871 878 # We must ensure that __builtin__ (without the final 's') is always
872 879 # available and pointing to the __builtin__ *module*. For more details:
873 880 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
874 881
875 882 if user_ns is None:
876 883 # Set __name__ to __main__ to better match the behavior of the
877 884 # normal interpreter.
878 885 user_ns = {'__name__' :'__main__',
879 886 '__builtin__' : __builtin__,
880 887 '__builtins__' : __builtin__,
881 888 }
882 889 else:
883 890 user_ns.setdefault('__name__','__main__')
884 891 user_ns.setdefault('__builtin__',__builtin__)
885 892 user_ns.setdefault('__builtins__',__builtin__)
886 893
887 894 if user_global_ns is None:
888 895 user_global_ns = user_ns
889 896 if type(user_global_ns) is not dict:
890 897 raise TypeError("user_global_ns must be a true dict; got %r"
891 898 % type(user_global_ns))
892 899
893 900 return user_ns, user_global_ns
894 901
895 902 def init_sys_modules(self):
896 903 # We need to insert into sys.modules something that looks like a
897 904 # module but which accesses the IPython namespace, for shelve and
898 905 # pickle to work interactively. Normally they rely on getting
899 906 # everything out of __main__, but for embedding purposes each IPython
900 907 # instance has its own private namespace, so we can't go shoving
901 908 # everything into __main__.
902 909
903 910 # note, however, that we should only do this for non-embedded
904 911 # ipythons, which really mimic the __main__.__dict__ with their own
905 912 # namespace. Embedded instances, on the other hand, should not do
906 913 # this because they need to manage the user local/global namespaces
907 914 # only, but they live within a 'normal' __main__ (meaning, they
908 915 # shouldn't overtake the execution environment of the script they're
909 916 # embedded in).
910 917
911 918 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
912 919
913 920 try:
914 921 main_name = self.user_ns['__name__']
915 922 except KeyError:
916 923 raise KeyError('user_ns dictionary MUST have a "__name__" key')
917 924 else:
918 925 sys.modules[main_name] = FakeModule(self.user_ns)
919 926
920 927 def init_user_ns(self):
921 928 """Initialize all user-visible namespaces to their minimum defaults.
922 929
923 930 Certain history lists are also initialized here, as they effectively
924 931 act as user namespaces.
925 932
926 933 Notes
927 934 -----
928 935 All data structures here are only filled in, they are NOT reset by this
929 936 method. If they were not empty before, data will simply be added to
930 937 therm.
931 938 """
932 939 # This function works in two parts: first we put a few things in
933 940 # user_ns, and we sync that contents into user_ns_hidden so that these
934 941 # initial variables aren't shown by %who. After the sync, we add the
935 942 # rest of what we *do* want the user to see with %who even on a new
936 943 # session (probably nothing, so theye really only see their own stuff)
937 944
938 945 # The user dict must *always* have a __builtin__ reference to the
939 946 # Python standard __builtin__ namespace, which must be imported.
940 947 # This is so that certain operations in prompt evaluation can be
941 948 # reliably executed with builtins. Note that we can NOT use
942 949 # __builtins__ (note the 's'), because that can either be a dict or a
943 950 # module, and can even mutate at runtime, depending on the context
944 951 # (Python makes no guarantees on it). In contrast, __builtin__ is
945 952 # always a module object, though it must be explicitly imported.
946 953
947 954 # For more details:
948 955 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
949 956 ns = dict(__builtin__ = __builtin__)
950 957
951 958 # Put 'help' in the user namespace
952 959 try:
953 960 from site import _Helper
954 961 ns['help'] = _Helper()
955 962 except ImportError:
956 963 warn('help() not available - check site.py')
957 964
958 965 # make global variables for user access to the histories
959 966 ns['_ih'] = self.history_manager.input_hist_parsed
960 967 ns['_oh'] = self.history_manager.output_hist
961 968 ns['_dh'] = self.history_manager.dir_hist
962 969
963 970 ns['_sh'] = shadowns
964 971
965 972 # user aliases to input and output histories. These shouldn't show up
966 973 # in %who, as they can have very large reprs.
967 974 ns['In'] = self.history_manager.input_hist_parsed
968 975 ns['Out'] = self.history_manager.output_hist
969 976
970 977 # Store myself as the public api!!!
971 978 ns['get_ipython'] = self.get_ipython
972 979
973 980 # Sync what we've added so far to user_ns_hidden so these aren't seen
974 981 # by %who
975 982 self.user_ns_hidden.update(ns)
976 983
977 984 # Anything put into ns now would show up in %who. Think twice before
978 985 # putting anything here, as we really want %who to show the user their
979 986 # stuff, not our variables.
980 987
981 988 # Finally, update the real user's namespace
982 989 self.user_ns.update(ns)
983 990
984 991 def reset(self):
985 992 """Clear all internal namespaces.
986 993
987 994 Note that this is much more aggressive than %reset, since it clears
988 995 fully all namespaces, as well as all input/output lists.
989 996 """
990 997 # Clear histories
991 998 self.history_manager.reset()
992 999
993 1000 # Reset counter used to index all histories
994 1001 self.execution_count = 0
995 1002
996 1003 # Restore the user namespaces to minimal usability
997 1004 for ns in self.ns_refs_table:
998 1005 ns.clear()
999 1006
1000 1007 # The main execution namespaces must be cleared very carefully,
1001 1008 # skipping the deletion of the builtin-related keys, because doing so
1002 1009 # would cause errors in many object's __del__ methods.
1003 1010 for ns in [self.user_ns, self.user_global_ns]:
1004 1011 drop_keys = set(ns.keys())
1005 1012 drop_keys.discard('__builtin__')
1006 1013 drop_keys.discard('__builtins__')
1007 1014 for k in drop_keys:
1008 1015 del ns[k]
1009 1016
1010 1017 # Restore the user namespaces to minimal usability
1011 1018 self.init_user_ns()
1012 1019
1013 1020 # Restore the default and user aliases
1014 1021 self.alias_manager.clear_aliases()
1015 1022 self.alias_manager.init_aliases()
1016 1023
1017 1024 def reset_selective(self, regex=None):
1018 1025 """Clear selective variables from internal namespaces based on a
1019 1026 specified regular expression.
1020 1027
1021 1028 Parameters
1022 1029 ----------
1023 1030 regex : string or compiled pattern, optional
1024 1031 A regular expression pattern that will be used in searching
1025 1032 variable names in the users namespaces.
1026 1033 """
1027 1034 if regex is not None:
1028 1035 try:
1029 1036 m = re.compile(regex)
1030 1037 except TypeError:
1031 1038 raise TypeError('regex must be a string or compiled pattern')
1032 1039 # Search for keys in each namespace that match the given regex
1033 1040 # If a match is found, delete the key/value pair.
1034 1041 for ns in self.ns_refs_table:
1035 1042 for var in ns:
1036 1043 if m.search(var):
1037 1044 del ns[var]
1038 1045
1039 1046 def push(self, variables, interactive=True):
1040 1047 """Inject a group of variables into the IPython user namespace.
1041 1048
1042 1049 Parameters
1043 1050 ----------
1044 1051 variables : dict, str or list/tuple of str
1045 1052 The variables to inject into the user's namespace. If a dict, a
1046 1053 simple update is done. If a str, the string is assumed to have
1047 1054 variable names separated by spaces. A list/tuple of str can also
1048 1055 be used to give the variable names. If just the variable names are
1049 1056 give (list/tuple/str) then the variable values looked up in the
1050 1057 callers frame.
1051 1058 interactive : bool
1052 1059 If True (default), the variables will be listed with the ``who``
1053 1060 magic.
1054 1061 """
1055 1062 vdict = None
1056 1063
1057 1064 # We need a dict of name/value pairs to do namespace updates.
1058 1065 if isinstance(variables, dict):
1059 1066 vdict = variables
1060 1067 elif isinstance(variables, (basestring, list, tuple)):
1061 1068 if isinstance(variables, basestring):
1062 1069 vlist = variables.split()
1063 1070 else:
1064 1071 vlist = variables
1065 1072 vdict = {}
1066 1073 cf = sys._getframe(1)
1067 1074 for name in vlist:
1068 1075 try:
1069 1076 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1070 1077 except:
1071 1078 print ('Could not get variable %s from %s' %
1072 1079 (name,cf.f_code.co_name))
1073 1080 else:
1074 1081 raise ValueError('variables must be a dict/str/list/tuple')
1075 1082
1076 1083 # Propagate variables to user namespace
1077 1084 self.user_ns.update(vdict)
1078 1085
1079 1086 # And configure interactive visibility
1080 1087 config_ns = self.user_ns_hidden
1081 1088 if interactive:
1082 1089 for name, val in vdict.iteritems():
1083 1090 config_ns.pop(name, None)
1084 1091 else:
1085 1092 for name,val in vdict.iteritems():
1086 1093 config_ns[name] = val
1087 1094
1088 1095 #-------------------------------------------------------------------------
1089 1096 # Things related to object introspection
1090 1097 #-------------------------------------------------------------------------
1091 1098
1092 1099 def _ofind(self, oname, namespaces=None):
1093 1100 """Find an object in the available namespaces.
1094 1101
1095 1102 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1096 1103
1097 1104 Has special code to detect magic functions.
1098 1105 """
1099 1106 #oname = oname.strip()
1100 1107 #print '1- oname: <%r>' % oname # dbg
1101 1108 try:
1102 1109 oname = oname.strip().encode('ascii')
1103 1110 #print '2- oname: <%r>' % oname # dbg
1104 1111 except UnicodeEncodeError:
1105 1112 print 'Python identifiers can only contain ascii characters.'
1106 1113 return dict(found=False)
1107 1114
1108 1115 alias_ns = None
1109 1116 if namespaces is None:
1110 1117 # Namespaces to search in:
1111 1118 # Put them in a list. The order is important so that we
1112 1119 # find things in the same order that Python finds them.
1113 1120 namespaces = [ ('Interactive', self.user_ns),
1114 1121 ('IPython internal', self.internal_ns),
1115 1122 ('Python builtin', __builtin__.__dict__),
1116 1123 ('Alias', self.alias_manager.alias_table),
1117 1124 ]
1118 1125 alias_ns = self.alias_manager.alias_table
1119 1126
1120 1127 # initialize results to 'null'
1121 1128 found = False; obj = None; ospace = None; ds = None;
1122 1129 ismagic = False; isalias = False; parent = None
1123 1130
1124 1131 # We need to special-case 'print', which as of python2.6 registers as a
1125 1132 # function but should only be treated as one if print_function was
1126 1133 # loaded with a future import. In this case, just bail.
1127 1134 if (oname == 'print' and not (self.compile.compiler_flags &
1128 1135 __future__.CO_FUTURE_PRINT_FUNCTION)):
1129 1136 return {'found':found, 'obj':obj, 'namespace':ospace,
1130 1137 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1131 1138
1132 1139 # Look for the given name by splitting it in parts. If the head is
1133 1140 # found, then we look for all the remaining parts as members, and only
1134 1141 # declare success if we can find them all.
1135 1142 oname_parts = oname.split('.')
1136 1143 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1137 1144 for nsname,ns in namespaces:
1138 1145 try:
1139 1146 obj = ns[oname_head]
1140 1147 except KeyError:
1141 1148 continue
1142 1149 else:
1143 1150 #print 'oname_rest:', oname_rest # dbg
1144 1151 for part in oname_rest:
1145 1152 try:
1146 1153 parent = obj
1147 1154 obj = getattr(obj,part)
1148 1155 except:
1149 1156 # Blanket except b/c some badly implemented objects
1150 1157 # allow __getattr__ to raise exceptions other than
1151 1158 # AttributeError, which then crashes IPython.
1152 1159 break
1153 1160 else:
1154 1161 # If we finish the for loop (no break), we got all members
1155 1162 found = True
1156 1163 ospace = nsname
1157 1164 if ns == alias_ns:
1158 1165 isalias = True
1159 1166 break # namespace loop
1160 1167
1161 1168 # Try to see if it's magic
1162 1169 if not found:
1163 1170 if oname.startswith(ESC_MAGIC):
1164 1171 oname = oname[1:]
1165 1172 obj = getattr(self,'magic_'+oname,None)
1166 1173 if obj is not None:
1167 1174 found = True
1168 1175 ospace = 'IPython internal'
1169 1176 ismagic = True
1170 1177
1171 1178 # Last try: special-case some literals like '', [], {}, etc:
1172 1179 if not found and oname_head in ["''",'""','[]','{}','()']:
1173 1180 obj = eval(oname_head)
1174 1181 found = True
1175 1182 ospace = 'Interactive'
1176 1183
1177 1184 return {'found':found, 'obj':obj, 'namespace':ospace,
1178 1185 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1179 1186
1180 1187 def _ofind_property(self, oname, info):
1181 1188 """Second part of object finding, to look for property details."""
1182 1189 if info.found:
1183 1190 # Get the docstring of the class property if it exists.
1184 1191 path = oname.split('.')
1185 1192 root = '.'.join(path[:-1])
1186 1193 if info.parent is not None:
1187 1194 try:
1188 1195 target = getattr(info.parent, '__class__')
1189 1196 # The object belongs to a class instance.
1190 1197 try:
1191 1198 target = getattr(target, path[-1])
1192 1199 # The class defines the object.
1193 1200 if isinstance(target, property):
1194 1201 oname = root + '.__class__.' + path[-1]
1195 1202 info = Struct(self._ofind(oname))
1196 1203 except AttributeError: pass
1197 1204 except AttributeError: pass
1198 1205
1199 1206 # We return either the new info or the unmodified input if the object
1200 1207 # hadn't been found
1201 1208 return info
1202 1209
1203 1210 def _object_find(self, oname, namespaces=None):
1204 1211 """Find an object and return a struct with info about it."""
1205 1212 inf = Struct(self._ofind(oname, namespaces))
1206 1213 return Struct(self._ofind_property(oname, inf))
1207 1214
1208 1215 def _inspect(self, meth, oname, namespaces=None, **kw):
1209 1216 """Generic interface to the inspector system.
1210 1217
1211 1218 This function is meant to be called by pdef, pdoc & friends."""
1212 1219 info = self._object_find(oname)
1213 1220 if info.found:
1214 1221 pmethod = getattr(self.inspector, meth)
1215 1222 formatter = format_screen if info.ismagic else None
1216 1223 if meth == 'pdoc':
1217 1224 pmethod(info.obj, oname, formatter)
1218 1225 elif meth == 'pinfo':
1219 1226 pmethod(info.obj, oname, formatter, info, **kw)
1220 1227 else:
1221 1228 pmethod(info.obj, oname)
1222 1229 else:
1223 1230 print 'Object `%s` not found.' % oname
1224 1231 return 'not found' # so callers can take other action
1225 1232
1226 1233 def object_inspect(self, oname):
1227 1234 info = self._object_find(oname)
1228 1235 if info.found:
1229 1236 return self.inspector.info(info.obj, oname, info=info)
1230 1237 else:
1231 1238 return oinspect.object_info(name=oname, found=False)
1232 1239
1233 1240 #-------------------------------------------------------------------------
1234 1241 # Things related to history management
1235 1242 #-------------------------------------------------------------------------
1236 1243
1237 1244 def init_history(self):
1238 1245 """Sets up the command history, and starts regular autosaves."""
1239 1246 self.history_manager = HistoryManager(shell=self)
1240 1247
1241 1248 def save_history(self):
1242 1249 """Save input history to a file (via readline library)."""
1243 1250 self.history_manager.save_history()
1244 1251
1245 1252 def reload_history(self):
1246 1253 """Reload the input history from disk file."""
1247 1254 self.history_manager.reload_history()
1248 1255
1249 1256 def history_saving_wrapper(self, func):
1250 1257 """ Wrap func for readline history saving
1251 1258
1252 1259 Convert func into callable that saves & restores
1253 1260 history around the call """
1254 1261
1255 1262 if self.has_readline:
1256 1263 from IPython.utils import rlineimpl as readline
1257 1264 else:
1258 1265 return func
1259 1266
1260 1267 def wrapper():
1261 1268 self.save_history()
1262 1269 try:
1263 1270 func()
1264 1271 finally:
1265 1272 self.reload_history()
1266 1273 return wrapper
1267 1274
1268 1275 def get_history(self, index=None, raw=False, output=True):
1269 1276 return self.history_manager.get_history(index, raw, output)
1270 1277
1271 1278
1272 1279 #-------------------------------------------------------------------------
1273 1280 # Things related to exception handling and tracebacks (not debugging)
1274 1281 #-------------------------------------------------------------------------
1275 1282
1276 1283 def init_traceback_handlers(self, custom_exceptions):
1277 1284 # Syntax error handler.
1278 1285 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1279 1286
1280 1287 # The interactive one is initialized with an offset, meaning we always
1281 1288 # want to remove the topmost item in the traceback, which is our own
1282 1289 # internal code. Valid modes: ['Plain','Context','Verbose']
1283 1290 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1284 1291 color_scheme='NoColor',
1285 1292 tb_offset = 1,
1286 1293 check_cache=self.compile.check_cache)
1287 1294
1288 1295 # The instance will store a pointer to the system-wide exception hook,
1289 1296 # so that runtime code (such as magics) can access it. This is because
1290 1297 # during the read-eval loop, it may get temporarily overwritten.
1291 1298 self.sys_excepthook = sys.excepthook
1292 1299
1293 1300 # and add any custom exception handlers the user may have specified
1294 1301 self.set_custom_exc(*custom_exceptions)
1295 1302
1296 1303 # Set the exception mode
1297 1304 self.InteractiveTB.set_mode(mode=self.xmode)
1298 1305
1299 1306 def set_custom_exc(self, exc_tuple, handler):
1300 1307 """set_custom_exc(exc_tuple,handler)
1301 1308
1302 1309 Set a custom exception handler, which will be called if any of the
1303 1310 exceptions in exc_tuple occur in the mainloop (specifically, in the
1304 1311 run_code() method.
1305 1312
1306 1313 Inputs:
1307 1314
1308 1315 - exc_tuple: a *tuple* of valid exceptions to call the defined
1309 1316 handler for. It is very important that you use a tuple, and NOT A
1310 1317 LIST here, because of the way Python's except statement works. If
1311 1318 you only want to trap a single exception, use a singleton tuple:
1312 1319
1313 1320 exc_tuple == (MyCustomException,)
1314 1321
1315 1322 - handler: this must be defined as a function with the following
1316 1323 basic interface::
1317 1324
1318 1325 def my_handler(self, etype, value, tb, tb_offset=None)
1319 1326 ...
1320 1327 # The return value must be
1321 1328 return structured_traceback
1322 1329
1323 1330 This will be made into an instance method (via types.MethodType)
1324 1331 of IPython itself, and it will be called if any of the exceptions
1325 1332 listed in the exc_tuple are caught. If the handler is None, an
1326 1333 internal basic one is used, which just prints basic info.
1327 1334
1328 1335 WARNING: by putting in your own exception handler into IPython's main
1329 1336 execution loop, you run a very good chance of nasty crashes. This
1330 1337 facility should only be used if you really know what you are doing."""
1331 1338
1332 1339 assert type(exc_tuple)==type(()) , \
1333 1340 "The custom exceptions must be given AS A TUPLE."
1334 1341
1335 1342 def dummy_handler(self,etype,value,tb):
1336 1343 print '*** Simple custom exception handler ***'
1337 1344 print 'Exception type :',etype
1338 1345 print 'Exception value:',value
1339 1346 print 'Traceback :',tb
1340 1347 print 'Source code :','\n'.join(self.buffer)
1341 1348
1342 1349 if handler is None: handler = dummy_handler
1343 1350
1344 1351 self.CustomTB = types.MethodType(handler,self)
1345 1352 self.custom_exceptions = exc_tuple
1346 1353
1347 1354 def excepthook(self, etype, value, tb):
1348 1355 """One more defense for GUI apps that call sys.excepthook.
1349 1356
1350 1357 GUI frameworks like wxPython trap exceptions and call
1351 1358 sys.excepthook themselves. I guess this is a feature that
1352 1359 enables them to keep running after exceptions that would
1353 1360 otherwise kill their mainloop. This is a bother for IPython
1354 1361 which excepts to catch all of the program exceptions with a try:
1355 1362 except: statement.
1356 1363
1357 1364 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1358 1365 any app directly invokes sys.excepthook, it will look to the user like
1359 1366 IPython crashed. In order to work around this, we can disable the
1360 1367 CrashHandler and replace it with this excepthook instead, which prints a
1361 1368 regular traceback using our InteractiveTB. In this fashion, apps which
1362 1369 call sys.excepthook will generate a regular-looking exception from
1363 1370 IPython, and the CrashHandler will only be triggered by real IPython
1364 1371 crashes.
1365 1372
1366 1373 This hook should be used sparingly, only in places which are not likely
1367 1374 to be true IPython errors.
1368 1375 """
1369 1376 self.showtraceback((etype,value,tb),tb_offset=0)
1370 1377
1371 1378 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1372 1379 exception_only=False):
1373 1380 """Display the exception that just occurred.
1374 1381
1375 1382 If nothing is known about the exception, this is the method which
1376 1383 should be used throughout the code for presenting user tracebacks,
1377 1384 rather than directly invoking the InteractiveTB object.
1378 1385
1379 1386 A specific showsyntaxerror() also exists, but this method can take
1380 1387 care of calling it if needed, so unless you are explicitly catching a
1381 1388 SyntaxError exception, don't try to analyze the stack manually and
1382 1389 simply call this method."""
1383 1390
1384 1391 try:
1385 1392 if exc_tuple is None:
1386 1393 etype, value, tb = sys.exc_info()
1387 1394 else:
1388 1395 etype, value, tb = exc_tuple
1389 1396
1390 1397 if etype is None:
1391 1398 if hasattr(sys, 'last_type'):
1392 1399 etype, value, tb = sys.last_type, sys.last_value, \
1393 1400 sys.last_traceback
1394 1401 else:
1395 1402 self.write_err('No traceback available to show.\n')
1396 1403 return
1397 1404
1398 1405 if etype is SyntaxError:
1399 1406 # Though this won't be called by syntax errors in the input
1400 1407 # line, there may be SyntaxError cases whith imported code.
1401 1408 self.showsyntaxerror(filename)
1402 1409 elif etype is UsageError:
1403 1410 print "UsageError:", value
1404 1411 else:
1405 1412 # WARNING: these variables are somewhat deprecated and not
1406 1413 # necessarily safe to use in a threaded environment, but tools
1407 1414 # like pdb depend on their existence, so let's set them. If we
1408 1415 # find problems in the field, we'll need to revisit their use.
1409 1416 sys.last_type = etype
1410 1417 sys.last_value = value
1411 1418 sys.last_traceback = tb
1412 1419
1413 1420 if etype in self.custom_exceptions:
1414 1421 # FIXME: Old custom traceback objects may just return a
1415 1422 # string, in that case we just put it into a list
1416 1423 stb = self.CustomTB(etype, value, tb, tb_offset)
1417 1424 if isinstance(ctb, basestring):
1418 1425 stb = [stb]
1419 1426 else:
1420 1427 if exception_only:
1421 1428 stb = ['An exception has occurred, use %tb to see '
1422 1429 'the full traceback.\n']
1423 1430 stb.extend(self.InteractiveTB.get_exception_only(etype,
1424 1431 value))
1425 1432 else:
1426 1433 stb = self.InteractiveTB.structured_traceback(etype,
1427 1434 value, tb, tb_offset=tb_offset)
1428 1435 # FIXME: the pdb calling should be done by us, not by
1429 1436 # the code computing the traceback.
1430 1437 if self.InteractiveTB.call_pdb:
1431 1438 # pdb mucks up readline, fix it back
1432 1439 self.set_readline_completer()
1433 1440
1434 1441 # Actually show the traceback
1435 1442 self._showtraceback(etype, value, stb)
1436 1443
1437 1444 except KeyboardInterrupt:
1438 1445 self.write_err("\nKeyboardInterrupt\n")
1439 1446
1440 1447 def _showtraceback(self, etype, evalue, stb):
1441 1448 """Actually show a traceback.
1442 1449
1443 1450 Subclasses may override this method to put the traceback on a different
1444 1451 place, like a side channel.
1445 1452 """
1446 1453 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1447 1454
1448 1455 def showsyntaxerror(self, filename=None):
1449 1456 """Display the syntax error that just occurred.
1450 1457
1451 1458 This doesn't display a stack trace because there isn't one.
1452 1459
1453 1460 If a filename is given, it is stuffed in the exception instead
1454 1461 of what was there before (because Python's parser always uses
1455 1462 "<string>" when reading from a string).
1456 1463 """
1457 1464 etype, value, last_traceback = sys.exc_info()
1458 1465
1459 1466 # See note about these variables in showtraceback() above
1460 1467 sys.last_type = etype
1461 1468 sys.last_value = value
1462 1469 sys.last_traceback = last_traceback
1463 1470
1464 1471 if filename and etype is SyntaxError:
1465 1472 # Work hard to stuff the correct filename in the exception
1466 1473 try:
1467 1474 msg, (dummy_filename, lineno, offset, line) = value
1468 1475 except:
1469 1476 # Not the format we expect; leave it alone
1470 1477 pass
1471 1478 else:
1472 1479 # Stuff in the right filename
1473 1480 try:
1474 1481 # Assume SyntaxError is a class exception
1475 1482 value = SyntaxError(msg, (filename, lineno, offset, line))
1476 1483 except:
1477 1484 # If that failed, assume SyntaxError is a string
1478 1485 value = msg, (filename, lineno, offset, line)
1479 1486 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1480 1487 self._showtraceback(etype, value, stb)
1481 1488
1482 1489 #-------------------------------------------------------------------------
1483 1490 # Things related to readline
1484 1491 #-------------------------------------------------------------------------
1485 1492
1486 1493 def init_readline(self):
1487 1494 """Command history completion/saving/reloading."""
1488 1495
1489 1496 if self.readline_use:
1490 1497 import IPython.utils.rlineimpl as readline
1491 1498
1492 1499 self.rl_next_input = None
1493 1500 self.rl_do_indent = False
1494 1501
1495 1502 if not self.readline_use or not readline.have_readline:
1496 1503 self.has_readline = False
1497 1504 self.readline = None
1498 1505 # Set a number of methods that depend on readline to be no-op
1499 1506 self.set_readline_completer = no_op
1500 1507 self.set_custom_completer = no_op
1501 1508 self.set_completer_frame = no_op
1502 1509 warn('Readline services not available or not loaded.')
1503 1510 else:
1504 1511 self.has_readline = True
1505 1512 self.readline = readline
1506 1513 sys.modules['readline'] = readline
1507 1514
1508 1515 # Platform-specific configuration
1509 1516 if os.name == 'nt':
1510 1517 # FIXME - check with Frederick to see if we can harmonize
1511 1518 # naming conventions with pyreadline to avoid this
1512 1519 # platform-dependent check
1513 1520 self.readline_startup_hook = readline.set_pre_input_hook
1514 1521 else:
1515 1522 self.readline_startup_hook = readline.set_startup_hook
1516 1523
1517 1524 # Load user's initrc file (readline config)
1518 1525 # Or if libedit is used, load editrc.
1519 1526 inputrc_name = os.environ.get('INPUTRC')
1520 1527 if inputrc_name is None:
1521 1528 home_dir = get_home_dir()
1522 1529 if home_dir is not None:
1523 1530 inputrc_name = '.inputrc'
1524 1531 if readline.uses_libedit:
1525 1532 inputrc_name = '.editrc'
1526 1533 inputrc_name = os.path.join(home_dir, inputrc_name)
1527 1534 if os.path.isfile(inputrc_name):
1528 1535 try:
1529 1536 readline.read_init_file(inputrc_name)
1530 1537 except:
1531 1538 warn('Problems reading readline initialization file <%s>'
1532 1539 % inputrc_name)
1533 1540
1534 1541 # Configure readline according to user's prefs
1535 1542 # This is only done if GNU readline is being used. If libedit
1536 1543 # is being used (as on Leopard) the readline config is
1537 1544 # not run as the syntax for libedit is different.
1538 1545 if not readline.uses_libedit:
1539 1546 for rlcommand in self.readline_parse_and_bind:
1540 1547 #print "loading rl:",rlcommand # dbg
1541 1548 readline.parse_and_bind(rlcommand)
1542 1549
1543 1550 # Remove some chars from the delimiters list. If we encounter
1544 1551 # unicode chars, discard them.
1545 1552 delims = readline.get_completer_delims().encode("ascii", "ignore")
1546 1553 delims = delims.translate(None, self.readline_remove_delims)
1547 1554 delims = delims.replace(ESC_MAGIC, '')
1548 1555 readline.set_completer_delims(delims)
1549 1556 # otherwise we end up with a monster history after a while:
1550 1557 readline.set_history_length(self.history_length)
1551 1558 try:
1552 1559 #print '*** Reading readline history' # dbg
1553 1560 self.reload_history()
1554 1561 except IOError:
1555 1562 pass # It doesn't exist yet.
1556 1563
1557 1564 # Configure auto-indent for all platforms
1558 1565 self.set_autoindent(self.autoindent)
1559 1566
1560 1567 def set_next_input(self, s):
1561 1568 """ Sets the 'default' input string for the next command line.
1562 1569
1563 1570 Requires readline.
1564 1571
1565 1572 Example:
1566 1573
1567 1574 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1568 1575 [D:\ipython]|2> Hello Word_ # cursor is here
1569 1576 """
1570 1577
1571 1578 self.rl_next_input = s
1572 1579
1573 1580 # Maybe move this to the terminal subclass?
1574 1581 def pre_readline(self):
1575 1582 """readline hook to be used at the start of each line.
1576 1583
1577 1584 Currently it handles auto-indent only."""
1578 1585
1579 1586 if self.rl_do_indent:
1580 1587 self.readline.insert_text(self._indent_current_str())
1581 1588 if self.rl_next_input is not None:
1582 1589 self.readline.insert_text(self.rl_next_input)
1583 1590 self.rl_next_input = None
1584 1591
1585 1592 def _indent_current_str(self):
1586 1593 """return the current level of indentation as a string"""
1587 1594 return self.input_splitter.indent_spaces * ' '
1588 1595
1589 1596 #-------------------------------------------------------------------------
1590 1597 # Things related to text completion
1591 1598 #-------------------------------------------------------------------------
1592 1599
1593 1600 def init_completer(self):
1594 1601 """Initialize the completion machinery.
1595 1602
1596 1603 This creates completion machinery that can be used by client code,
1597 1604 either interactively in-process (typically triggered by the readline
1598 1605 library), programatically (such as in test suites) or out-of-prcess
1599 1606 (typically over the network by remote frontends).
1600 1607 """
1601 1608 from IPython.core.completer import IPCompleter
1602 1609 from IPython.core.completerlib import (module_completer,
1603 1610 magic_run_completer, cd_completer)
1604 1611
1605 1612 self.Completer = IPCompleter(self,
1606 1613 self.user_ns,
1607 1614 self.user_global_ns,
1608 1615 self.readline_omit__names,
1609 1616 self.alias_manager.alias_table,
1610 1617 self.has_readline)
1611 1618
1612 1619 # Add custom completers to the basic ones built into IPCompleter
1613 1620 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1614 1621 self.strdispatchers['complete_command'] = sdisp
1615 1622 self.Completer.custom_completers = sdisp
1616 1623
1617 1624 self.set_hook('complete_command', module_completer, str_key = 'import')
1618 1625 self.set_hook('complete_command', module_completer, str_key = 'from')
1619 1626 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1620 1627 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1621 1628
1622 1629 # Only configure readline if we truly are using readline. IPython can
1623 1630 # do tab-completion over the network, in GUIs, etc, where readline
1624 1631 # itself may be absent
1625 1632 if self.has_readline:
1626 1633 self.set_readline_completer()
1627 1634
1628 1635 def complete(self, text, line=None, cursor_pos=None):
1629 1636 """Return the completed text and a list of completions.
1630 1637
1631 1638 Parameters
1632 1639 ----------
1633 1640
1634 1641 text : string
1635 1642 A string of text to be completed on. It can be given as empty and
1636 1643 instead a line/position pair are given. In this case, the
1637 1644 completer itself will split the line like readline does.
1638 1645
1639 1646 line : string, optional
1640 1647 The complete line that text is part of.
1641 1648
1642 1649 cursor_pos : int, optional
1643 1650 The position of the cursor on the input line.
1644 1651
1645 1652 Returns
1646 1653 -------
1647 1654 text : string
1648 1655 The actual text that was completed.
1649 1656
1650 1657 matches : list
1651 1658 A sorted list with all possible completions.
1652 1659
1653 1660 The optional arguments allow the completion to take more context into
1654 1661 account, and are part of the low-level completion API.
1655 1662
1656 1663 This is a wrapper around the completion mechanism, similar to what
1657 1664 readline does at the command line when the TAB key is hit. By
1658 1665 exposing it as a method, it can be used by other non-readline
1659 1666 environments (such as GUIs) for text completion.
1660 1667
1661 1668 Simple usage example:
1662 1669
1663 1670 In [1]: x = 'hello'
1664 1671
1665 1672 In [2]: _ip.complete('x.l')
1666 1673 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1667 1674 """
1668 1675
1669 1676 # Inject names into __builtin__ so we can complete on the added names.
1670 1677 with self.builtin_trap:
1671 1678 return self.Completer.complete(text, line, cursor_pos)
1672 1679
1673 1680 def set_custom_completer(self, completer, pos=0):
1674 1681 """Adds a new custom completer function.
1675 1682
1676 1683 The position argument (defaults to 0) is the index in the completers
1677 1684 list where you want the completer to be inserted."""
1678 1685
1679 1686 newcomp = types.MethodType(completer,self.Completer)
1680 1687 self.Completer.matchers.insert(pos,newcomp)
1681 1688
1682 1689 def set_readline_completer(self):
1683 1690 """Reset readline's completer to be our own."""
1684 1691 self.readline.set_completer(self.Completer.rlcomplete)
1685 1692
1686 1693 def set_completer_frame(self, frame=None):
1687 1694 """Set the frame of the completer."""
1688 1695 if frame:
1689 1696 self.Completer.namespace = frame.f_locals
1690 1697 self.Completer.global_namespace = frame.f_globals
1691 1698 else:
1692 1699 self.Completer.namespace = self.user_ns
1693 1700 self.Completer.global_namespace = self.user_global_ns
1694 1701
1695 1702 #-------------------------------------------------------------------------
1696 1703 # Things related to magics
1697 1704 #-------------------------------------------------------------------------
1698 1705
1699 1706 def init_magics(self):
1700 1707 # FIXME: Move the color initialization to the DisplayHook, which
1701 1708 # should be split into a prompt manager and displayhook. We probably
1702 1709 # even need a centralize colors management object.
1703 1710 self.magic_colors(self.colors)
1704 1711 # History was moved to a separate module
1705 1712 from . import history
1706 1713 history.init_ipython(self)
1707 1714
1708 1715 def magic(self,arg_s):
1709 1716 """Call a magic function by name.
1710 1717
1711 1718 Input: a string containing the name of the magic function to call and
1712 1719 any additional arguments to be passed to the magic.
1713 1720
1714 1721 magic('name -opt foo bar') is equivalent to typing at the ipython
1715 1722 prompt:
1716 1723
1717 1724 In[1]: %name -opt foo bar
1718 1725
1719 1726 To call a magic without arguments, simply use magic('name').
1720 1727
1721 1728 This provides a proper Python function to call IPython's magics in any
1722 1729 valid Python code you can type at the interpreter, including loops and
1723 1730 compound statements.
1724 1731 """
1725 1732 args = arg_s.split(' ',1)
1726 1733 magic_name = args[0]
1727 1734 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1728 1735
1729 1736 try:
1730 1737 magic_args = args[1]
1731 1738 except IndexError:
1732 1739 magic_args = ''
1733 1740 fn = getattr(self,'magic_'+magic_name,None)
1734 1741 if fn is None:
1735 1742 error("Magic function `%s` not found." % magic_name)
1736 1743 else:
1737 1744 magic_args = self.var_expand(magic_args,1)
1738 1745 with nested(self.builtin_trap,):
1739 1746 result = fn(magic_args)
1740 1747 return result
1741 1748
1742 1749 def define_magic(self, magicname, func):
1743 1750 """Expose own function as magic function for ipython
1744 1751
1745 1752 def foo_impl(self,parameter_s=''):
1746 1753 'My very own magic!. (Use docstrings, IPython reads them).'
1747 1754 print 'Magic function. Passed parameter is between < >:'
1748 1755 print '<%s>' % parameter_s
1749 1756 print 'The self object is:',self
1750 1757
1751 1758 self.define_magic('foo',foo_impl)
1752 1759 """
1753 1760
1754 1761 import new
1755 1762 im = types.MethodType(func,self)
1756 1763 old = getattr(self, "magic_" + magicname, None)
1757 1764 setattr(self, "magic_" + magicname, im)
1758 1765 return old
1759 1766
1760 1767 #-------------------------------------------------------------------------
1761 1768 # Things related to macros
1762 1769 #-------------------------------------------------------------------------
1763 1770
1764 1771 def define_macro(self, name, themacro):
1765 1772 """Define a new macro
1766 1773
1767 1774 Parameters
1768 1775 ----------
1769 1776 name : str
1770 1777 The name of the macro.
1771 1778 themacro : str or Macro
1772 1779 The action to do upon invoking the macro. If a string, a new
1773 1780 Macro object is created by passing the string to it.
1774 1781 """
1775 1782
1776 1783 from IPython.core import macro
1777 1784
1778 1785 if isinstance(themacro, basestring):
1779 1786 themacro = macro.Macro(themacro)
1780 1787 if not isinstance(themacro, macro.Macro):
1781 1788 raise ValueError('A macro must be a string or a Macro instance.')
1782 1789 self.user_ns[name] = themacro
1783 1790
1784 1791 #-------------------------------------------------------------------------
1785 1792 # Things related to the running of system commands
1786 1793 #-------------------------------------------------------------------------
1787 1794
1788 1795 def system(self, cmd):
1789 1796 """Call the given cmd in a subprocess.
1790 1797
1791 1798 Parameters
1792 1799 ----------
1793 1800 cmd : str
1794 1801 Command to execute (can not end in '&', as bacground processes are
1795 1802 not supported.
1796 1803 """
1797 1804 # We do not support backgrounding processes because we either use
1798 1805 # pexpect or pipes to read from. Users can always just call
1799 1806 # os.system() if they really want a background process.
1800 1807 if cmd.endswith('&'):
1801 1808 raise OSError("Background processes not supported.")
1802 1809
1803 1810 return system(self.var_expand(cmd, depth=2))
1804 1811
1805 1812 def getoutput(self, cmd, split=True):
1806 1813 """Get output (possibly including stderr) from a subprocess.
1807 1814
1808 1815 Parameters
1809 1816 ----------
1810 1817 cmd : str
1811 1818 Command to execute (can not end in '&', as background processes are
1812 1819 not supported.
1813 1820 split : bool, optional
1814 1821
1815 1822 If True, split the output into an IPython SList. Otherwise, an
1816 1823 IPython LSString is returned. These are objects similar to normal
1817 1824 lists and strings, with a few convenience attributes for easier
1818 1825 manipulation of line-based output. You can use '?' on them for
1819 1826 details.
1820 1827 """
1821 1828 if cmd.endswith('&'):
1822 1829 raise OSError("Background processes not supported.")
1823 1830 out = getoutput(self.var_expand(cmd, depth=2))
1824 1831 if split:
1825 1832 out = SList(out.splitlines())
1826 1833 else:
1827 1834 out = LSString(out)
1828 1835 return out
1829 1836
1830 1837 #-------------------------------------------------------------------------
1831 1838 # Things related to aliases
1832 1839 #-------------------------------------------------------------------------
1833 1840
1834 1841 def init_alias(self):
1835 1842 self.alias_manager = AliasManager(shell=self, config=self.config)
1836 1843 self.ns_table['alias'] = self.alias_manager.alias_table,
1837 1844
1838 1845 #-------------------------------------------------------------------------
1839 1846 # Things related to extensions and plugins
1840 1847 #-------------------------------------------------------------------------
1841 1848
1842 1849 def init_extension_manager(self):
1843 1850 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1844 1851
1845 1852 def init_plugin_manager(self):
1846 1853 self.plugin_manager = PluginManager(config=self.config)
1847 1854
1848 1855 #-------------------------------------------------------------------------
1849 1856 # Things related to payloads
1850 1857 #-------------------------------------------------------------------------
1851 1858
1852 1859 def init_payload(self):
1853 1860 self.payload_manager = PayloadManager(config=self.config)
1854 1861
1855 1862 #-------------------------------------------------------------------------
1856 1863 # Things related to the prefilter
1857 1864 #-------------------------------------------------------------------------
1858 1865
1859 1866 def init_prefilter(self):
1860 1867 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1861 1868 # Ultimately this will be refactored in the new interpreter code, but
1862 1869 # for now, we should expose the main prefilter method (there's legacy
1863 1870 # code out there that may rely on this).
1864 1871 self.prefilter = self.prefilter_manager.prefilter_lines
1865 1872
1866 1873 def auto_rewrite_input(self, cmd):
1867 1874 """Print to the screen the rewritten form of the user's command.
1868 1875
1869 1876 This shows visual feedback by rewriting input lines that cause
1870 1877 automatic calling to kick in, like::
1871 1878
1872 1879 /f x
1873 1880
1874 1881 into::
1875 1882
1876 1883 ------> f(x)
1877 1884
1878 1885 after the user's input prompt. This helps the user understand that the
1879 1886 input line was transformed automatically by IPython.
1880 1887 """
1881 1888 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1882 1889
1883 1890 try:
1884 1891 # plain ascii works better w/ pyreadline, on some machines, so
1885 1892 # we use it and only print uncolored rewrite if we have unicode
1886 1893 rw = str(rw)
1887 1894 print >> IPython.utils.io.Term.cout, rw
1888 1895 except UnicodeEncodeError:
1889 1896 print "------> " + cmd
1890 1897
1891 1898 #-------------------------------------------------------------------------
1892 1899 # Things related to extracting values/expressions from kernel and user_ns
1893 1900 #-------------------------------------------------------------------------
1894 1901
1895 1902 def _simple_error(self):
1896 1903 etype, value = sys.exc_info()[:2]
1897 1904 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1898 1905
1899 1906 def user_variables(self, names):
1900 1907 """Get a list of variable names from the user's namespace.
1901 1908
1902 1909 Parameters
1903 1910 ----------
1904 1911 names : list of strings
1905 1912 A list of names of variables to be read from the user namespace.
1906 1913
1907 1914 Returns
1908 1915 -------
1909 1916 A dict, keyed by the input names and with the repr() of each value.
1910 1917 """
1911 1918 out = {}
1912 1919 user_ns = self.user_ns
1913 1920 for varname in names:
1914 1921 try:
1915 1922 value = repr(user_ns[varname])
1916 1923 except:
1917 1924 value = self._simple_error()
1918 1925 out[varname] = value
1919 1926 return out
1920 1927
1921 1928 def user_expressions(self, expressions):
1922 1929 """Evaluate a dict of expressions in the user's namespace.
1923 1930
1924 1931 Parameters
1925 1932 ----------
1926 1933 expressions : dict
1927 1934 A dict with string keys and string values. The expression values
1928 1935 should be valid Python expressions, each of which will be evaluated
1929 1936 in the user namespace.
1930 1937
1931 1938 Returns
1932 1939 -------
1933 1940 A dict, keyed like the input expressions dict, with the repr() of each
1934 1941 value.
1935 1942 """
1936 1943 out = {}
1937 1944 user_ns = self.user_ns
1938 1945 global_ns = self.user_global_ns
1939 1946 for key, expr in expressions.iteritems():
1940 1947 try:
1941 1948 value = repr(eval(expr, global_ns, user_ns))
1942 1949 except:
1943 1950 value = self._simple_error()
1944 1951 out[key] = value
1945 1952 return out
1946 1953
1947 1954 #-------------------------------------------------------------------------
1948 1955 # Things related to the running of code
1949 1956 #-------------------------------------------------------------------------
1950 1957
1951 1958 def ex(self, cmd):
1952 1959 """Execute a normal python statement in user namespace."""
1953 1960 with nested(self.builtin_trap,):
1954 1961 exec cmd in self.user_global_ns, self.user_ns
1955 1962
1956 1963 def ev(self, expr):
1957 1964 """Evaluate python expression expr in user namespace.
1958 1965
1959 1966 Returns the result of evaluation
1960 1967 """
1961 1968 with nested(self.builtin_trap,):
1962 1969 return eval(expr, self.user_global_ns, self.user_ns)
1963 1970
1964 1971 def safe_execfile(self, fname, *where, **kw):
1965 1972 """A safe version of the builtin execfile().
1966 1973
1967 1974 This version will never throw an exception, but instead print
1968 1975 helpful error messages to the screen. This only works on pure
1969 1976 Python files with the .py extension.
1970 1977
1971 1978 Parameters
1972 1979 ----------
1973 1980 fname : string
1974 1981 The name of the file to be executed.
1975 1982 where : tuple
1976 1983 One or two namespaces, passed to execfile() as (globals,locals).
1977 1984 If only one is given, it is passed as both.
1978 1985 exit_ignore : bool (False)
1979 1986 If True, then silence SystemExit for non-zero status (it is always
1980 1987 silenced for zero status, as it is so common).
1981 1988 """
1982 1989 kw.setdefault('exit_ignore', False)
1983 1990
1984 1991 fname = os.path.abspath(os.path.expanduser(fname))
1985 1992
1986 1993 # Make sure we have a .py file
1987 1994 if not fname.endswith('.py'):
1988 1995 warn('File must end with .py to be run using execfile: <%s>' % fname)
1989 1996
1990 1997 # Make sure we can open the file
1991 1998 try:
1992 1999 with open(fname) as thefile:
1993 2000 pass
1994 2001 except:
1995 2002 warn('Could not open file <%s> for safe execution.' % fname)
1996 2003 return
1997 2004
1998 2005 # Find things also in current directory. This is needed to mimic the
1999 2006 # behavior of running a script from the system command line, where
2000 2007 # Python inserts the script's directory into sys.path
2001 2008 dname = os.path.dirname(fname)
2002 2009
2003 2010 with prepended_to_syspath(dname):
2004 2011 try:
2005 2012 execfile(fname,*where)
2006 2013 except SystemExit, status:
2007 2014 # If the call was made with 0 or None exit status (sys.exit(0)
2008 2015 # or sys.exit() ), don't bother showing a traceback, as both of
2009 2016 # these are considered normal by the OS:
2010 2017 # > python -c'import sys;sys.exit(0)'; echo $?
2011 2018 # 0
2012 2019 # > python -c'import sys;sys.exit()'; echo $?
2013 2020 # 0
2014 2021 # For other exit status, we show the exception unless
2015 2022 # explicitly silenced, but only in short form.
2016 2023 if status.code not in (0, None) and not kw['exit_ignore']:
2017 2024 self.showtraceback(exception_only=True)
2018 2025 except:
2019 2026 self.showtraceback()
2020 2027
2021 2028 def safe_execfile_ipy(self, fname):
2022 2029 """Like safe_execfile, but for .ipy files with IPython syntax.
2023 2030
2024 2031 Parameters
2025 2032 ----------
2026 2033 fname : str
2027 2034 The name of the file to execute. The filename must have a
2028 2035 .ipy extension.
2029 2036 """
2030 2037 fname = os.path.abspath(os.path.expanduser(fname))
2031 2038
2032 2039 # Make sure we have a .py file
2033 2040 if not fname.endswith('.ipy'):
2034 2041 warn('File must end with .py to be run using execfile: <%s>' % fname)
2035 2042
2036 2043 # Make sure we can open the file
2037 2044 try:
2038 2045 with open(fname) as thefile:
2039 2046 pass
2040 2047 except:
2041 2048 warn('Could not open file <%s> for safe execution.' % fname)
2042 2049 return
2043 2050
2044 2051 # Find things also in current directory. This is needed to mimic the
2045 2052 # behavior of running a script from the system command line, where
2046 2053 # Python inserts the script's directory into sys.path
2047 2054 dname = os.path.dirname(fname)
2048 2055
2049 2056 with prepended_to_syspath(dname):
2050 2057 try:
2051 2058 with open(fname) as thefile:
2052 2059 # self.run_cell currently captures all exceptions
2053 2060 # raised in user code. It would be nice if there were
2054 2061 # versions of runlines, execfile that did raise, so
2055 2062 # we could catch the errors.
2056 2063 self.run_cell(thefile.read())
2057 2064 except:
2058 2065 self.showtraceback()
2059 2066 warn('Unknown failure executing file: <%s>' % fname)
2060 2067
2061 2068 def run_cell(self, cell):
2062 2069 """Run the contents of an entire multiline 'cell' of code.
2063 2070
2064 2071 The cell is split into separate blocks which can be executed
2065 2072 individually. Then, based on how many blocks there are, they are
2066 2073 executed as follows:
2067 2074
2068 2075 - A single block: 'single' mode.
2069 2076
2070 2077 If there's more than one block, it depends:
2071 2078
2072 2079 - if the last one is no more than two lines long, run all but the last
2073 2080 in 'exec' mode and the very last one in 'single' mode. This makes it
2074 2081 easy to type simple expressions at the end to see computed values. -
2075 2082 otherwise (last one is also multiline), run all in 'exec' mode
2076 2083
2077 2084 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2078 2085 results are displayed and output prompts are computed. In 'exec' mode,
2079 2086 no results are displayed unless :func:`print` is called explicitly;
2080 2087 this mode is more akin to running a script.
2081 2088
2082 2089 Parameters
2083 2090 ----------
2084 2091 cell : str
2085 2092 A single or multiline string.
2086 2093 """
2087 2094
2088 2095 # We need to break up the input into executable blocks that can be run
2089 2096 # in 'single' mode, to provide comfortable user behavior.
2090 2097 blocks = self.input_splitter.split_blocks(cell)
2091 2098
2092 2099 if not blocks:
2093 2100 return
2094 2101
2095 2102 # Store the 'ipython' version of the cell as well, since that's what
2096 2103 # needs to go into the translated history and get executed (the
2097 2104 # original cell may contain non-python syntax).
2098 2105 ipy_cell = ''.join(blocks)
2099 2106
2100 2107 # Store raw and processed history
2101 2108 self.history_manager.store_inputs(ipy_cell, cell)
2102 2109
2103 2110 self.logger.log(ipy_cell, cell)
2104 2111 # dbg code!!!
2105 2112 if 0:
2106 2113 def myapp(self, val): # dbg
2107 2114 import traceback as tb
2108 2115 stack = ''.join(tb.format_stack())
2109 2116 print 'Value:', val
2110 2117 print 'Stack:\n', stack
2111 2118 list.append(self, val)
2112 2119
2113 2120 import new
2114 2121 self.history_manager.input_hist_parsed.append = types.MethodType(myapp,
2115 2122 self.history_manager.input_hist_parsed)
2116 2123 # End dbg
2117 2124
2118 2125 # All user code execution must happen with our context managers active
2119 2126 with nested(self.builtin_trap, self.display_trap):
2120 2127
2121 2128 # Single-block input should behave like an interactive prompt
2122 2129 if len(blocks) == 1:
2123 2130 # since we return here, we need to update the execution count
2124 2131 out = self.run_one_block(blocks[0])
2125 2132 self.execution_count += 1
2126 2133 return out
2127 2134
2128 2135 # In multi-block input, if the last block is a simple (one-two
2129 2136 # lines) expression, run it in single mode so it produces output.
2130 2137 # Otherwise just feed the whole thing to run_code. This seems like
2131 2138 # a reasonable usability design.
2132 2139 last = blocks[-1]
2133 2140 last_nlines = len(last.splitlines())
2134 2141
2135 2142 # Note: below, whenever we call run_code, we must sync history
2136 2143 # ourselves, because run_code is NOT meant to manage history at all.
2137 2144 if last_nlines < 2:
2138 2145 # Here we consider the cell split between 'body' and 'last',
2139 2146 # store all history and execute 'body', and if successful, then
2140 2147 # proceed to execute 'last'.
2141 2148
2142 2149 # Get the main body to run as a cell
2143 2150 ipy_body = ''.join(blocks[:-1])
2144 2151 retcode = self.run_source(ipy_body, symbol='exec',
2145 2152 post_execute=False)
2146 2153 if retcode==0:
2147 2154 # And the last expression via runlines so it produces output
2148 2155 self.run_one_block(last)
2149 2156 else:
2150 2157 # Run the whole cell as one entity, storing both raw and
2151 2158 # processed input in history
2152 2159 self.run_source(ipy_cell, symbol='exec')
2153 2160
2154 2161 # Each cell is a *single* input, regardless of how many lines it has
2155 2162 self.execution_count += 1
2156 2163
2157 2164 def run_one_block(self, block):
2158 2165 """Run a single interactive block.
2159 2166
2160 2167 If the block is single-line, dynamic transformations are applied to it
2161 2168 (like automagics, autocall and alias recognition).
2162 2169 """
2163 2170 if len(block.splitlines()) <= 1:
2164 2171 out = self.run_single_line(block)
2165 2172 else:
2166 2173 out = self.run_code(block)
2167 2174 return out
2168 2175
2169 2176 def run_single_line(self, line):
2170 2177 """Run a single-line interactive statement.
2171 2178
2172 2179 This assumes the input has been transformed to IPython syntax by
2173 2180 applying all static transformations (those with an explicit prefix like
2174 2181 % or !), but it will further try to apply the dynamic ones.
2175 2182
2176 2183 It does not update history.
2177 2184 """
2178 2185 tline = self.prefilter_manager.prefilter_line(line)
2179 2186 return self.run_source(tline)
2180 2187
2181 2188 # PENDING REMOVAL: this method is slated for deletion, once our new
2182 2189 # input logic has been 100% moved to frontends and is stable.
2183 2190 def runlines(self, lines, clean=False):
2184 2191 """Run a string of one or more lines of source.
2185 2192
2186 2193 This method is capable of running a string containing multiple source
2187 2194 lines, as if they had been entered at the IPython prompt. Since it
2188 2195 exposes IPython's processing machinery, the given strings can contain
2189 2196 magic calls (%magic), special shell access (!cmd), etc.
2190 2197 """
2191 2198
2192 2199 if isinstance(lines, (list, tuple)):
2193 2200 lines = '\n'.join(lines)
2194 2201
2195 2202 if clean:
2196 2203 lines = self._cleanup_ipy_script(lines)
2197 2204
2198 2205 # We must start with a clean buffer, in case this is run from an
2199 2206 # interactive IPython session (via a magic, for example).
2200 2207 self.reset_buffer()
2201 2208 lines = lines.splitlines()
2202 2209
2203 2210 # Since we will prefilter all lines, store the user's raw input too
2204 2211 # before we apply any transformations
2205 2212 self.buffer_raw[:] = [ l+'\n' for l in lines]
2206 2213
2207 2214 more = False
2208 2215 prefilter_lines = self.prefilter_manager.prefilter_lines
2209 2216 with nested(self.builtin_trap, self.display_trap):
2210 2217 for line in lines:
2211 2218 # skip blank lines so we don't mess up the prompt counter, but
2212 2219 # do NOT skip even a blank line if we are in a code block (more
2213 2220 # is true)
2214 2221
2215 2222 if line or more:
2216 2223 more = self.push_line(prefilter_lines(line, more))
2217 2224 # IPython's run_source returns None if there was an error
2218 2225 # compiling the code. This allows us to stop processing
2219 2226 # right away, so the user gets the error message at the
2220 2227 # right place.
2221 2228 if more is None:
2222 2229 break
2223 2230 # final newline in case the input didn't have it, so that the code
2224 2231 # actually does get executed
2225 2232 if more:
2226 2233 self.push_line('\n')
2227 2234
2228 2235 def run_source(self, source, filename=None,
2229 2236 symbol='single', post_execute=True):
2230 2237 """Compile and run some source in the interpreter.
2231 2238
2232 2239 Arguments are as for compile_command().
2233 2240
2234 2241 One several things can happen:
2235 2242
2236 2243 1) The input is incorrect; compile_command() raised an
2237 2244 exception (SyntaxError or OverflowError). A syntax traceback
2238 2245 will be printed by calling the showsyntaxerror() method.
2239 2246
2240 2247 2) The input is incomplete, and more input is required;
2241 2248 compile_command() returned None. Nothing happens.
2242 2249
2243 2250 3) The input is complete; compile_command() returned a code
2244 2251 object. The code is executed by calling self.run_code() (which
2245 2252 also handles run-time exceptions, except for SystemExit).
2246 2253
2247 2254 The return value is:
2248 2255
2249 2256 - True in case 2
2250 2257
2251 2258 - False in the other cases, unless an exception is raised, where
2252 2259 None is returned instead. This can be used by external callers to
2253 2260 know whether to continue feeding input or not.
2254 2261
2255 2262 The return value can be used to decide whether to use sys.ps1 or
2256 2263 sys.ps2 to prompt the next line."""
2257 2264
2258 2265 # We need to ensure that the source is unicode from here on.
2259 2266 if type(source)==str:
2260 2267 usource = source.decode(self.stdin_encoding)
2261 2268 else:
2262 2269 usource = source
2263 2270
2264 2271 if 0: # dbg
2265 2272 print 'Source:', repr(source) # dbg
2266 2273 print 'USource:', repr(usource) # dbg
2267 2274 print 'type:', type(source) # dbg
2268 2275 print 'encoding', self.stdin_encoding # dbg
2269 2276
2270 2277 try:
2271 2278 code = self.compile(usource, symbol, self.execution_count)
2272 2279 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2273 2280 # Case 1
2274 2281 self.showsyntaxerror(filename)
2275 2282 return None
2276 2283
2277 2284 if code is None:
2278 2285 # Case 2
2279 2286 return True
2280 2287
2281 2288 # Case 3
2282 2289 # We store the code object so that threaded shells and
2283 2290 # custom exception handlers can access all this info if needed.
2284 2291 # The source corresponding to this can be obtained from the
2285 2292 # buffer attribute as '\n'.join(self.buffer).
2286 2293 self.code_to_run = code
2287 2294 # now actually execute the code object
2288 2295 if self.run_code(code, post_execute) == 0:
2289 2296 return False
2290 2297 else:
2291 2298 return None
2292 2299
2293 2300 # For backwards compatibility
2294 2301 runsource = run_source
2295 2302
2296 2303 def run_code(self, code_obj, post_execute=True):
2297 2304 """Execute a code object.
2298 2305
2299 2306 When an exception occurs, self.showtraceback() is called to display a
2300 2307 traceback.
2301 2308
2302 2309 Return value: a flag indicating whether the code to be run completed
2303 2310 successfully:
2304 2311
2305 2312 - 0: successful execution.
2306 2313 - 1: an error occurred.
2307 2314 """
2308 2315
2309 2316 # Set our own excepthook in case the user code tries to call it
2310 2317 # directly, so that the IPython crash handler doesn't get triggered
2311 2318 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2312 2319
2313 2320 # we save the original sys.excepthook in the instance, in case config
2314 2321 # code (such as magics) needs access to it.
2315 2322 self.sys_excepthook = old_excepthook
2316 2323 outflag = 1 # happens in more places, so it's easier as default
2317 2324 try:
2318 2325 try:
2319 2326 self.hooks.pre_run_code_hook()
2320 2327 #rprint('Running code') # dbg
2321 2328 exec code_obj in self.user_global_ns, self.user_ns
2322 2329 finally:
2323 2330 # Reset our crash handler in place
2324 2331 sys.excepthook = old_excepthook
2325 2332 except SystemExit:
2326 2333 self.reset_buffer()
2327 2334 self.showtraceback(exception_only=True)
2328 2335 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2329 2336 except self.custom_exceptions:
2330 2337 etype,value,tb = sys.exc_info()
2331 2338 self.CustomTB(etype,value,tb)
2332 2339 except:
2333 2340 self.showtraceback()
2334 2341 else:
2335 2342 outflag = 0
2336 2343 if softspace(sys.stdout, 0):
2337 2344 print
2338 2345
2339 2346 # Execute any registered post-execution functions. Here, any errors
2340 2347 # are reported only minimally and just on the terminal, because the
2341 2348 # main exception channel may be occupied with a user traceback.
2342 2349 # FIXME: we need to think this mechanism a little more carefully.
2343 2350 if post_execute:
2344 2351 for func in self._post_execute:
2345 2352 try:
2346 2353 func()
2347 2354 except:
2348 2355 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2349 2356 func
2350 2357 print >> io.Term.cout, head
2351 2358 print >> io.Term.cout, self._simple_error()
2352 2359 print >> io.Term.cout, 'Removing from post_execute'
2353 2360 self._post_execute.remove(func)
2354 2361
2355 2362 # Flush out code object which has been run (and source)
2356 2363 self.code_to_run = None
2357 2364 return outflag
2358 2365
2359 2366 # For backwards compatibility
2360 2367 runcode = run_code
2361 2368
2362 2369 # PENDING REMOVAL: this method is slated for deletion, once our new
2363 2370 # input logic has been 100% moved to frontends and is stable.
2364 2371 def push_line(self, line):
2365 2372 """Push a line to the interpreter.
2366 2373
2367 2374 The line should not have a trailing newline; it may have
2368 2375 internal newlines. The line is appended to a buffer and the
2369 2376 interpreter's run_source() method is called with the
2370 2377 concatenated contents of the buffer as source. If this
2371 2378 indicates that the command was executed or invalid, the buffer
2372 2379 is reset; otherwise, the command is incomplete, and the buffer
2373 2380 is left as it was after the line was appended. The return
2374 2381 value is 1 if more input is required, 0 if the line was dealt
2375 2382 with in some way (this is the same as run_source()).
2376 2383 """
2377 2384
2378 2385 # autoindent management should be done here, and not in the
2379 2386 # interactive loop, since that one is only seen by keyboard input. We
2380 2387 # need this done correctly even for code run via runlines (which uses
2381 2388 # push).
2382 2389
2383 2390 #print 'push line: <%s>' % line # dbg
2384 2391 self.buffer.append(line)
2385 2392 full_source = '\n'.join(self.buffer)
2386 2393 more = self.run_source(full_source, self.filename)
2387 2394 if not more:
2388 2395 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2389 2396 full_source)
2390 2397 self.reset_buffer()
2391 2398 self.execution_count += 1
2392 2399 return more
2393 2400
2394 2401 def reset_buffer(self):
2395 2402 """Reset the input buffer."""
2396 2403 self.buffer[:] = []
2397 2404 self.buffer_raw[:] = []
2398 2405 self.input_splitter.reset()
2399 2406
2400 2407 # For backwards compatibility
2401 2408 resetbuffer = reset_buffer
2402 2409
2403 2410 def _is_secondary_block_start(self, s):
2404 2411 if not s.endswith(':'):
2405 2412 return False
2406 2413 if (s.startswith('elif') or
2407 2414 s.startswith('else') or
2408 2415 s.startswith('except') or
2409 2416 s.startswith('finally')):
2410 2417 return True
2411 2418
2412 2419 def _cleanup_ipy_script(self, script):
2413 2420 """Make a script safe for self.runlines()
2414 2421
2415 2422 Currently, IPython is lines based, with blocks being detected by
2416 2423 empty lines. This is a problem for block based scripts that may
2417 2424 not have empty lines after blocks. This script adds those empty
2418 2425 lines to make scripts safe for running in the current line based
2419 2426 IPython.
2420 2427 """
2421 2428 res = []
2422 2429 lines = script.splitlines()
2423 2430 level = 0
2424 2431
2425 2432 for l in lines:
2426 2433 lstripped = l.lstrip()
2427 2434 stripped = l.strip()
2428 2435 if not stripped:
2429 2436 continue
2430 2437 newlevel = len(l) - len(lstripped)
2431 2438 if level > 0 and newlevel == 0 and \
2432 2439 not self._is_secondary_block_start(stripped):
2433 2440 # add empty line
2434 2441 res.append('')
2435 2442 res.append(l)
2436 2443 level = newlevel
2437 2444
2438 2445 return '\n'.join(res) + '\n'
2439 2446
2440 2447 #-------------------------------------------------------------------------
2441 2448 # Things related to GUI support and pylab
2442 2449 #-------------------------------------------------------------------------
2443 2450
2444 2451 def enable_pylab(self, gui=None):
2445 2452 raise NotImplementedError('Implement enable_pylab in a subclass')
2446 2453
2447 2454 #-------------------------------------------------------------------------
2448 2455 # Utilities
2449 2456 #-------------------------------------------------------------------------
2450 2457
2451 2458 def var_expand(self,cmd,depth=0):
2452 2459 """Expand python variables in a string.
2453 2460
2454 2461 The depth argument indicates how many frames above the caller should
2455 2462 be walked to look for the local namespace where to expand variables.
2456 2463
2457 2464 The global namespace for expansion is always the user's interactive
2458 2465 namespace.
2459 2466 """
2460 2467
2461 2468 return str(ItplNS(cmd,
2462 2469 self.user_ns, # globals
2463 2470 # Skip our own frame in searching for locals:
2464 2471 sys._getframe(depth+1).f_locals # locals
2465 2472 ))
2466 2473
2467 2474 def mktempfile(self, data=None, prefix='ipython_edit_'):
2468 2475 """Make a new tempfile and return its filename.
2469 2476
2470 2477 This makes a call to tempfile.mktemp, but it registers the created
2471 2478 filename internally so ipython cleans it up at exit time.
2472 2479
2473 2480 Optional inputs:
2474 2481
2475 2482 - data(None): if data is given, it gets written out to the temp file
2476 2483 immediately, and the file is closed again."""
2477 2484
2478 2485 filename = tempfile.mktemp('.py', prefix)
2479 2486 self.tempfiles.append(filename)
2480 2487
2481 2488 if data:
2482 2489 tmp_file = open(filename,'w')
2483 2490 tmp_file.write(data)
2484 2491 tmp_file.close()
2485 2492 return filename
2486 2493
2487 2494 # TODO: This should be removed when Term is refactored.
2488 2495 def write(self,data):
2489 2496 """Write a string to the default output"""
2490 2497 io.Term.cout.write(data)
2491 2498
2492 2499 # TODO: This should be removed when Term is refactored.
2493 2500 def write_err(self,data):
2494 2501 """Write a string to the default error output"""
2495 2502 io.Term.cerr.write(data)
2496 2503
2497 2504 def ask_yes_no(self,prompt,default=True):
2498 2505 if self.quiet:
2499 2506 return True
2500 2507 return ask_yes_no(prompt,default)
2501 2508
2502 2509 def show_usage(self):
2503 2510 """Show a usage message"""
2504 2511 page.page(IPython.core.usage.interactive_usage)
2505 2512
2506 2513 #-------------------------------------------------------------------------
2507 2514 # Things related to IPython exiting
2508 2515 #-------------------------------------------------------------------------
2509 2516 def atexit_operations(self):
2510 2517 """This will be executed at the time of exit.
2511 2518
2512 2519 Cleanup operations and saving of persistent data that is done
2513 2520 unconditionally by IPython should be performed here.
2514 2521
2515 2522 For things that may depend on startup flags or platform specifics (such
2516 2523 as having readline or not), register a separate atexit function in the
2517 2524 code that has the appropriate information, rather than trying to
2518 2525 clutter
2519 2526 """
2520 2527 # Cleanup all tempfiles left around
2521 2528 for tfile in self.tempfiles:
2522 2529 try:
2523 2530 os.unlink(tfile)
2524 2531 except OSError:
2525 2532 pass
2526 2533
2527 2534 self.save_history()
2528 2535
2529 2536 # Clear all user namespaces to release all references cleanly.
2530 2537 self.reset()
2531 2538
2532 2539 # Run user hooks
2533 2540 self.hooks.shutdown_hook()
2534 2541
2535 2542 def cleanup(self):
2536 2543 self.restore_sys_module_state()
2537 2544
2538 2545
2539 2546 class InteractiveShellABC(object):
2540 2547 """An abstract base class for InteractiveShell."""
2541 2548 __metaclass__ = abc.ABCMeta
2542 2549
2543 2550 InteractiveShellABC.register(InteractiveShell)
@@ -1,467 +1,482 b''
1 1 """ A FrontendWidget that emulates the interface of the console IPython and
2 2 supports the additional functionality provided by the IPython kernel.
3 3
4 4 TODO: Add support for retrieving the system default editor. Requires code
5 5 paths for Windows (use the registry), Mac OS (use LaunchServices), and
6 6 Linux (use the xdg system).
7 7 """
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Imports
11 11 #-----------------------------------------------------------------------------
12 12
13 13 # Standard library imports
14 14 from collections import namedtuple
15 15 import re
16 16 from subprocess import Popen
17 17 from textwrap import dedent
18 18
19 19 # System library imports
20 20 from PyQt4 import QtCore, QtGui
21 21
22 22 # Local imports
23 23 from IPython.core.inputsplitter import IPythonInputSplitter, \
24 24 transform_ipy_prompt
25 25 from IPython.core.usage import default_gui_banner
26 26 from IPython.utils.traitlets import Bool, Str
27 27 from frontend_widget import FrontendWidget
28 28 from styles import (default_light_style_sheet, default_light_syntax_style,
29 29 default_dark_style_sheet, default_dark_syntax_style,
30 30 default_bw_style_sheet, default_bw_syntax_style)
31 31
32 32 #-----------------------------------------------------------------------------
33 33 # Constants
34 34 #-----------------------------------------------------------------------------
35 35
36 36 # Default strings to build and display input and output prompts (and separators
37 37 # in between)
38 38 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
39 39 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
40 40 default_input_sep = '\n'
41 41 default_output_sep = ''
42 42 default_output_sep2 = ''
43 43
44 44 # Base path for most payload sources.
45 45 zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell'
46 46
47 47 #-----------------------------------------------------------------------------
48 48 # IPythonWidget class
49 49 #-----------------------------------------------------------------------------
50 50
51 51 class IPythonWidget(FrontendWidget):
52 52 """ A FrontendWidget for an IPython kernel.
53 53 """
54 54
55 55 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
56 56 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
57 57 # settings.
58 58 custom_edit = Bool(False)
59 59 custom_edit_requested = QtCore.pyqtSignal(object, object)
60 60
61 61 # A command for invoking a system text editor. If the string contains a
62 62 # {filename} format specifier, it will be used. Otherwise, the filename will
63 63 # be appended to the end the command.
64 64 editor = Str('default', config=True)
65 65
66 66 # The editor command to use when a specific line number is requested. The
67 67 # string should contain two format specifiers: {line} and {filename}. If
68 68 # this parameter is not specified, the line number option to the %edit magic
69 69 # will be ignored.
70 70 editor_line = Str(config=True)
71 71
72 72 # A CSS stylesheet. The stylesheet can contain classes for:
73 73 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
74 74 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
75 75 # 3. IPython: .error, .in-prompt, .out-prompt, etc
76 76 style_sheet = Str(config=True)
77 77
78 78 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
79 79 # the style sheet is queried for Pygments style information.
80 80 syntax_style = Str(config=True)
81 81
82 82 # Prompts.
83 83 in_prompt = Str(default_in_prompt, config=True)
84 84 out_prompt = Str(default_out_prompt, config=True)
85 85 input_sep = Str(default_input_sep, config=True)
86 86 output_sep = Str(default_output_sep, config=True)
87 87 output_sep2 = Str(default_output_sep2, config=True)
88 88
89 89 # FrontendWidget protected class variables.
90 90 _input_splitter_class = IPythonInputSplitter
91 91
92 92 # IPythonWidget protected class variables.
93 93 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
94 94 _payload_source_edit = zmq_shell_source + '.edit_magic'
95 95 _payload_source_exit = zmq_shell_source + '.ask_exit'
96 96 _payload_source_loadpy = zmq_shell_source + '.magic_loadpy'
97 97 _payload_source_page = 'IPython.zmq.page.page'
98 98
99 99 #---------------------------------------------------------------------------
100 100 # 'object' interface
101 101 #---------------------------------------------------------------------------
102 102
103 103 def __init__(self, *args, **kw):
104 104 super(IPythonWidget, self).__init__(*args, **kw)
105 105
106 106 # IPythonWidget protected variables.
107 107 self._code_to_load = None
108 108 self._payload_handlers = {
109 109 self._payload_source_edit : self._handle_payload_edit,
110 110 self._payload_source_exit : self._handle_payload_exit,
111 111 self._payload_source_page : self._handle_payload_page,
112 112 self._payload_source_loadpy : self._handle_payload_loadpy }
113 113 self._previous_prompt_obj = None
114 114 self._keep_kernel_on_exit = None
115 115
116 116 # Initialize widget styling.
117 117 if self.style_sheet:
118 118 self._style_sheet_changed()
119 119 self._syntax_style_changed()
120 120 else:
121 121 self.set_default_style()
122 122
123 123 #---------------------------------------------------------------------------
124 124 # 'BaseFrontendMixin' abstract interface
125 125 #---------------------------------------------------------------------------
126 126
127 127 def _handle_complete_reply(self, rep):
128 128 """ Reimplemented to support IPython's improved completion machinery.
129 129 """
130 130 cursor = self._get_cursor()
131 131 info = self._request_info.get('complete')
132 132 if info and info.id == rep['parent_header']['msg_id'] and \
133 133 info.pos == cursor.position():
134 134 matches = rep['content']['matches']
135 135 text = rep['content']['matched_text']
136 136 offset = len(text)
137 137
138 138 # Clean up matches with period and path separators if the matched
139 139 # text has not been transformed. This is done by truncating all
140 140 # but the last component and then suitably decreasing the offset
141 141 # between the current cursor position and the start of completion.
142 142 if len(matches) > 1 and matches[0][:offset] == text:
143 143 parts = re.split(r'[./\\]', text)
144 144 sep_count = len(parts) - 1
145 145 if sep_count:
146 146 chop_length = sum(map(len, parts[:sep_count])) + sep_count
147 147 matches = [ match[chop_length:] for match in matches ]
148 148 offset -= chop_length
149 149
150 150 # Move the cursor to the start of the match and complete.
151 151 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
152 152 self._complete_with_items(cursor, matches)
153 153
154 154 def _handle_execute_reply(self, msg):
155 155 """ Reimplemented to support prompt requests.
156 156 """
157 157 info = self._request_info.get('execute')
158 158 if info and info.id == msg['parent_header']['msg_id']:
159 159 if info.kind == 'prompt':
160 160 number = msg['content']['execution_count'] + 1
161 161 self._show_interpreter_prompt(number)
162 162 else:
163 163 super(IPythonWidget, self)._handle_execute_reply(msg)
164 164
165 165 def _handle_history_reply(self, msg):
166 166 """ Implemented to handle history replies, which are only supported by
167 167 the IPython kernel.
168 168 """
169 169 history_dict = msg['content']['history']
170 170 input_history_dict = {}
171 171 for key,val in history_dict.items():
172 172 input_history_dict[int(key)] = val
173 173 items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ]
174 174 self._set_history(items)
175 175
176 176 def _handle_pyout(self, msg):
177 177 """ Reimplemented for IPython-style "display hook".
178 178 """
179 179 if not self._hidden and self._is_from_this_session(msg):
180 180 content = msg['content']
181 181 prompt_number = content['execution_count']
182 182 self._append_plain_text(self.output_sep)
183 183 self._append_html(self._make_out_prompt(prompt_number))
184 184 self._append_plain_text(content['data']+self.output_sep2)
185 185
186 def _handle_display_data(self, msg):
187 """ The base handler for the ``display_data`` message.
188 """
189 # For now, we don't display data from other frontends, but we
190 # eventually will as this allows all frontends to monitor the display
191 # data. But we need to figure out how to handle this in the GUI.
192 if not self._hidden and self._is_from_this_session(msg):
193 source = msg['content']['source']
194 data = msg['content']['data']
195 metadata = msg['content']['metadata']
196 # In the regular IPythonWidget, we simply print the plain text
197 # representation.
198 if data.has_key('text/plain'):
199 self._append_plain_text(data['text/plain'])
200
186 201 def _started_channels(self):
187 202 """ Reimplemented to make a history request.
188 203 """
189 204 super(IPythonWidget, self)._started_channels()
190 205 self.kernel_manager.xreq_channel.history(raw=True, output=False)
191 206
192 207 #---------------------------------------------------------------------------
193 208 # 'ConsoleWidget' public interface
194 209 #---------------------------------------------------------------------------
195 210
196 211 def copy(self):
197 212 """ Copy the currently selected text to the clipboard, removing prompts
198 213 if possible.
199 214 """
200 215 text = unicode(self._control.textCursor().selection().toPlainText())
201 216 if text:
202 217 lines = map(transform_ipy_prompt, text.splitlines())
203 218 text = '\n'.join(lines)
204 219 QtGui.QApplication.clipboard().setText(text)
205 220
206 221 #---------------------------------------------------------------------------
207 222 # 'FrontendWidget' public interface
208 223 #---------------------------------------------------------------------------
209 224
210 225 def execute_file(self, path, hidden=False):
211 226 """ Reimplemented to use the 'run' magic.
212 227 """
213 228 self.execute('%%run %s' % path, hidden=hidden)
214 229
215 230 #---------------------------------------------------------------------------
216 231 # 'FrontendWidget' protected interface
217 232 #---------------------------------------------------------------------------
218 233
219 234 def _complete(self):
220 235 """ Reimplemented to support IPython's improved completion machinery.
221 236 """
222 237 # We let the kernel split the input line, so we *always* send an empty
223 238 # text field. Readline-based frontends do get a real text field which
224 239 # they can use.
225 240 text = ''
226 241
227 242 # Send the completion request to the kernel
228 243 msg_id = self.kernel_manager.xreq_channel.complete(
229 244 text, # text
230 245 self._get_input_buffer_cursor_line(), # line
231 246 self._get_input_buffer_cursor_column(), # cursor_pos
232 247 self.input_buffer) # block
233 248 pos = self._get_cursor().position()
234 249 info = self._CompletionRequest(msg_id, pos)
235 250 self._request_info['complete'] = info
236 251
237 252 def _get_banner(self):
238 253 """ Reimplemented to return IPython's default banner.
239 254 """
240 255 return default_gui_banner
241 256
242 257 def _process_execute_error(self, msg):
243 258 """ Reimplemented for IPython-style traceback formatting.
244 259 """
245 260 content = msg['content']
246 261 traceback = '\n'.join(content['traceback']) + '\n'
247 262 if False:
248 263 # FIXME: For now, tracebacks come as plain text, so we can't use
249 264 # the html renderer yet. Once we refactor ultratb to produce
250 265 # properly styled tracebacks, this branch should be the default
251 266 traceback = traceback.replace(' ', '&nbsp;')
252 267 traceback = traceback.replace('\n', '<br/>')
253 268
254 269 ename = content['ename']
255 270 ename_styled = '<span class="error">%s</span>' % ename
256 271 traceback = traceback.replace(ename, ename_styled)
257 272
258 273 self._append_html(traceback)
259 274 else:
260 275 # This is the fallback for now, using plain text with ansi escapes
261 276 self._append_plain_text(traceback)
262 277
263 278 def _process_execute_payload(self, item):
264 279 """ Reimplemented to dispatch payloads to handler methods.
265 280 """
266 281 handler = self._payload_handlers.get(item['source'])
267 282 if handler is None:
268 283 # We have no handler for this type of payload, simply ignore it
269 284 return False
270 285 else:
271 286 handler(item)
272 287 return True
273 288
274 289 def _show_interpreter_prompt(self, number=None):
275 290 """ Reimplemented for IPython-style prompts.
276 291 """
277 292 # If a number was not specified, make a prompt number request.
278 293 if number is None:
279 294 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
280 295 info = self._ExecutionRequest(msg_id, 'prompt')
281 296 self._request_info['execute'] = info
282 297 return
283 298
284 299 # Show a new prompt and save information about it so that it can be
285 300 # updated later if the prompt number turns out to be wrong.
286 301 self._prompt_sep = self.input_sep
287 302 self._show_prompt(self._make_in_prompt(number), html=True)
288 303 block = self._control.document().lastBlock()
289 304 length = len(self._prompt)
290 305 self._previous_prompt_obj = self._PromptBlock(block, length, number)
291 306
292 307 # Update continuation prompt to reflect (possibly) new prompt length.
293 308 self._set_continuation_prompt(
294 309 self._make_continuation_prompt(self._prompt), html=True)
295 310
296 311 # Load code from the %loadpy magic, if necessary.
297 312 if self._code_to_load is not None:
298 313 self.input_buffer = dedent(unicode(self._code_to_load).rstrip())
299 314 self._code_to_load = None
300 315
301 316 def _show_interpreter_prompt_for_reply(self, msg):
302 317 """ Reimplemented for IPython-style prompts.
303 318 """
304 319 # Update the old prompt number if necessary.
305 320 content = msg['content']
306 321 previous_prompt_number = content['execution_count']
307 322 if self._previous_prompt_obj and \
308 323 self._previous_prompt_obj.number != previous_prompt_number:
309 324 block = self._previous_prompt_obj.block
310 325
311 326 # Make sure the prompt block has not been erased.
312 327 if block.isValid() and not block.text().isEmpty():
313 328
314 329 # Remove the old prompt and insert a new prompt.
315 330 cursor = QtGui.QTextCursor(block)
316 331 cursor.movePosition(QtGui.QTextCursor.Right,
317 332 QtGui.QTextCursor.KeepAnchor,
318 333 self._previous_prompt_obj.length)
319 334 prompt = self._make_in_prompt(previous_prompt_number)
320 335 self._prompt = self._insert_html_fetching_plain_text(
321 336 cursor, prompt)
322 337
323 338 # When the HTML is inserted, Qt blows away the syntax
324 339 # highlighting for the line, so we need to rehighlight it.
325 340 self._highlighter.rehighlightBlock(cursor.block())
326 341
327 342 self._previous_prompt_obj = None
328 343
329 344 # Show a new prompt with the kernel's estimated prompt number.
330 345 self._show_interpreter_prompt(previous_prompt_number + 1)
331 346
332 347 #---------------------------------------------------------------------------
333 348 # 'IPythonWidget' interface
334 349 #---------------------------------------------------------------------------
335 350
336 351 def set_default_style(self, colors='lightbg'):
337 352 """ Sets the widget style to the class defaults.
338 353
339 354 Parameters:
340 355 -----------
341 356 colors : str, optional (default lightbg)
342 357 Whether to use the default IPython light background or dark
343 358 background or B&W style.
344 359 """
345 360 colors = colors.lower()
346 361 if colors=='lightbg':
347 362 self.style_sheet = default_light_style_sheet
348 363 self.syntax_style = default_light_syntax_style
349 364 elif colors=='linux':
350 365 self.style_sheet = default_dark_style_sheet
351 366 self.syntax_style = default_dark_syntax_style
352 367 elif colors=='nocolor':
353 368 self.style_sheet = default_bw_style_sheet
354 369 self.syntax_style = default_bw_syntax_style
355 370 else:
356 371 raise KeyError("No such color scheme: %s"%colors)
357 372
358 373 #---------------------------------------------------------------------------
359 374 # 'IPythonWidget' protected interface
360 375 #---------------------------------------------------------------------------
361 376
362 377 def _edit(self, filename, line=None):
363 378 """ Opens a Python script for editing.
364 379
365 380 Parameters:
366 381 -----------
367 382 filename : str
368 383 A path to a local system file.
369 384
370 385 line : int, optional
371 386 A line of interest in the file.
372 387 """
373 388 if self.custom_edit:
374 389 self.custom_edit_requested.emit(filename, line)
375 390 elif self.editor == 'default':
376 391 self._append_plain_text('No default editor available.\n')
377 392 else:
378 393 try:
379 394 filename = '"%s"' % filename
380 395 if line and self.editor_line:
381 396 command = self.editor_line.format(filename=filename,
382 397 line=line)
383 398 else:
384 399 try:
385 400 command = self.editor.format()
386 401 except KeyError:
387 402 command = self.editor.format(filename=filename)
388 403 else:
389 404 command += ' ' + filename
390 405 except KeyError:
391 406 self._append_plain_text('Invalid editor command.\n')
392 407 else:
393 408 try:
394 409 Popen(command, shell=True)
395 410 except OSError:
396 411 msg = 'Opening editor with command "%s" failed.\n'
397 412 self._append_plain_text(msg % command)
398 413
399 414 def _make_in_prompt(self, number):
400 415 """ Given a prompt number, returns an HTML In prompt.
401 416 """
402 417 body = self.in_prompt % number
403 418 return '<span class="in-prompt">%s</span>' % body
404 419
405 420 def _make_continuation_prompt(self, prompt):
406 421 """ Given a plain text version of an In prompt, returns an HTML
407 422 continuation prompt.
408 423 """
409 424 end_chars = '...: '
410 425 space_count = len(prompt.lstrip('\n')) - len(end_chars)
411 426 body = '&nbsp;' * space_count + end_chars
412 427 return '<span class="in-prompt">%s</span>' % body
413 428
414 429 def _make_out_prompt(self, number):
415 430 """ Given a prompt number, returns an HTML Out prompt.
416 431 """
417 432 body = self.out_prompt % number
418 433 return '<span class="out-prompt">%s</span>' % body
419 434
420 435 #------ Payload handlers --------------------------------------------------
421 436
422 437 # Payload handlers with a generic interface: each takes the opaque payload
423 438 # dict, unpacks it and calls the underlying functions with the necessary
424 439 # arguments.
425 440
426 441 def _handle_payload_edit(self, item):
427 442 self._edit(item['filename'], item['line_number'])
428 443
429 444 def _handle_payload_exit(self, item):
430 445 self._keep_kernel_on_exit = item['keepkernel']
431 446 self.exit_requested.emit()
432 447
433 448 def _handle_payload_loadpy(self, item):
434 449 # Simple save the text of the .py file for later. The text is written
435 450 # to the buffer when _prompt_started_hook is called.
436 451 self._code_to_load = item['text']
437 452
438 453 def _handle_payload_page(self, item):
439 454 # Since the plain text widget supports only a very small subset of HTML
440 455 # and we have no control over the HTML source, we only page HTML
441 456 # payloads in the rich text widget.
442 457 if item['html'] and self.kind == 'rich':
443 458 self._page(item['html'], html=True)
444 459 else:
445 460 self._page(item['text'], html=False)
446 461
447 #------ Trait change handlers ---------------------------------------------
462 #------ Trait change handlers --------------------------------------------
448 463
449 464 def _style_sheet_changed(self):
450 465 """ Set the style sheets of the underlying widgets.
451 466 """
452 467 self.setStyleSheet(self.style_sheet)
453 468 self._control.document().setDefaultStyleSheet(self.style_sheet)
454 469 if self._page_control:
455 470 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
456 471
457 472 bg_color = self._control.palette().background().color()
458 473 self._ansi_processor.set_background_color(bg_color)
459 474
460 475 def _syntax_style_changed(self):
461 476 """ Set the style for the syntax highlighter.
462 477 """
463 478 if self.syntax_style:
464 479 self._highlighter.set_style(self.syntax_style)
465 480 else:
466 481 self._highlighter.set_style_sheet(self.style_sheet)
467
482
@@ -1,195 +1,226 b''
1 1 # System library imports
2 2 import os
3 3 import re
4 4 from PyQt4 import QtCore, QtGui
5 5
6 6 # Local imports
7 7 from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image
8 8 from ipython_widget import IPythonWidget
9 9
10 10
11 11 class RichIPythonWidget(IPythonWidget):
12 12 """ An IPythonWidget that supports rich text, including lists, images, and
13 13 tables. Note that raw performance will be reduced compared to the plain
14 14 text version.
15 15 """
16 16
17 17 # RichIPythonWidget protected class variables.
18 18 _payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload'
19 19 _svg_text_format_property = 1
20 20
21 21 #---------------------------------------------------------------------------
22 22 # 'object' interface
23 23 #---------------------------------------------------------------------------
24 24
25 25 def __init__(self, *args, **kw):
26 26 """ Create a RichIPythonWidget.
27 27 """
28 28 kw['kind'] = 'rich'
29 29 super(RichIPythonWidget, self).__init__(*args, **kw)
30 30 # Dictionary for resolving Qt names to images when
31 31 # generating XHTML output
32 32 self._name_to_svg = {}
33 33
34 34 #---------------------------------------------------------------------------
35 35 # 'ConsoleWidget' protected interface
36 36 #---------------------------------------------------------------------------
37 37
38 38 def _context_menu_make(self, pos):
39 39 """ Reimplemented to return a custom context menu for images.
40 40 """
41 41 format = self._control.cursorForPosition(pos).charFormat()
42 42 name = format.stringProperty(QtGui.QTextFormat.ImageName)
43 43 if name.isEmpty():
44 44 menu = super(RichIPythonWidget, self)._context_menu_make(pos)
45 45 else:
46 46 menu = QtGui.QMenu()
47 47
48 48 menu.addAction('Copy Image', lambda: self._copy_image(name))
49 49 menu.addAction('Save Image As...', lambda: self._save_image(name))
50 50 menu.addSeparator()
51 51
52 52 svg = format.stringProperty(self._svg_text_format_property)
53 53 if not svg.isEmpty():
54 54 menu.addSeparator()
55 55 menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg))
56 56 menu.addAction('Save SVG As...',
57 57 lambda: save_svg(svg, self._control))
58 58 return menu
59
59
60 #---------------------------------------------------------------------------
61 # 'BaseFrontendMixin' abstract interface
62 #---------------------------------------------------------------------------
63
64 def _handle_display_data(self, msg):
65 """ A handler for ``display_data`` message that handles html and svg.
66 """
67 if not self._hidden and self._is_from_this_session(msg):
68 source = msg['content']['source']
69 data = msg['content']['data']
70 metadata = msg['content']['metadata']
71 # Try to use the svg or html representations.
72 # FIXME: Is this the right ordering of things to try?
73 if data.has_key('image/svg+xml'):
74 svg = data['image/svg+xml']
75 # TODO: try/except this call.
76 self._append_svg(svg)
77 elif data.has_key('text/html'):
78 html = data['text/html']
79 self._append_html(html)
80 else:
81 # Default back to the plain text representation.
82 return super(RichIPythonWidget, self)._handle_display_data(msg)
83
60 84 #---------------------------------------------------------------------------
61 85 # 'FrontendWidget' protected interface
62 86 #---------------------------------------------------------------------------
63 87
64 88 def _process_execute_payload(self, item):
65 89 """ Reimplemented to handle matplotlib plot payloads.
66 90 """
67 91 if item['source'] == self._payload_source_plot:
92 # TODO: remove this as all plot data is coming back through the
93 # display_data message type.
68 94 if item['format'] == 'svg':
69 95 svg = item['data']
70 try:
71 image = svg_to_image(svg)
72 except ValueError:
73 self._append_plain_text('Received invalid plot data.')
74 else:
75 format = self._add_image(image)
76 self._name_to_svg[str(format.name())] = svg
77 format.setProperty(self._svg_text_format_property, svg)
78 cursor = self._get_end_cursor()
79 cursor.insertBlock()
80 cursor.insertImage(format)
81 cursor.insertBlock()
96 self._append_svg(svg)
82 97 return True
83 98 else:
84 99 # Add other plot formats here!
85 100 return False
86 101 else:
87 102 return super(RichIPythonWidget, self)._process_execute_payload(item)
88 103
89 104 #---------------------------------------------------------------------------
90 105 # 'RichIPythonWidget' protected interface
91 106 #---------------------------------------------------------------------------
92 107
108 def _append_svg(self, svg):
109 """ Append raw svg data to the widget.
110 """
111 try:
112 image = svg_to_image(svg)
113 except ValueError:
114 self._append_plain_text('Received invalid plot data.')
115 else:
116 format = self._add_image(image)
117 self._name_to_svg[str(format.name())] = svg
118 format.setProperty(self._svg_text_format_property, svg)
119 cursor = self._get_end_cursor()
120 cursor.insertBlock()
121 cursor.insertImage(format)
122 cursor.insertBlock()
123
93 124 def _add_image(self, image):
94 125 """ Adds the specified QImage to the document and returns a
95 126 QTextImageFormat that references it.
96 127 """
97 128 document = self._control.document()
98 129 name = QtCore.QString.number(image.cacheKey())
99 130 document.addResource(QtGui.QTextDocument.ImageResource,
100 131 QtCore.QUrl(name), image)
101 132 format = QtGui.QTextImageFormat()
102 133 format.setName(name)
103 134 return format
104 135
105 136 def _copy_image(self, name):
106 137 """ Copies the ImageResource with 'name' to the clipboard.
107 138 """
108 139 image = self._get_image(name)
109 140 QtGui.QApplication.clipboard().setImage(image)
110 141
111 142 def _get_image(self, name):
112 143 """ Returns the QImage stored as the ImageResource with 'name'.
113 144 """
114 145 document = self._control.document()
115 146 variant = document.resource(QtGui.QTextDocument.ImageResource,
116 147 QtCore.QUrl(name))
117 148 return variant.toPyObject()
118 149
119 150 def _save_image(self, name, format='PNG'):
120 151 """ Shows a save dialog for the ImageResource with 'name'.
121 152 """
122 153 dialog = QtGui.QFileDialog(self._control, 'Save Image')
123 154 dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
124 155 dialog.setDefaultSuffix(format.lower())
125 156 dialog.setNameFilter('%s file (*.%s)' % (format, format.lower()))
126 157 if dialog.exec_():
127 158 filename = dialog.selectedFiles()[0]
128 159 image = self._get_image(name)
129 160 image.save(filename, format)
130 161
131 162 def image_tag(self, match, path = None, format = "png"):
132 163 """ Return (X)HTML mark-up for the image-tag given by match.
133 164
134 165 Parameters
135 166 ----------
136 167 match : re.SRE_Match
137 168 A match to an HTML image tag as exported by Qt, with
138 169 match.group("Name") containing the matched image ID.
139 170
140 171 path : string|None, optional [default None]
141 172 If not None, specifies a path to which supporting files
142 173 may be written (e.g., for linked images).
143 174 If None, all images are to be included inline.
144 175
145 176 format : "png"|"svg", optional [default "png"]
146 177 Format for returned or referenced images.
147 178
148 179 Subclasses supporting image display should override this
149 180 method.
150 181 """
151 182
152 183 if(format == "png"):
153 184 try:
154 185 image = self._get_image(match.group("name"))
155 186 except KeyError:
156 187 return "<b>Couldn't find image %s</b>" % match.group("name")
157 188
158 189 if(path is not None):
159 190 if not os.path.exists(path):
160 191 os.mkdir(path)
161 192 relpath = os.path.basename(path)
162 193 if(image.save("%s/qt_img%s.png" % (path,match.group("name")),
163 194 "PNG")):
164 195 return '<img src="%s/qt_img%s.png">' % (relpath,
165 196 match.group("name"))
166 197 else:
167 198 return "<b>Couldn't save image!</b>"
168 199 else:
169 200 ba = QtCore.QByteArray()
170 201 buffer_ = QtCore.QBuffer(ba)
171 202 buffer_.open(QtCore.QIODevice.WriteOnly)
172 203 image.save(buffer_, "PNG")
173 204 buffer_.close()
174 205 return '<img src="data:image/png;base64,\n%s\n" />' % (
175 206 re.sub(r'(.{60})',r'\1\n',str(ba.toBase64())))
176 207
177 208 elif(format == "svg"):
178 209 try:
179 210 svg = str(self._name_to_svg[match.group("name")])
180 211 except KeyError:
181 212 return "<b>Couldn't find image %s</b>" % match.group("name")
182 213
183 214 # Not currently checking path, because it's tricky to find a
184 215 # cross-browser way to embed external SVG images (e.g., via
185 216 # object or embed tags).
186 217
187 218 # Chop stand-alone header from matplotlib SVG
188 219 offset = svg.find("<svg")
189 220 assert(offset > -1)
190 221
191 222 return svg[offset:]
192 223
193 224 else:
194 225 return '<b>Unrecognized image format</b>'
195
226
@@ -1,240 +1,242 b''
1 1 """ Defines a KernelManager that provides signals and slots.
2 2 """
3 3
4 4 # System library imports.
5 5 from PyQt4 import QtCore
6 6
7 7 # IPython imports.
8 8 from IPython.utils.traitlets import Type
9 9 from IPython.zmq.kernelmanager import KernelManager, SubSocketChannel, \
10 10 XReqSocketChannel, RepSocketChannel, HBSocketChannel
11 11 from util import MetaQObjectHasTraits, SuperQObject
12 12
13 13
14 14 class SocketChannelQObject(SuperQObject):
15 15
16 16 # Emitted when the channel is started.
17 17 started = QtCore.pyqtSignal()
18 18
19 19 # Emitted when the channel is stopped.
20 20 stopped = QtCore.pyqtSignal()
21 21
22 22 #---------------------------------------------------------------------------
23 23 # 'ZmqSocketChannel' interface
24 24 #---------------------------------------------------------------------------
25 25
26 26 def start(self):
27 27 """ Reimplemented to emit signal.
28 28 """
29 29 super(SocketChannelQObject, self).start()
30 30 self.started.emit()
31 31
32 32 def stop(self):
33 33 """ Reimplemented to emit signal.
34 34 """
35 35 super(SocketChannelQObject, self).stop()
36 36 self.stopped.emit()
37 37
38 38
39 39 class QtXReqSocketChannel(SocketChannelQObject, XReqSocketChannel):
40 40
41 41 # Emitted when any message is received.
42 42 message_received = QtCore.pyqtSignal(object)
43 43
44 44 # Emitted when a reply has been received for the corresponding request
45 45 # type.
46 46 execute_reply = QtCore.pyqtSignal(object)
47 47 complete_reply = QtCore.pyqtSignal(object)
48 48 object_info_reply = QtCore.pyqtSignal(object)
49 49
50 50 # Emitted when the first reply comes back.
51 51 first_reply = QtCore.pyqtSignal()
52 52
53 53 # Used by the first_reply signal logic to determine if a reply is the
54 54 # first.
55 55 _handlers_called = False
56 56
57 57 #---------------------------------------------------------------------------
58 58 # 'XReqSocketChannel' interface
59 59 #---------------------------------------------------------------------------
60 60
61 61 def call_handlers(self, msg):
62 62 """ Reimplemented to emit signals instead of making callbacks.
63 63 """
64 64 # Emit the generic signal.
65 65 self.message_received.emit(msg)
66 66
67 67 # Emit signals for specialized message types.
68 68 msg_type = msg['msg_type']
69 69 signal = getattr(self, msg_type, None)
70 70 if signal:
71 71 signal.emit(msg)
72 72
73 73 if not self._handlers_called:
74 74 self.first_reply.emit()
75 75 self._handlers_called = True
76 76
77 77 #---------------------------------------------------------------------------
78 78 # 'QtXReqSocketChannel' interface
79 79 #---------------------------------------------------------------------------
80 80
81 81 def reset_first_reply(self):
82 82 """ Reset the first_reply signal to fire again on the next reply.
83 83 """
84 84 self._handlers_called = False
85 85
86 86
87 87 class QtSubSocketChannel(SocketChannelQObject, SubSocketChannel):
88 88
89 89 # Emitted when any message is received.
90 90 message_received = QtCore.pyqtSignal(object)
91 91
92 92 # Emitted when a message of type 'stream' is received.
93 93 stream_received = QtCore.pyqtSignal(object)
94 94
95 95 # Emitted when a message of type 'pyin' is received.
96 96 pyin_received = QtCore.pyqtSignal(object)
97 97
98 98 # Emitted when a message of type 'pyout' is received.
99 99 pyout_received = QtCore.pyqtSignal(object)
100 100
101 101 # Emitted when a message of type 'pyerr' is received.
102 102 pyerr_received = QtCore.pyqtSignal(object)
103 103
104 # Emitted when a message of type 'display_data' is received
105 display_data_received = QtCore.pyqtSignal(object)
106
104 107 # Emitted when a crash report message is received from the kernel's
105 108 # last-resort sys.excepthook.
106 109 crash_received = QtCore.pyqtSignal(object)
107 110
108 111 # Emitted when a shutdown is noticed.
109 112 shutdown_reply_received = QtCore.pyqtSignal(object)
110 113
111 114 #---------------------------------------------------------------------------
112 115 # 'SubSocketChannel' interface
113 116 #---------------------------------------------------------------------------
114 117
115 118 def call_handlers(self, msg):
116 119 """ Reimplemented to emit signals instead of making callbacks.
117 120 """
118 121 # Emit the generic signal.
119 122 self.message_received.emit(msg)
120
121 123 # Emit signals for specialized message types.
122 124 msg_type = msg['msg_type']
123 125 signal = getattr(self, msg_type + '_received', None)
124 126 if signal:
125 127 signal.emit(msg)
126 128 elif msg_type in ('stdout', 'stderr'):
127 129 self.stream_received.emit(msg)
128 130
129 131 def flush(self):
130 132 """ Reimplemented to ensure that signals are dispatched immediately.
131 133 """
132 134 super(QtSubSocketChannel, self).flush()
133 135 QtCore.QCoreApplication.instance().processEvents()
134 136
135 137
136 138 class QtRepSocketChannel(SocketChannelQObject, RepSocketChannel):
137 139
138 140 # Emitted when any message is received.
139 141 message_received = QtCore.pyqtSignal(object)
140 142
141 143 # Emitted when an input request is received.
142 144 input_requested = QtCore.pyqtSignal(object)
143 145
144 146 #---------------------------------------------------------------------------
145 147 # 'RepSocketChannel' interface
146 148 #---------------------------------------------------------------------------
147 149
148 150 def call_handlers(self, msg):
149 151 """ Reimplemented to emit signals instead of making callbacks.
150 152 """
151 153 # Emit the generic signal.
152 154 self.message_received.emit(msg)
153 155
154 156 # Emit signals for specialized message types.
155 157 msg_type = msg['msg_type']
156 158 if msg_type == 'input_request':
157 159 self.input_requested.emit(msg)
158 160
159 161
160 162 class QtHBSocketChannel(SocketChannelQObject, HBSocketChannel):
161 163
162 164 # Emitted when the kernel has died.
163 165 kernel_died = QtCore.pyqtSignal(object)
164 166
165 167 #---------------------------------------------------------------------------
166 168 # 'HBSocketChannel' interface
167 169 #---------------------------------------------------------------------------
168 170
169 171 def call_handlers(self, since_last_heartbeat):
170 172 """ Reimplemented to emit signals instead of making callbacks.
171 173 """
172 174 # Emit the generic signal.
173 175 self.kernel_died.emit(since_last_heartbeat)
174 176
175 177
176 178 class QtKernelManager(KernelManager, SuperQObject):
177 179 """ A KernelManager that provides signals and slots.
178 180 """
179 181
180 182 __metaclass__ = MetaQObjectHasTraits
181 183
182 184 # Emitted when the kernel manager has started listening.
183 185 started_channels = QtCore.pyqtSignal()
184 186
185 187 # Emitted when the kernel manager has stopped listening.
186 188 stopped_channels = QtCore.pyqtSignal()
187 189
188 190 # Use Qt-specific channel classes that emit signals.
189 191 sub_channel_class = Type(QtSubSocketChannel)
190 192 xreq_channel_class = Type(QtXReqSocketChannel)
191 193 rep_channel_class = Type(QtRepSocketChannel)
192 194 hb_channel_class = Type(QtHBSocketChannel)
193 195
194 196 #---------------------------------------------------------------------------
195 197 # 'KernelManager' interface
196 198 #---------------------------------------------------------------------------
197 199
198 200 #------ Kernel process management ------------------------------------------
199 201
200 202 def start_kernel(self, *args, **kw):
201 203 """ Reimplemented for proper heartbeat management.
202 204 """
203 205 if self._xreq_channel is not None:
204 206 self._xreq_channel.reset_first_reply()
205 207 super(QtKernelManager, self).start_kernel(*args, **kw)
206 208
207 209 #------ Channel management -------------------------------------------------
208 210
209 211 def start_channels(self, *args, **kw):
210 212 """ Reimplemented to emit signal.
211 213 """
212 214 super(QtKernelManager, self).start_channels(*args, **kw)
213 215 self.started_channels.emit()
214 216
215 217 def stop_channels(self):
216 218 """ Reimplemented to emit signal.
217 219 """
218 220 super(QtKernelManager, self).stop_channels()
219 221 self.stopped_channels.emit()
220 222
221 223 @property
222 224 def xreq_channel(self):
223 225 """ Reimplemented for proper heartbeat management.
224 226 """
225 227 if self._xreq_channel is None:
226 228 self._xreq_channel = super(QtKernelManager, self).xreq_channel
227 229 self._xreq_channel.first_reply.connect(self._first_reply)
228 230 return self._xreq_channel
229 231
230 232 #---------------------------------------------------------------------------
231 233 # Protected interface
232 234 #---------------------------------------------------------------------------
233 235
234 236 def _first_reply(self):
235 237 """ Unpauses the heartbeat channel when the first reply is received on
236 238 the execute channel. Note that this will *not* start the heartbeat
237 239 channel if it is not already running!
238 240 """
239 241 if self._hb_channel is not None:
240 242 self._hb_channel.unpause()
@@ -1,629 +1,632 b''
1 1 #!/usr/bin/env python
2 2 """A simple interactive kernel that talks to a frontend over 0MQ.
3 3
4 4 Things to do:
5 5
6 6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 7 call set_parent on all the PUB objects with the message about to be executed.
8 8 * Implement random port and security key logic.
9 9 * Implement control messages.
10 10 * Implement event loop and poll version.
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Standard library imports.
19 19 import __builtin__
20 20 import atexit
21 21 import sys
22 22 import time
23 23 import traceback
24 24
25 25 # System library imports.
26 26 import zmq
27 27
28 28 # Local imports.
29 29 from IPython.config.configurable import Configurable
30 30 from IPython.utils import io
31 31 from IPython.utils.jsonutil import json_clean
32 32 from IPython.lib import pylabtools
33 33 from IPython.utils.traitlets import Instance, Float
34 34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
35 35 start_kernel)
36 36 from iostream import OutStream
37 37 from session import Session, Message
38 38 from zmqshell import ZMQInteractiveShell
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Main kernel class
42 42 #-----------------------------------------------------------------------------
43 43
44 44 class Kernel(Configurable):
45 45
46 46 #---------------------------------------------------------------------------
47 47 # Kernel interface
48 48 #---------------------------------------------------------------------------
49 49
50 50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 51 session = Instance(Session)
52 52 reply_socket = Instance('zmq.Socket')
53 53 pub_socket = Instance('zmq.Socket')
54 54 req_socket = Instance('zmq.Socket')
55 55
56 56 # Private interface
57 57
58 58 # Time to sleep after flushing the stdout/err buffers in each execute
59 59 # cycle. While this introduces a hard limit on the minimal latency of the
60 60 # execute cycle, it helps prevent output synchronization problems for
61 61 # clients.
62 62 # Units are in seconds. The minimum zmq latency on local host is probably
63 63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 64 # a little if it's not enough after more interactive testing.
65 65 _execute_sleep = Float(0.0005, config=True)
66 66
67 67 # Frequency of the kernel's event loop.
68 68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 69 # adapt to milliseconds.
70 70 _poll_interval = Float(0.05, config=True)
71 71
72 72 # If the shutdown was requested over the network, we leave here the
73 73 # necessary reply message so it can be sent by our registered atexit
74 74 # handler. This ensures that the reply is only sent to clients truly at
75 75 # the end of our shutdown process (which happens after the underlying
76 76 # IPython shell's own shutdown).
77 77 _shutdown_message = None
78 78
79 79 # This is a dict of port number that the kernel is listening on. It is set
80 80 # by record_ports and used by connect_request.
81 81 _recorded_ports = None
82 82
83 83 def __init__(self, **kwargs):
84 84 super(Kernel, self).__init__(**kwargs)
85 85
86 86 # Before we even start up the shell, register *first* our exit handlers
87 87 # so they come before the shell's
88 88 atexit.register(self._at_shutdown)
89 89
90 90 # Initialize the InteractiveShell subclass
91 91 self.shell = ZMQInteractiveShell.instance()
92 92 self.shell.displayhook.session = self.session
93 93 self.shell.displayhook.pub_socket = self.pub_socket
94 self.shell.display_pub.session = self.session
95 self.shell.display_pub.pub_socket = self.pub_socket
94 96
95 97 # TMP - hack while developing
96 98 self.shell._reply_content = None
97 99
98 100 # Build dict of handlers for message types
99 101 msg_types = [ 'execute_request', 'complete_request',
100 102 'object_info_request', 'history_request',
101 103 'connect_request', 'shutdown_request']
102 104 self.handlers = {}
103 105 for msg_type in msg_types:
104 106 self.handlers[msg_type] = getattr(self, msg_type)
105 107
106 108 def do_one_iteration(self):
107 109 """Do one iteration of the kernel's evaluation loop.
108 110 """
109 111 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
110 112 if msg is None:
111 113 return
112 114
113 115 # This assert will raise in versions of zeromq 2.0.7 and lesser.
114 116 # We now require 2.0.8 or above, so we can uncomment for safety.
115 117 # print(ident,msg, file=sys.__stdout__)
116 118 assert ident is not None, "Missing message part."
117 119
118 120 # Print some info about this message and leave a '--->' marker, so it's
119 121 # easier to trace visually the message chain when debugging. Each
120 122 # handler prints its message at the end.
121 123 # Eventually we'll move these from stdout to a logger.
122 124 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
123 125 io.raw_print(' Content: ', msg['content'],
124 126 '\n --->\n ', sep='', end='')
125 127
126 128 # Find and call actual handler for message
127 129 handler = self.handlers.get(msg['msg_type'], None)
128 130 if handler is None:
129 131 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
130 132 else:
131 133 handler(ident, msg)
132 134
133 135 # Check whether we should exit, in case the incoming message set the
134 136 # exit flag on
135 137 if self.shell.exit_now:
136 138 io.raw_print('\nExiting IPython kernel...')
137 139 # We do a normal, clean exit, which allows any actions registered
138 140 # via atexit (such as history saving) to take place.
139 141 sys.exit(0)
140 142
141 143
142 144 def start(self):
143 145 """ Start the kernel main loop.
144 146 """
145 147 while True:
146 148 time.sleep(self._poll_interval)
147 149 self.do_one_iteration()
148 150
149 151 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
150 152 """Record the ports that this kernel is using.
151 153
152 154 The creator of the Kernel instance must call this methods if they
153 155 want the :meth:`connect_request` method to return the port numbers.
154 156 """
155 157 self._recorded_ports = {
156 158 'xrep_port' : xrep_port,
157 159 'pub_port' : pub_port,
158 160 'req_port' : req_port,
159 161 'hb_port' : hb_port
160 162 }
161 163
162 164 #---------------------------------------------------------------------------
163 165 # Kernel request handlers
164 166 #---------------------------------------------------------------------------
165 167
166 168 def _publish_pyin(self, code, parent):
167 169 """Publish the code request on the pyin stream."""
168 170
169 171 pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent)
170 172
171 173 def execute_request(self, ident, parent):
172 174
173 175 status_msg = self.session.send(self.pub_socket,
174 176 u'status',
175 177 {u'execution_state':u'busy'},
176 178 parent=parent
177 179 )
178 180
179 181 try:
180 182 content = parent[u'content']
181 183 code = content[u'code']
182 184 silent = content[u'silent']
183 185 except:
184 186 io.raw_print_err("Got bad msg: ")
185 187 io.raw_print_err(Message(parent))
186 188 return
187 189
188 190 shell = self.shell # we'll need this a lot here
189 191
190 192 # Replace raw_input. Note that is not sufficient to replace
191 193 # raw_input in the user namespace.
192 194 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
193 195 __builtin__.raw_input = raw_input
194 196
195 197 # Set the parent message of the display hook and out streams.
196 198 shell.displayhook.set_parent(parent)
199 shell.display_pub.set_parent(parent)
197 200 sys.stdout.set_parent(parent)
198 201 sys.stderr.set_parent(parent)
199 202
200 203 # Re-broadcast our input for the benefit of listening clients, and
201 204 # start computing output
202 205 if not silent:
203 206 self._publish_pyin(code, parent)
204 207
205 208 reply_content = {}
206 209 try:
207 210 if silent:
208 211 # run_code uses 'exec' mode, so no displayhook will fire, and it
209 212 # doesn't call logging or history manipulations. Print
210 213 # statements in that code will obviously still execute.
211 214 shell.run_code(code)
212 215 else:
213 216 # FIXME: the shell calls the exception handler itself.
214 217 shell._reply_content = None
215 218 shell.run_cell(code)
216 219 except:
217 220 status = u'error'
218 221 # FIXME: this code right now isn't being used yet by default,
219 222 # because the runlines() call above directly fires off exception
220 223 # reporting. This code, therefore, is only active in the scenario
221 224 # where runlines itself has an unhandled exception. We need to
222 225 # uniformize this, for all exception construction to come from a
223 226 # single location in the codbase.
224 227 etype, evalue, tb = sys.exc_info()
225 228 tb_list = traceback.format_exception(etype, evalue, tb)
226 229 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
227 230 else:
228 231 status = u'ok'
229 232
230 233 reply_content[u'status'] = status
231 234
232 235 # Return the execution counter so clients can display prompts
233 236 reply_content['execution_count'] = shell.execution_count -1
234 237
235 238 # FIXME - fish exception info out of shell, possibly left there by
236 239 # runlines. We'll need to clean up this logic later.
237 240 if shell._reply_content is not None:
238 241 reply_content.update(shell._reply_content)
239 242
240 243 # At this point, we can tell whether the main code execution succeeded
241 244 # or not. If it did, we proceed to evaluate user_variables/expressions
242 245 if reply_content['status'] == 'ok':
243 246 reply_content[u'user_variables'] = \
244 247 shell.user_variables(content[u'user_variables'])
245 248 reply_content[u'user_expressions'] = \
246 249 shell.user_expressions(content[u'user_expressions'])
247 250 else:
248 251 # If there was an error, don't even try to compute variables or
249 252 # expressions
250 253 reply_content[u'user_variables'] = {}
251 254 reply_content[u'user_expressions'] = {}
252 255
253 256 # Payloads should be retrieved regardless of outcome, so we can both
254 257 # recover partial output (that could have been generated early in a
255 258 # block, before an error) and clear the payload system always.
256 259 reply_content[u'payload'] = shell.payload_manager.read_payload()
257 260 # Be agressive about clearing the payload because we don't want
258 261 # it to sit in memory until the next execute_request comes in.
259 262 shell.payload_manager.clear_payload()
260 263
261 264 # Send the reply.
262 265 reply_msg = self.session.send(self.reply_socket, u'execute_reply', reply_content, parent, ident=ident)
263 266 io.raw_print(reply_msg)
264 267
265 268 # Flush output before sending the reply.
266 269 sys.stdout.flush()
267 270 sys.stderr.flush()
268 271 # FIXME: on rare occasions, the flush doesn't seem to make it to the
269 272 # clients... This seems to mitigate the problem, but we definitely need
270 273 # to better understand what's going on.
271 274 if self._execute_sleep:
272 275 time.sleep(self._execute_sleep)
273 276
274 277 if reply_msg['content']['status'] == u'error':
275 278 self._abort_queue()
276 279
277 280 status_msg = self.session.send(self.pub_socket,
278 281 u'status',
279 282 {u'execution_state':u'idle'},
280 283 parent=parent
281 284 )
282 285
283 286 def complete_request(self, ident, parent):
284 287 txt, matches = self._complete(parent)
285 288 matches = {'matches' : matches,
286 289 'matched_text' : txt,
287 290 'status' : 'ok'}
288 291 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
289 292 matches, parent, ident)
290 293 io.raw_print(completion_msg)
291 294
292 295 def object_info_request(self, ident, parent):
293 296 object_info = self.shell.object_inspect(parent['content']['oname'])
294 297 # Before we send this object over, we scrub it for JSON usage
295 298 oinfo = json_clean(object_info)
296 299 msg = self.session.send(self.reply_socket, 'object_info_reply',
297 300 oinfo, parent, ident)
298 301 io.raw_print(msg)
299 302
300 303 def history_request(self, ident, parent):
301 304 output = parent['content']['output']
302 305 index = parent['content']['index']
303 306 raw = parent['content']['raw']
304 307 hist = self.shell.get_history(index=index, raw=raw, output=output)
305 308 content = {'history' : hist}
306 309 msg = self.session.send(self.reply_socket, 'history_reply',
307 310 content, parent, ident)
308 311 io.raw_print(msg)
309 312
310 313 def connect_request(self, ident, parent):
311 314 if self._recorded_ports is not None:
312 315 content = self._recorded_ports.copy()
313 316 else:
314 317 content = {}
315 318 msg = self.session.send(self.reply_socket, 'connect_reply',
316 319 content, parent, ident)
317 320 io.raw_print(msg)
318 321
319 322 def shutdown_request(self, ident, parent):
320 323 self.shell.exit_now = True
321 324 self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent)
322 325 sys.exit(0)
323 326
324 327 #---------------------------------------------------------------------------
325 328 # Protected interface
326 329 #---------------------------------------------------------------------------
327 330
328 331 def _abort_queue(self):
329 332 while True:
330 333 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
331 334 if msg is None:
332 335 break
333 336 else:
334 337 assert ident is not None, \
335 338 "Unexpected missing message part."
336 339 io.raw_print("Aborting:\n", Message(msg))
337 340 msg_type = msg['msg_type']
338 341 reply_type = msg_type.split('_')[0] + '_reply'
339 342 reply_msg = self.session.send(self.reply_socket, reply_type,
340 343 {'status' : 'aborted'}, msg, ident=ident)
341 344 io.raw_print(reply_msg)
342 345 # We need to wait a bit for requests to come in. This can probably
343 346 # be set shorter for true asynchronous clients.
344 347 time.sleep(0.1)
345 348
346 349 def _raw_input(self, prompt, ident, parent):
347 350 # Flush output before making the request.
348 351 sys.stderr.flush()
349 352 sys.stdout.flush()
350 353
351 354 # Send the input request.
352 355 content = dict(prompt=prompt)
353 356 msg = self.session.send(self.req_socket, u'input_request', content, parent)
354 357
355 358 # Await a response.
356 359 ident, reply = self.session.recv(self.req_socket, 0)
357 360 try:
358 361 value = reply['content']['value']
359 362 except:
360 363 io.raw_print_err("Got bad raw_input reply: ")
361 364 io.raw_print_err(Message(parent))
362 365 value = ''
363 366 return value
364 367
365 368 def _complete(self, msg):
366 369 c = msg['content']
367 370 try:
368 371 cpos = int(c['cursor_pos'])
369 372 except:
370 373 # If we don't get something that we can convert to an integer, at
371 374 # least attempt the completion guessing the cursor is at the end of
372 375 # the text, if there's any, and otherwise of the line
373 376 cpos = len(c['text'])
374 377 if cpos==0:
375 378 cpos = len(c['line'])
376 379 return self.shell.complete(c['text'], c['line'], cpos)
377 380
378 381 def _object_info(self, context):
379 382 symbol, leftover = self._symbol_from_context(context)
380 383 if symbol is not None and not leftover:
381 384 doc = getattr(symbol, '__doc__', '')
382 385 else:
383 386 doc = ''
384 387 object_info = dict(docstring = doc)
385 388 return object_info
386 389
387 390 def _symbol_from_context(self, context):
388 391 if not context:
389 392 return None, context
390 393
391 394 base_symbol_string = context[0]
392 395 symbol = self.shell.user_ns.get(base_symbol_string, None)
393 396 if symbol is None:
394 397 symbol = __builtin__.__dict__.get(base_symbol_string, None)
395 398 if symbol is None:
396 399 return None, context
397 400
398 401 context = context[1:]
399 402 for i, name in enumerate(context):
400 403 new_symbol = getattr(symbol, name, None)
401 404 if new_symbol is None:
402 405 return symbol, context[i:]
403 406 else:
404 407 symbol = new_symbol
405 408
406 409 return symbol, []
407 410
408 411 def _at_shutdown(self):
409 412 """Actions taken at shutdown by the kernel, called by python's atexit.
410 413 """
411 414 # io.rprint("Kernel at_shutdown") # dbg
412 415 if self._shutdown_message is not None:
413 416 self.session.send(self.reply_socket, self._shutdown_message)
414 417 self.session.send(self.pub_socket, self._shutdown_message)
415 418 io.raw_print(self._shutdown_message)
416 419 # A very short sleep to give zmq time to flush its message buffers
417 420 # before Python truly shuts down.
418 421 time.sleep(0.01)
419 422
420 423
421 424 class QtKernel(Kernel):
422 425 """A Kernel subclass with Qt support."""
423 426
424 427 def start(self):
425 428 """Start a kernel with QtPy4 event loop integration."""
426 429
427 430 from PyQt4 import QtCore
428 431 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
429 432
430 433 self.app = get_app_qt4([" "])
431 434 self.app.setQuitOnLastWindowClosed(False)
432 435 self.timer = QtCore.QTimer()
433 436 self.timer.timeout.connect(self.do_one_iteration)
434 437 # Units for the timer are in milliseconds
435 438 self.timer.start(1000*self._poll_interval)
436 439 start_event_loop_qt4(self.app)
437 440
438 441
439 442 class WxKernel(Kernel):
440 443 """A Kernel subclass with Wx support."""
441 444
442 445 def start(self):
443 446 """Start a kernel with wx event loop support."""
444 447
445 448 import wx
446 449 from IPython.lib.guisupport import start_event_loop_wx
447 450
448 451 doi = self.do_one_iteration
449 452 # Wx uses milliseconds
450 453 poll_interval = int(1000*self._poll_interval)
451 454
452 455 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
453 456 # We make the Frame hidden when we create it in the main app below.
454 457 class TimerFrame(wx.Frame):
455 458 def __init__(self, func):
456 459 wx.Frame.__init__(self, None, -1)
457 460 self.timer = wx.Timer(self)
458 461 # Units for the timer are in milliseconds
459 462 self.timer.Start(poll_interval)
460 463 self.Bind(wx.EVT_TIMER, self.on_timer)
461 464 self.func = func
462 465
463 466 def on_timer(self, event):
464 467 self.func()
465 468
466 469 # We need a custom wx.App to create our Frame subclass that has the
467 470 # wx.Timer to drive the ZMQ event loop.
468 471 class IPWxApp(wx.App):
469 472 def OnInit(self):
470 473 self.frame = TimerFrame(doi)
471 474 self.frame.Show(False)
472 475 return True
473 476
474 477 # The redirect=False here makes sure that wx doesn't replace
475 478 # sys.stdout/stderr with its own classes.
476 479 self.app = IPWxApp(redirect=False)
477 480 start_event_loop_wx(self.app)
478 481
479 482
480 483 class TkKernel(Kernel):
481 484 """A Kernel subclass with Tk support."""
482 485
483 486 def start(self):
484 487 """Start a Tk enabled event loop."""
485 488
486 489 import Tkinter
487 490 doi = self.do_one_iteration
488 491 # Tk uses milliseconds
489 492 poll_interval = int(1000*self._poll_interval)
490 493 # For Tkinter, we create a Tk object and call its withdraw method.
491 494 class Timer(object):
492 495 def __init__(self, func):
493 496 self.app = Tkinter.Tk()
494 497 self.app.withdraw()
495 498 self.func = func
496 499
497 500 def on_timer(self):
498 501 self.func()
499 502 self.app.after(poll_interval, self.on_timer)
500 503
501 504 def start(self):
502 505 self.on_timer() # Call it once to get things going.
503 506 self.app.mainloop()
504 507
505 508 self.timer = Timer(doi)
506 509 self.timer.start()
507 510
508 511
509 512 class GTKKernel(Kernel):
510 513 """A Kernel subclass with GTK support."""
511 514
512 515 def start(self):
513 516 """Start the kernel, coordinating with the GTK event loop"""
514 517 from .gui.gtkembed import GTKEmbed
515 518
516 519 gtk_kernel = GTKEmbed(self)
517 520 gtk_kernel.start()
518 521
519 522
520 523 #-----------------------------------------------------------------------------
521 524 # Kernel main and launch functions
522 525 #-----------------------------------------------------------------------------
523 526
524 527 def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0,
525 528 independent=False, pylab=False, colors=None):
526 529 """Launches a localhost kernel, binding to the specified ports.
527 530
528 531 Parameters
529 532 ----------
530 533 ip : str, optional
531 534 The ip address the kernel will bind to.
532 535
533 536 xrep_port : int, optional
534 537 The port to use for XREP channel.
535 538
536 539 pub_port : int, optional
537 540 The port to use for the SUB channel.
538 541
539 542 req_port : int, optional
540 543 The port to use for the REQ (raw input) channel.
541 544
542 545 hb_port : int, optional
543 546 The port to use for the hearbeat REP channel.
544 547
545 548 independent : bool, optional (default False)
546 549 If set, the kernel process is guaranteed to survive if this process
547 550 dies. If not set, an effort is made to ensure that the kernel is killed
548 551 when this process dies. Note that in this case it is still good practice
549 552 to kill kernels manually before exiting.
550 553
551 554 pylab : bool or string, optional (default False)
552 555 If not False, the kernel will be launched with pylab enabled. If a
553 556 string is passed, matplotlib will use the specified backend. Otherwise,
554 557 matplotlib's default backend will be used.
555 558
556 559 colors : None or string, optional (default None)
557 560 If not None, specify the color scheme. One of (NoColor, LightBG, Linux)
558 561
559 562 Returns
560 563 -------
561 564 A tuple of form:
562 565 (kernel_process, xrep_port, pub_port, req_port)
563 566 where kernel_process is a Popen object and the ports are integers.
564 567 """
565 568 extra_arguments = []
566 569 if pylab:
567 570 extra_arguments.append('--pylab')
568 571 if isinstance(pylab, basestring):
569 572 extra_arguments.append(pylab)
570 573 if ip is not None:
571 574 extra_arguments.append('--ip')
572 575 if isinstance(ip, basestring):
573 576 extra_arguments.append(ip)
574 577 if colors is not None:
575 578 extra_arguments.append('--colors')
576 579 extra_arguments.append(colors)
577 580 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
578 581 xrep_port, pub_port, req_port, hb_port,
579 582 independent, extra_arguments)
580 583
581 584
582 585 def main():
583 586 """ The IPython kernel main entry point.
584 587 """
585 588 parser = make_argument_parser()
586 589 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
587 590 const='auto', help = \
588 591 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
589 592 given, the GUI backend is matplotlib's, otherwise use one of: \
590 593 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
591 594 parser.add_argument('--colors',
592 595 type=str, dest='colors',
593 596 help="Set the color scheme (NoColor, Linux, and LightBG).",
594 597 metavar='ZMQInteractiveShell.colors')
595 598 namespace = parser.parse_args()
596 599
597 600 kernel_class = Kernel
598 601
599 602 kernel_classes = {
600 603 'qt' : QtKernel,
601 604 'qt4': QtKernel,
602 605 'inline': Kernel,
603 606 'wx' : WxKernel,
604 607 'tk' : TkKernel,
605 608 'gtk': GTKKernel,
606 609 }
607 610 if namespace.pylab:
608 611 if namespace.pylab == 'auto':
609 612 gui, backend = pylabtools.find_gui_and_backend()
610 613 else:
611 614 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
612 615 kernel_class = kernel_classes.get(gui)
613 616 if kernel_class is None:
614 617 raise ValueError('GUI is not supported: %r' % gui)
615 618 pylabtools.activate_matplotlib(backend)
616 619 if namespace.colors:
617 620 ZMQInteractiveShell.colors=namespace.colors
618 621
619 622 kernel = make_kernel(namespace, kernel_class, OutStream)
620 623
621 624 if namespace.pylab:
622 625 pylabtools.import_pylab(kernel.shell.user_ns, backend,
623 626 shell=kernel.shell)
624 627
625 628 start_kernel(namespace, kernel)
626 629
627 630
628 631 if __name__ == '__main__':
629 632 main()
@@ -1,119 +1,123 b''
1 1 """Produce SVG versions of active plots for display by the rich Qt frontend.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Imports
5 5 #-----------------------------------------------------------------------------
6 6 from __future__ import print_function
7 7
8 8 # Standard library imports
9 9 from cStringIO import StringIO
10 10
11 11 # System library imports.
12 12 import matplotlib
13 13 from matplotlib.backends.backend_svg import new_figure_manager
14 14 from matplotlib._pylab_helpers import Gcf
15 15
16 16 # Local imports.
17 from backend_payload import add_plot_payload
17 from IPython.core.displaypub import publish_display_data
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Functions
21 21 #-----------------------------------------------------------------------------
22 22
23 23 def show(close=True):
24 24 """Show all figures as SVG payloads sent to the IPython clients.
25 25
26 26 Parameters
27 27 ----------
28 28 close : bool, optional
29 29 If true, a ``plt.close('all')`` call is automatically issued after
30 30 sending all the SVG figures.
31 31 """
32 32 for figure_manager in Gcf.get_all_fig_managers():
33 33 send_svg_canvas(figure_manager.canvas)
34 34 if close:
35 35 matplotlib.pyplot.close('all')
36 36
37 37 # This flag will be reset by draw_if_interactive when called
38 38 show._draw_called = False
39 39
40 40
41 41 def figsize(sizex, sizey):
42 42 """Set the default figure size to be [sizex, sizey].
43 43
44 44 This is just an easy to remember, convenience wrapper that sets::
45 45
46 46 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
47 47 """
48 48 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
49 49
50 50
51 51 def pastefig(*figs):
52 52 """Paste one or more figures into the console workspace.
53 53
54 54 If no arguments are given, all available figures are pasted. If the
55 55 argument list contains references to invalid figures, a warning is printed
56 56 but the function continues pasting further figures.
57 57
58 58 Parameters
59 59 ----------
60 60 figs : tuple
61 61 A tuple that can contain any mixture of integers and figure objects.
62 62 """
63 63 if not figs:
64 64 show(close=False)
65 65 else:
66 66 fig_managers = Gcf.get_all_fig_managers()
67 67 fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers]
68 68 + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] )
69 69
70 70 for fig in figs:
71 71 canvas = fig_index.get(fig)
72 72 if canvas is None:
73 73 print('Warning: figure %s not available.' % fig)
74 74 else:
75 75 send_svg_canvas(canvas)
76 76
77 77
78 78 def send_svg_canvas(canvas):
79 79 """Draw the current canvas and send it as an SVG payload.
80 80 """
81 81 # Set the background to white instead so it looks good on black. We store
82 82 # the current values to restore them at the end.
83 83 fc = canvas.figure.get_facecolor()
84 84 ec = canvas.figure.get_edgecolor()
85 85 canvas.figure.set_facecolor('white')
86 86 canvas.figure.set_edgecolor('white')
87 87 try:
88 add_plot_payload('svg', svg_from_canvas(canvas))
88 publish_display_data(
89 'IPython.zmq.pylab.backend_inline.send_svg_canvas',
90 '<Matplotlib Plot>',
91 svg=svg_from_canvas(canvas)
92 )
89 93 finally:
90 94 canvas.figure.set_facecolor(fc)
91 95 canvas.figure.set_edgecolor(ec)
92 96
93 97
94 98 def svg_from_canvas(canvas):
95 99 """ Return a string containing the SVG representation of a FigureCanvasSvg.
96 100 """
97 101 string_io = StringIO()
98 102 canvas.print_figure(string_io, format='svg')
99 103 return string_io.getvalue()
100 104
101 105
102 106 def draw_if_interactive():
103 107 """
104 108 Is called after every pylab drawing command
105 109 """
106 110 # We simply flag we were called and otherwise do nothing. At the end of
107 111 # the code execution, a separate call to show_close() will act upon this.
108 112 show._draw_called = True
109 113
110 114
111 115 def flush_svg():
112 116 """Call show, close all open figures, sending all SVG images.
113 117
114 118 This is meant to be called automatically and will call show() if, during
115 119 prior code execution, there had been any calls to draw_if_interactive.
116 120 """
117 121 if show._draw_called:
118 122 show(close=True)
119 123 show._draw_called = False
@@ -1,580 +1,605 b''
1 1 """A ZMQ-based subclass of InteractiveShell.
2 2
3 3 This code is meant to ease the refactoring of the base InteractiveShell into
4 4 something with a cleaner architecture for 2-process use, without actually
5 5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 6 we subclass and override what we want to fix. Once this is working well, we
7 7 can go back to the base class and refactor the code for a cleaner inheritance
8 8 implementation that doesn't rely on so much monkeypatching.
9 9
10 10 But this lets us maintain a fully working IPython as we develop the new
11 11 machinery. This should thus be thought of as scaffolding.
12 12 """
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Stdlib
19 19 import inspect
20 20 import os
21 21 import re
22 22
23 23 # Our own
24 24 from IPython.core.interactiveshell import (
25 25 InteractiveShell, InteractiveShellABC
26 26 )
27 27 from IPython.core import page
28 28 from IPython.core.displayhook import DisplayHook
29 from IPython.core.displaypub import DisplayPublisher
29 30 from IPython.core.macro import Macro
30 31 from IPython.core.payloadpage import install_payload_page
31 32 from IPython.utils import io
32 33 from IPython.utils.path import get_py_filename
33 34 from IPython.utils.text import StringTypes
34 35 from IPython.utils.traitlets import Instance, Type, Dict
35 36 from IPython.utils.warn import warn
36 37 from IPython.zmq.session import extract_header
37 38 from session import Session
38 39
39 40 #-----------------------------------------------------------------------------
40 41 # Globals and side-effects
41 42 #-----------------------------------------------------------------------------
42 43
43 44 # Install the payload version of page.
44 45 install_payload_page()
45 46
46 47 #-----------------------------------------------------------------------------
47 48 # Functions and classes
48 49 #-----------------------------------------------------------------------------
49 50
50 51 class ZMQDisplayHook(DisplayHook):
51 52
52 53 session = Instance(Session)
53 54 pub_socket = Instance('zmq.Socket')
54 55 parent_header = Dict({})
55 56
56 57 def set_parent(self, parent):
57 58 """Set the parent for outbound messages."""
58 59 self.parent_header = extract_header(parent)
59 60
60 61 def start_displayhook(self):
61 62 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
62 63
63 64 def write_output_prompt(self):
64 65 """Write the output prompt."""
65 66 if self.do_full_cache:
66 67 self.msg['content']['execution_count'] = self.prompt_count
67 68
68 69 def write_result_repr(self, result_repr, extra_formats):
69 70 self.msg['content']['data'] = result_repr
70 71 self.msg['content']['extra_formats'] = extra_formats
71 72
72 73 def finish_displayhook(self):
73 74 """Finish up all displayhook activities."""
74 75 self.session.send(self.pub_socket, self.msg)
75 76 self.msg = None
76 77
77 78
79 class ZMQDisplayPublisher(DisplayPublisher):
80 """A ``DisplayPublisher`` that published data using a ZeroMQ PUB socket."""
81
82 session = Instance(Session)
83 pub_socket = Instance('zmq.Socket')
84 parent_header = Dict({})
85
86 def set_parent(self, parent):
87 """Set the parent for outbound messages."""
88 self.parent_header = extract_header(parent)
89
90 def publish(self, source, data, metadata=None):
91 if metadata is None:
92 metadata = {}
93 self._validate_data(source, data, metadata)
94 msg = self.session.msg(u'display_data', {}, parent=self.parent_header)
95 msg['content']['source'] = source
96 msg['content']['data'] = data
97 msg['content']['metadata'] = metadata
98 self.pub_socket.send_json(msg)
99
100
78 101 class ZMQInteractiveShell(InteractiveShell):
79 102 """A subclass of InteractiveShell for ZMQ."""
80 103
81 104 displayhook_class = Type(ZMQDisplayHook)
105 display_pub_class = Type(ZMQDisplayPublisher)
106
82 107 keepkernel_on_exit = None
83 108
84 109 def init_environment(self):
85 110 """Configure the user's environment.
86 111
87 112 """
88 113 env = os.environ
89 114 # These two ensure 'ls' produces nice coloring on BSD-derived systems
90 115 env['TERM'] = 'xterm-color'
91 116 env['CLICOLOR'] = '1'
92 117 # Since normal pagers don't work at all (over pexpect we don't have
93 118 # single-key control of the subprocess), try to disable paging in
94 119 # subprocesses as much as possible.
95 120 env['PAGER'] = 'cat'
96 121 env['GIT_PAGER'] = 'cat'
97 122
98 123 def auto_rewrite_input(self, cmd):
99 124 """Called to show the auto-rewritten input for autocall and friends.
100 125
101 126 FIXME: this payload is currently not correctly processed by the
102 127 frontend.
103 128 """
104 129 new = self.displayhook.prompt1.auto_rewrite() + cmd
105 130 payload = dict(
106 131 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
107 132 transformed_input=new,
108 133 )
109 134 self.payload_manager.write_payload(payload)
110 135
111 136 def ask_exit(self):
112 137 """Engage the exit actions."""
113 138 payload = dict(
114 139 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
115 140 exit=True,
116 141 keepkernel=self.keepkernel_on_exit,
117 142 )
118 143 self.payload_manager.write_payload(payload)
119 144
120 145 def _showtraceback(self, etype, evalue, stb):
121 146
122 147 exc_content = {
123 148 u'traceback' : stb,
124 149 u'ename' : unicode(etype.__name__),
125 150 u'evalue' : unicode(evalue)
126 151 }
127 152
128 153 dh = self.displayhook
129 154 # Send exception info over pub socket for other clients than the caller
130 155 # to pick up
131 156 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header)
132 157
133 158 # FIXME - Hack: store exception info in shell object. Right now, the
134 159 # caller is reading this info after the fact, we need to fix this logic
135 160 # to remove this hack. Even uglier, we need to store the error status
136 161 # here, because in the main loop, the logic that sets it is being
137 162 # skipped because runlines swallows the exceptions.
138 163 exc_content[u'status'] = u'error'
139 164 self._reply_content = exc_content
140 165 # /FIXME
141 166
142 167 return exc_content
143 168
144 169 #------------------------------------------------------------------------
145 170 # Magic overrides
146 171 #------------------------------------------------------------------------
147 172 # Once the base class stops inheriting from magic, this code needs to be
148 173 # moved into a separate machinery as well. For now, at least isolate here
149 174 # the magics which this class needs to implement differently from the base
150 175 # class, or that are unique to it.
151 176
152 177 def magic_doctest_mode(self,parameter_s=''):
153 178 """Toggle doctest mode on and off.
154 179
155 180 This mode is intended to make IPython behave as much as possible like a
156 181 plain Python shell, from the perspective of how its prompts, exceptions
157 182 and output look. This makes it easy to copy and paste parts of a
158 183 session into doctests. It does so by:
159 184
160 185 - Changing the prompts to the classic ``>>>`` ones.
161 186 - Changing the exception reporting mode to 'Plain'.
162 187 - Disabling pretty-printing of output.
163 188
164 189 Note that IPython also supports the pasting of code snippets that have
165 190 leading '>>>' and '...' prompts in them. This means that you can paste
166 191 doctests from files or docstrings (even if they have leading
167 192 whitespace), and the code will execute correctly. You can then use
168 193 '%history -t' to see the translated history; this will give you the
169 194 input after removal of all the leading prompts and whitespace, which
170 195 can be pasted back into an editor.
171 196
172 197 With these features, you can switch into this mode easily whenever you
173 198 need to do testing and changes to doctests, without having to leave
174 199 your existing IPython session.
175 200 """
176 201
177 202 from IPython.utils.ipstruct import Struct
178 203
179 204 # Shorthands
180 205 shell = self.shell
181 206 # dstore is a data store kept in the instance metadata bag to track any
182 207 # changes we make, so we can undo them later.
183 208 dstore = shell.meta.setdefault('doctest_mode', Struct())
184 209 save_dstore = dstore.setdefault
185 210
186 211 # save a few values we'll need to recover later
187 212 mode = save_dstore('mode', False)
188 213 save_dstore('rc_pprint', shell.pprint)
189 214 save_dstore('xmode', shell.InteractiveTB.mode)
190 215
191 216 if mode == False:
192 217 # turn on
193 218 shell.pprint = False
194 219 shell.magic_xmode('Plain')
195 220 else:
196 221 # turn off
197 222 shell.pprint = dstore.rc_pprint
198 223 shell.magic_xmode(dstore.xmode)
199 224
200 225 # Store new mode and inform on console
201 226 dstore.mode = bool(1-int(mode))
202 227 mode_label = ['OFF','ON'][dstore.mode]
203 228 print('Doctest mode is:', mode_label)
204 229
205 230 # Send the payload back so that clients can modify their prompt display
206 231 payload = dict(
207 232 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
208 233 mode=dstore.mode)
209 234 self.payload_manager.write_payload(payload)
210 235
211 236 def magic_edit(self,parameter_s='',last_call=['','']):
212 237 """Bring up an editor and execute the resulting code.
213 238
214 239 Usage:
215 240 %edit [options] [args]
216 241
217 242 %edit runs IPython's editor hook. The default version of this hook is
218 243 set to call the __IPYTHON__.rc.editor command. This is read from your
219 244 environment variable $EDITOR. If this isn't found, it will default to
220 245 vi under Linux/Unix and to notepad under Windows. See the end of this
221 246 docstring for how to change the editor hook.
222 247
223 248 You can also set the value of this editor via the command line option
224 249 '-editor' or in your ipythonrc file. This is useful if you wish to use
225 250 specifically for IPython an editor different from your typical default
226 251 (and for Windows users who typically don't set environment variables).
227 252
228 253 This command allows you to conveniently edit multi-line code right in
229 254 your IPython session.
230 255
231 256 If called without arguments, %edit opens up an empty editor with a
232 257 temporary file and will execute the contents of this file when you
233 258 close it (don't forget to save it!).
234 259
235 260
236 261 Options:
237 262
238 263 -n <number>: open the editor at a specified line number. By default,
239 264 the IPython editor hook uses the unix syntax 'editor +N filename', but
240 265 you can configure this by providing your own modified hook if your
241 266 favorite editor supports line-number specifications with a different
242 267 syntax.
243 268
244 269 -p: this will call the editor with the same data as the previous time
245 270 it was used, regardless of how long ago (in your current session) it
246 271 was.
247 272
248 273 -r: use 'raw' input. This option only applies to input taken from the
249 274 user's history. By default, the 'processed' history is used, so that
250 275 magics are loaded in their transformed version to valid Python. If
251 276 this option is given, the raw input as typed as the command line is
252 277 used instead. When you exit the editor, it will be executed by
253 278 IPython's own processor.
254 279
255 280 -x: do not execute the edited code immediately upon exit. This is
256 281 mainly useful if you are editing programs which need to be called with
257 282 command line arguments, which you can then do using %run.
258 283
259 284
260 285 Arguments:
261 286
262 287 If arguments are given, the following possibilites exist:
263 288
264 289 - The arguments are numbers or pairs of colon-separated numbers (like
265 290 1 4:8 9). These are interpreted as lines of previous input to be
266 291 loaded into the editor. The syntax is the same of the %macro command.
267 292
268 293 - If the argument doesn't start with a number, it is evaluated as a
269 294 variable and its contents loaded into the editor. You can thus edit
270 295 any string which contains python code (including the result of
271 296 previous edits).
272 297
273 298 - If the argument is the name of an object (other than a string),
274 299 IPython will try to locate the file where it was defined and open the
275 300 editor at the point where it is defined. You can use `%edit function`
276 301 to load an editor exactly at the point where 'function' is defined,
277 302 edit it and have the file be executed automatically.
278 303
279 304 If the object is a macro (see %macro for details), this opens up your
280 305 specified editor with a temporary file containing the macro's data.
281 306 Upon exit, the macro is reloaded with the contents of the file.
282 307
283 308 Note: opening at an exact line is only supported under Unix, and some
284 309 editors (like kedit and gedit up to Gnome 2.8) do not understand the
285 310 '+NUMBER' parameter necessary for this feature. Good editors like
286 311 (X)Emacs, vi, jed, pico and joe all do.
287 312
288 313 - If the argument is not found as a variable, IPython will look for a
289 314 file with that name (adding .py if necessary) and load it into the
290 315 editor. It will execute its contents with execfile() when you exit,
291 316 loading any code in the file into your interactive namespace.
292 317
293 318 After executing your code, %edit will return as output the code you
294 319 typed in the editor (except when it was an existing file). This way
295 320 you can reload the code in further invocations of %edit as a variable,
296 321 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
297 322 the output.
298 323
299 324 Note that %edit is also available through the alias %ed.
300 325
301 326 This is an example of creating a simple function inside the editor and
302 327 then modifying it. First, start up the editor:
303 328
304 329 In [1]: ed
305 330 Editing... done. Executing edited code...
306 331 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
307 332
308 333 We can then call the function foo():
309 334
310 335 In [2]: foo()
311 336 foo() was defined in an editing session
312 337
313 338 Now we edit foo. IPython automatically loads the editor with the
314 339 (temporary) file where foo() was previously defined:
315 340
316 341 In [3]: ed foo
317 342 Editing... done. Executing edited code...
318 343
319 344 And if we call foo() again we get the modified version:
320 345
321 346 In [4]: foo()
322 347 foo() has now been changed!
323 348
324 349 Here is an example of how to edit a code snippet successive
325 350 times. First we call the editor:
326 351
327 352 In [5]: ed
328 353 Editing... done. Executing edited code...
329 354 hello
330 355 Out[5]: "print 'hello'n"
331 356
332 357 Now we call it again with the previous output (stored in _):
333 358
334 359 In [6]: ed _
335 360 Editing... done. Executing edited code...
336 361 hello world
337 362 Out[6]: "print 'hello world'n"
338 363
339 364 Now we call it with the output #8 (stored in _8, also as Out[8]):
340 365
341 366 In [7]: ed _8
342 367 Editing... done. Executing edited code...
343 368 hello again
344 369 Out[7]: "print 'hello again'n"
345 370
346 371
347 372 Changing the default editor hook:
348 373
349 374 If you wish to write your own editor hook, you can put it in a
350 375 configuration file which you load at startup time. The default hook
351 376 is defined in the IPython.core.hooks module, and you can use that as a
352 377 starting example for further modifications. That file also has
353 378 general instructions on how to set a new hook for use once you've
354 379 defined it."""
355 380
356 381 # FIXME: This function has become a convoluted mess. It needs a
357 382 # ground-up rewrite with clean, simple logic.
358 383
359 384 def make_filename(arg):
360 385 "Make a filename from the given args"
361 386 try:
362 387 filename = get_py_filename(arg)
363 388 except IOError:
364 389 if args.endswith('.py'):
365 390 filename = arg
366 391 else:
367 392 filename = None
368 393 return filename
369 394
370 395 # custom exceptions
371 396 class DataIsObject(Exception): pass
372 397
373 398 opts,args = self.parse_options(parameter_s,'prn:')
374 399 # Set a few locals from the options for convenience:
375 400 opts_p = opts.has_key('p')
376 401 opts_r = opts.has_key('r')
377 402
378 403 # Default line number value
379 404 lineno = opts.get('n',None)
380 405 if lineno is not None:
381 406 try:
382 407 lineno = int(lineno)
383 408 except:
384 409 warn("The -n argument must be an integer.")
385 410 return
386 411
387 412 if opts_p:
388 413 args = '_%s' % last_call[0]
389 414 if not self.shell.user_ns.has_key(args):
390 415 args = last_call[1]
391 416
392 417 # use last_call to remember the state of the previous call, but don't
393 418 # let it be clobbered by successive '-p' calls.
394 419 try:
395 420 last_call[0] = self.shell.displayhook.prompt_count
396 421 if not opts_p:
397 422 last_call[1] = parameter_s
398 423 except:
399 424 pass
400 425
401 426 # by default this is done with temp files, except when the given
402 427 # arg is a filename
403 428 use_temp = 1
404 429
405 430 if re.match(r'\d',args):
406 431 # Mode where user specifies ranges of lines, like in %macro.
407 432 # This means that you can't edit files whose names begin with
408 433 # numbers this way. Tough.
409 434 ranges = args.split()
410 435 data = ''.join(self.extract_input_slices(ranges,opts_r))
411 436 elif args.endswith('.py'):
412 437 filename = make_filename(args)
413 438 data = ''
414 439 use_temp = 0
415 440 elif args:
416 441 try:
417 442 # Load the parameter given as a variable. If not a string,
418 443 # process it as an object instead (below)
419 444
420 445 #print '*** args',args,'type',type(args) # dbg
421 446 data = eval(args,self.shell.user_ns)
422 447 if not type(data) in StringTypes:
423 448 raise DataIsObject
424 449
425 450 except (NameError,SyntaxError):
426 451 # given argument is not a variable, try as a filename
427 452 filename = make_filename(args)
428 453 if filename is None:
429 454 warn("Argument given (%s) can't be found as a variable "
430 455 "or as a filename." % args)
431 456 return
432 457
433 458 data = ''
434 459 use_temp = 0
435 460 except DataIsObject:
436 461
437 462 # macros have a special edit function
438 463 if isinstance(data,Macro):
439 464 self._edit_macro(args,data)
440 465 return
441 466
442 467 # For objects, try to edit the file where they are defined
443 468 try:
444 469 filename = inspect.getabsfile(data)
445 470 if 'fakemodule' in filename.lower() and inspect.isclass(data):
446 471 # class created by %edit? Try to find source
447 472 # by looking for method definitions instead, the
448 473 # __module__ in those classes is FakeModule.
449 474 attrs = [getattr(data, aname) for aname in dir(data)]
450 475 for attr in attrs:
451 476 if not inspect.ismethod(attr):
452 477 continue
453 478 filename = inspect.getabsfile(attr)
454 479 if filename and 'fakemodule' not in filename.lower():
455 480 # change the attribute to be the edit target instead
456 481 data = attr
457 482 break
458 483
459 484 datafile = 1
460 485 except TypeError:
461 486 filename = make_filename(args)
462 487 datafile = 1
463 488 warn('Could not find file where `%s` is defined.\n'
464 489 'Opening a file named `%s`' % (args,filename))
465 490 # Now, make sure we can actually read the source (if it was in
466 491 # a temp file it's gone by now).
467 492 if datafile:
468 493 try:
469 494 if lineno is None:
470 495 lineno = inspect.getsourcelines(data)[1]
471 496 except IOError:
472 497 filename = make_filename(args)
473 498 if filename is None:
474 499 warn('The file `%s` where `%s` was defined cannot '
475 500 'be read.' % (filename,data))
476 501 return
477 502 use_temp = 0
478 503 else:
479 504 data = ''
480 505
481 506 if use_temp:
482 507 filename = self.shell.mktempfile(data)
483 508 print('IPython will make a temporary file named:', filename)
484 509
485 510 # Make sure we send to the client an absolute path, in case the working
486 511 # directory of client and kernel don't match
487 512 filename = os.path.abspath(filename)
488 513
489 514 payload = {
490 515 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
491 516 'filename' : filename,
492 517 'line_number' : lineno
493 518 }
494 519 self.payload_manager.write_payload(payload)
495 520
496 521 def magic_gui(self, *args, **kwargs):
497 522 raise NotImplementedError(
498 523 'GUI support must be enabled in command line options.')
499 524
500 525 def magic_pylab(self, *args, **kwargs):
501 526 raise NotImplementedError(
502 527 'pylab support must be enabled in command line options.')
503 528
504 529 # A few magics that are adapted to the specifics of using pexpect and a
505 530 # remote terminal
506 531
507 532 def magic_clear(self, arg_s):
508 533 """Clear the terminal."""
509 534 if os.name == 'posix':
510 535 self.shell.system("clear")
511 536 else:
512 537 self.shell.system("cls")
513 538
514 539 if os.name == 'nt':
515 540 # This is the usual name in windows
516 541 magic_cls = magic_clear
517 542
518 543 # Terminal pagers won't work over pexpect, but we do have our own pager
519 544
520 545 def magic_less(self, arg_s):
521 546 """Show a file through the pager.
522 547
523 548 Files ending in .py are syntax-highlighted."""
524 549 cont = open(arg_s).read()
525 550 if arg_s.endswith('.py'):
526 551 cont = self.shell.pycolorize(cont)
527 552 page.page(cont)
528 553
529 554 magic_more = magic_less
530 555
531 556 # Man calls a pager, so we also need to redefine it
532 557 if os.name == 'posix':
533 558 def magic_man(self, arg_s):
534 559 """Find the man page for the given command and display in pager."""
535 560 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
536 561 split=False))
537 562
538 563 # FIXME: this is specific to the GUI, so we should let the gui app load
539 564 # magics at startup that are only for the gui. Once the gui app has proper
540 565 # profile and configuration management, we can have it initialize a kernel
541 566 # with a special config file that provides these.
542 567 def magic_guiref(self, arg_s):
543 568 """Show a basic reference about the GUI console."""
544 569 from IPython.core.usage import gui_reference
545 570 page.page(gui_reference, auto_html=True)
546 571
547 572 def magic_loadpy(self, arg_s):
548 573 """Load a .py python script into the GUI console.
549 574
550 575 This magic command can either take a local filename or a url::
551 576
552 577 %loadpy myscript.py
553 578 %loadpy http://www.example.com/myscript.py
554 579 """
555 580 if not arg_s.endswith('.py'):
556 581 raise ValueError('%%load only works with .py files: %s' % arg_s)
557 582 if arg_s.startswith('http'):
558 583 import urllib2
559 584 response = urllib2.urlopen(arg_s)
560 585 content = response.read()
561 586 else:
562 587 content = open(arg_s).read()
563 588 payload = dict(
564 589 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy',
565 590 text=content
566 591 )
567 592 self.payload_manager.write_payload(payload)
568 593
569 594 def magic_Exit(self, parameter_s=''):
570 595 """Exit IPython. If the -k option is provided, the kernel will be left
571 596 running. Otherwise, it will shutdown without prompting.
572 597 """
573 598 opts,args = self.parse_options(parameter_s,'k')
574 599 self.shell.keepkernel_on_exit = opts.has_key('k')
575 600 self.shell.ask_exit()
576 601
577 602 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
578 603 magic_exit = magic_quit = magic_Quit = magic_Exit
579 604
580 605 InteractiveShellABC.register(ZMQInteractiveShell)
@@ -1,934 +1,936 b''
1 1 .. _messaging:
2 2
3 3 ======================
4 4 Messaging in IPython
5 5 ======================
6 6
7 7
8 8 Introduction
9 9 ============
10 10
11 11 This document explains the basic communications design and messaging
12 12 specification for how the various IPython objects interact over a network
13 13 transport. The current implementation uses the ZeroMQ_ library for messaging
14 14 within and between hosts.
15 15
16 16 .. Note::
17 17
18 18 This document should be considered the authoritative description of the
19 19 IPython messaging protocol, and all developers are strongly encouraged to
20 20 keep it updated as the implementation evolves, so that we have a single
21 21 common reference for all protocol details.
22 22
23 23 The basic design is explained in the following diagram:
24 24
25 25 .. image:: frontend-kernel.png
26 26 :width: 450px
27 27 :alt: IPython kernel/frontend messaging architecture.
28 28 :align: center
29 29 :target: ../_images/frontend-kernel.png
30 30
31 31 A single kernel can be simultaneously connected to one or more frontends. The
32 32 kernel has three sockets that serve the following functions:
33 33
34 34 1. REQ: this socket is connected to a *single* frontend at a time, and it allows
35 35 the kernel to request input from a frontend when :func:`raw_input` is called.
36 36 The frontend holding the matching REP socket acts as a 'virtual keyboard'
37 37 for the kernel while this communication is happening (illustrated in the
38 38 figure by the black outline around the central keyboard). In practice,
39 39 frontends may display such kernel requests using a special input widget or
40 40 otherwise indicating that the user is to type input for the kernel instead
41 41 of normal commands in the frontend.
42 42
43 43 2. XREP: this single sockets allows multiple incoming connections from
44 44 frontends, and this is the socket where requests for code execution, object
45 45 information, prompts, etc. are made to the kernel by any frontend. The
46 46 communication on this socket is a sequence of request/reply actions from
47 47 each frontend and the kernel.
48 48
49 49 3. PUB: this socket is the 'broadcast channel' where the kernel publishes all
50 50 side effects (stdout, stderr, etc.) as well as the requests coming from any
51 51 client over the XREP socket and its own requests on the REP socket. There
52 52 are a number of actions in Python which generate side effects: :func:`print`
53 53 writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in
54 54 a multi-client scenario, we want all frontends to be able to know what each
55 55 other has sent to the kernel (this can be useful in collaborative scenarios,
56 56 for example). This socket allows both side effects and the information
57 57 about communications taking place with one client over the XREQ/XREP channel
58 58 to be made available to all clients in a uniform manner.
59 59
60 60 All messages are tagged with enough information (details below) for clients
61 61 to know which messages come from their own interaction with the kernel and
62 62 which ones are from other clients, so they can display each type
63 63 appropriately.
64 64
65 65 The actual format of the messages allowed on each of these channels is
66 66 specified below. Messages are dicts of dicts with string keys and values that
67 67 are reasonably representable in JSON. Our current implementation uses JSON
68 68 explicitly as its message format, but this shouldn't be considered a permanent
69 69 feature. As we've discovered that JSON has non-trivial performance issues due
70 70 to excessive copying, we may in the future move to a pure pickle-based raw
71 71 message format. However, it should be possible to easily convert from the raw
72 72 objects to JSON, since we may have non-python clients (e.g. a web frontend).
73 73 As long as it's easy to make a JSON version of the objects that is a faithful
74 74 representation of all the data, we can communicate with such clients.
75 75
76 76 .. Note::
77 77
78 78 Not all of these have yet been fully fleshed out, but the key ones are, see
79 79 kernel and frontend files for actual implementation details.
80 80
81 81
82 82 Python functional API
83 83 =====================
84 84
85 85 As messages are dicts, they map naturally to a ``func(**kw)`` call form. We
86 86 should develop, at a few key points, functional forms of all the requests that
87 87 take arguments in this manner and automatically construct the necessary dict
88 88 for sending.
89 89
90 90
91 91 General Message Format
92 92 ======================
93 93
94 94 All messages send or received by any IPython process should have the following
95 95 generic structure::
96 96
97 97 {
98 98 # The message header contains a pair of unique identifiers for the
99 99 # originating session and the actual message id, in addition to the
100 100 # username for the process that generated the message. This is useful in
101 101 # collaborative settings where multiple users may be interacting with the
102 102 # same kernel simultaneously, so that frontends can label the various
103 103 # messages in a meaningful way.
104 104 'header' : { 'msg_id' : uuid,
105 105 'username' : str,
106 106 'session' : uuid
107 107 },
108 108
109 109 # In a chain of messages, the header from the parent is copied so that
110 110 # clients can track where messages come from.
111 111 'parent_header' : dict,
112 112
113 113 # All recognized message type strings are listed below.
114 114 'msg_type' : str,
115 115
116 116 # The actual content of the message must be a dict, whose structure
117 117 # depends on the message type.x
118 118 'content' : dict,
119 119 }
120 120
121 121 For each message type, the actual content will differ and all existing message
122 122 types are specified in what follows of this document.
123 123
124 124
125 125 Messages on the XREP/XREQ socket
126 126 ================================
127 127
128 128 .. _execute:
129 129
130 130 Execute
131 131 -------
132 132
133 133 This message type is used by frontends to ask the kernel to execute code on
134 134 behalf of the user, in a namespace reserved to the user's variables (and thus
135 135 separate from the kernel's own internal code and variables).
136 136
137 137 Message type: ``execute_request``::
138 138
139 139 content = {
140 140 # Source code to be executed by the kernel, one or more lines.
141 141 'code' : str,
142 142
143 143 # A boolean flag which, if True, signals the kernel to execute this
144 144 # code as quietly as possible. This means that the kernel will compile
145 145 # the code witIPython/core/tests/h 'exec' instead of 'single' (so
146 146 # sys.displayhook will not fire), and will *not*:
147 147 # - broadcast exceptions on the PUB socket
148 148 # - do any logging
149 149 # - populate any history
150 150 #
151 151 # The default is False.
152 152 'silent' : bool,
153 153
154 154 # A list of variable names from the user's namespace to be retrieved. What
155 155 # returns is a JSON string of the variable's repr(), not a python object.
156 156 'user_variables' : list,
157 157
158 158 # Similarly, a dict mapping names to expressions to be evaluated in the
159 159 # user's dict.
160 160 'user_expressions' : dict,
161 161 }
162 162
163 163 The ``code`` field contains a single string (possibly multiline). The kernel
164 164 is responsible for splitting this into one or more independent execution blocks
165 165 and deciding whether to compile these in 'single' or 'exec' mode (see below for
166 166 detailed execution semantics).
167 167
168 168 The ``user_`` fields deserve a detailed explanation. In the past, IPython had
169 169 the notion of a prompt string that allowed arbitrary code to be evaluated, and
170 170 this was put to good use by many in creating prompts that displayed system
171 171 status, path information, and even more esoteric uses like remote instrument
172 172 status aqcuired over the network. But now that IPython has a clean separation
173 173 between the kernel and the clients, the kernel has no prompt knowledge; prompts
174 174 are a frontend-side feature, and it should be even possible for different
175 175 frontends to display different prompts while interacting with the same kernel.
176 176
177 177 The kernel now provides the ability to retrieve data from the user's namespace
178 178 after the execution of the main ``code``, thanks to two fields in the
179 179 ``execute_request`` message:
180 180
181 181 - ``user_variables``: If only variables from the user's namespace are needed, a
182 182 list of variable names can be passed and a dict with these names as keys and
183 183 their :func:`repr()` as values will be returned.
184 184
185 185 - ``user_expressions``: For more complex expressions that require function
186 186 evaluations, a dict can be provided with string keys and arbitrary python
187 187 expressions as values. The return message will contain also a dict with the
188 188 same keys and the :func:`repr()` of the evaluated expressions as value.
189 189
190 190 With this information, frontends can display any status information they wish
191 191 in the form that best suits each frontend (a status line, a popup, inline for a
192 192 terminal, etc).
193 193
194 194 .. Note::
195 195
196 196 In order to obtain the current execution counter for the purposes of
197 197 displaying input prompts, frontends simply make an execution request with an
198 198 empty code string and ``silent=True``.
199 199
200 200 Execution semantics
201 201 ~~~~~~~~~~~~~~~~~~~
202 202
203 203 When the silent flag is false, the execution of use code consists of the
204 204 following phases (in silent mode, only the ``code`` field is executed):
205 205
206 206 1. Run the ``pre_runcode_hook``.
207 207
208 208 2. Execute the ``code`` field, see below for details.
209 209
210 210 3. If #2 succeeds, compute ``user_variables`` and ``user_expressions`` are
211 211 computed. This ensures that any error in the latter don't harm the main
212 212 code execution.
213 213
214 214 4. Call any method registered with :meth:`register_post_execute`.
215 215
216 216 .. warning::
217 217
218 218 The API for running code before/after the main code block is likely to
219 219 change soon. Both the ``pre_runcode_hook`` and the
220 220 :meth:`register_post_execute` are susceptible to modification, as we find a
221 221 consistent model for both.
222 222
223 223 To understand how the ``code`` field is executed, one must know that Python
224 224 code can be compiled in one of three modes (controlled by the ``mode`` argument
225 225 to the :func:`compile` builtin):
226 226
227 227 *single*
228 228 Valid for a single interactive statement (though the source can contain
229 229 multiple lines, such as a for loop). When compiled in this mode, the
230 230 generated bytecode contains special instructions that trigger the calling of
231 231 :func:`sys.displayhook` for any expression in the block that returns a value.
232 232 This means that a single statement can actually produce multiple calls to
233 233 :func:`sys.displayhook`, if for example it contains a loop where each
234 234 iteration computes an unassigned expression would generate 10 calls::
235 235
236 236 for i in range(10):
237 237 i**2
238 238
239 239 *exec*
240 240 An arbitrary amount of source code, this is how modules are compiled.
241 241 :func:`sys.displayhook` is *never* implicitly called.
242 242
243 243 *eval*
244 244 A single expression that returns a value. :func:`sys.displayhook` is *never*
245 245 implicitly called.
246 246
247 247
248 248 The ``code`` field is split into individual blocks each of which is valid for
249 249 execution in 'single' mode, and then:
250 250
251 251 - If there is only a single block: it is executed in 'single' mode.
252 252
253 253 - If there is more than one block:
254 254
255 255 * if the last one is a single line long, run all but the last in 'exec' mode
256 256 and the very last one in 'single' mode. This makes it easy to type simple
257 257 expressions at the end to see computed values.
258 258
259 259 * if the last one is no more than two lines long, run all but the last in
260 260 'exec' mode and the very last one in 'single' mode. This makes it easy to
261 261 type simple expressions at the end to see computed values. - otherwise
262 262 (last one is also multiline), run all in 'exec' mode
263 263
264 264 * otherwise (last one is also multiline), run all in 'exec' mode as a single
265 265 unit.
266 266
267 267 Any error in retrieving the ``user_variables`` or evaluating the
268 268 ``user_expressions`` will result in a simple error message in the return fields
269 269 of the form::
270 270
271 271 [ERROR] ExceptionType: Exception message
272 272
273 273 The user can simply send the same variable name or expression for evaluation to
274 274 see a regular traceback.
275 275
276 276 Errors in any registered post_execute functions are also reported similarly,
277 277 and the failing function is removed from the post_execution set so that it does
278 278 not continue triggering failures.
279 279
280 280 Upon completion of the execution request, the kernel *always* sends a reply,
281 281 with a status code indicating what happened and additional data depending on
282 282 the outcome. See :ref:`below <execution_results>` for the possible return
283 283 codes and associated data.
284 284
285 285
286 286 Execution counter (old prompt number)
287 287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
288 288
289 289 The kernel has a single, monotonically increasing counter of all execution
290 290 requests that are made with ``silent=False``. This counter is used to populate
291 291 the ``In[n]``, ``Out[n]`` and ``_n`` variables, so clients will likely want to
292 292 display it in some form to the user, which will typically (but not necessarily)
293 293 be done in the prompts. The value of this counter will be returned as the
294 294 ``execution_count`` field of all ``execute_reply`` messages.
295 295
296 296 .. _execution_results:
297 297
298 298 Execution results
299 299 ~~~~~~~~~~~~~~~~~
300 300
301 301 Message type: ``execute_reply``::
302 302
303 303 content = {
304 304 # One of: 'ok' OR 'error' OR 'abort'
305 305 'status' : str,
306 306
307 307 # The global kernel counter that increases by one with each non-silent
308 308 # executed request. This will typically be used by clients to display
309 309 # prompt numbers to the user. If the request was a silent one, this will
310 310 # be the current value of the counter in the kernel.
311 311 'execution_count' : int,
312 312 }
313 313
314 314 When status is 'ok', the following extra fields are present::
315 315
316 316 {
317 317 # The execution payload is a dict with string keys that may have been
318 318 # produced by the code being executed. It is retrieved by the kernel at
319 319 # the end of the execution and sent back to the front end, which can take
320 320 # action on it as needed. See main text for further details.
321 321 'payload' : dict,
322 322
323 323 # Results for the user_variables and user_expressions.
324 324 'user_variables' : dict,
325 325 'user_expressions' : dict,
326 326
327 327 # The kernel will often transform the input provided to it. If the
328 328 # '---->' transform had been applied, this is filled, otherwise it's the
329 329 # empty string. So transformations like magics don't appear here, only
330 330 # autocall ones.
331 331 'transformed_code' : str,
332 332 }
333 333
334 334 .. admonition:: Execution payloads
335 335
336 336 The notion of an 'execution payload' is different from a return value of a
337 337 given set of code, which normally is just displayed on the pyout stream
338 338 through the PUB socket. The idea of a payload is to allow special types of
339 339 code, typically magics, to populate a data container in the IPython kernel
340 340 that will be shipped back to the caller via this channel. The kernel will
341 341 have an API for this, probably something along the lines of::
342 342
343 343 ip.exec_payload_add(key, value)
344 344
345 345 though this API is still in the design stages. The data returned in this
346 346 payload will allow frontends to present special views of what just happened.
347 347
348 348
349 349 When status is 'error', the following extra fields are present::
350 350
351 351 {
352 352 'exc_name' : str, # Exception name, as a string
353 353 'exc_value' : str, # Exception value, as a string
354 354
355 355 # The traceback will contain a list of frames, represented each as a
356 356 # string. For now we'll stick to the existing design of ultraTB, which
357 357 # controls exception level of detail statefully. But eventually we'll
358 358 # want to grow into a model where more information is collected and
359 359 # packed into the traceback object, with clients deciding how little or
360 360 # how much of it to unpack. But for now, let's start with a simple list
361 361 # of strings, since that requires only minimal changes to ultratb as
362 362 # written.
363 363 'traceback' : list,
364 364 }
365 365
366 366
367 367 When status is 'abort', there are for now no additional data fields. This
368 368 happens when the kernel was interrupted by a signal.
369 369
370 370 Kernel attribute access
371 371 -----------------------
372 372
373 373 .. warning::
374 374
375 375 This part of the messaging spec is not actually implemented in the kernel
376 376 yet.
377 377
378 378 While this protocol does not specify full RPC access to arbitrary methods of
379 379 the kernel object, the kernel does allow read (and in some cases write) access
380 380 to certain attributes.
381 381
382 382 The policy for which attributes can be read is: any attribute of the kernel, or
383 383 its sub-objects, that belongs to a :class:`Configurable` object and has been
384 384 declared at the class-level with Traits validation, is in principle accessible
385 385 as long as its name does not begin with a leading underscore. The attribute
386 386 itself will have metadata indicating whether it allows remote read and/or write
387 387 access. The message spec follows for attribute read and write requests.
388 388
389 389 Message type: ``getattr_request``::
390 390
391 391 content = {
392 392 # The (possibly dotted) name of the attribute
393 393 'name' : str,
394 394 }
395 395
396 396 When a ``getattr_request`` fails, there are two possible error types:
397 397
398 398 - AttributeError: this type of error was raised when trying to access the
399 399 given name by the kernel itself. This means that the attribute likely
400 400 doesn't exist.
401 401
402 402 - AccessError: the attribute exists but its value is not readable remotely.
403 403
404 404
405 405 Message type: ``getattr_reply``::
406 406
407 407 content = {
408 408 # One of ['ok', 'AttributeError', 'AccessError'].
409 409 'status' : str,
410 410 # If status is 'ok', a JSON object.
411 411 'value' : object,
412 412 }
413 413
414 414 Message type: ``setattr_request``::
415 415
416 416 content = {
417 417 # The (possibly dotted) name of the attribute
418 418 'name' : str,
419 419
420 420 # A JSON-encoded object, that will be validated by the Traits
421 421 # information in the kernel
422 422 'value' : object,
423 423 }
424 424
425 425 When a ``setattr_request`` fails, there are also two possible error types with
426 426 similar meanings as those of the ``getattr_request`` case, but for writing.
427 427
428 428 Message type: ``setattr_reply``::
429 429
430 430 content = {
431 431 # One of ['ok', 'AttributeError', 'AccessError'].
432 432 'status' : str,
433 433 }
434 434
435 435
436 436
437 437 Object information
438 438 ------------------
439 439
440 440 One of IPython's most used capabilities is the introspection of Python objects
441 441 in the user's namespace, typically invoked via the ``?`` and ``??`` characters
442 442 (which in reality are shorthands for the ``%pinfo`` magic). This is used often
443 443 enough that it warrants an explicit message type, especially because frontends
444 444 may want to get object information in response to user keystrokes (like Tab or
445 445 F1) besides from the user explicitly typing code like ``x??``.
446 446
447 447 Message type: ``object_info_request``::
448 448
449 449 content = {
450 450 # The (possibly dotted) name of the object to be searched in all
451 451 # relevant namespaces
452 452 'name' : str,
453 453
454 454 # The level of detail desired. The default (0) is equivalent to typing
455 455 # 'x?' at the prompt, 1 is equivalent to 'x??'.
456 456 'detail_level' : int,
457 457 }
458 458
459 459 The returned information will be a dictionary with keys very similar to the
460 460 field names that IPython prints at the terminal.
461 461
462 462 Message type: ``object_info_reply``::
463 463
464 464 content = {
465 465 # The name the object was requested under
466 466 'name' : str,
467 467
468 468 # Boolean flag indicating whether the named object was found or not. If
469 469 # it's false, all other fields will be empty.
470 470 'found' : bool,
471 471
472 472 # Flags for magics and system aliases
473 473 'ismagic' : bool,
474 474 'isalias' : bool,
475 475
476 476 # The name of the namespace where the object was found ('builtin',
477 477 # 'magics', 'alias', 'interactive', etc.)
478 478 'namespace' : str,
479 479
480 480 # The type name will be type.__name__ for normal Python objects, but it
481 481 # can also be a string like 'Magic function' or 'System alias'
482 482 'type_name' : str,
483 483
484 484 'string_form' : str,
485 485
486 486 # For objects with a __class__ attribute this will be set
487 487 'base_class' : str,
488 488
489 489 # For objects with a __len__ attribute this will be set
490 490 'length' : int,
491 491
492 492 # If the object is a function, class or method whose file we can find,
493 493 # we give its full path
494 494 'file' : str,
495 495
496 496 # For pure Python callable objects, we can reconstruct the object
497 497 # definition line which provides its call signature. For convenience this
498 498 # is returned as a single 'definition' field, but below the raw parts that
499 499 # compose it are also returned as the argspec field.
500 500 'definition' : str,
501 501
502 502 # The individual parts that together form the definition string. Clients
503 503 # with rich display capabilities may use this to provide a richer and more
504 504 # precise representation of the definition line (e.g. by highlighting
505 505 # arguments based on the user's cursor position). For non-callable
506 506 # objects, this field is empty.
507 507 'argspec' : { # The names of all the arguments
508 508 args : list,
509 509 # The name of the varargs (*args), if any
510 510 varargs : str,
511 511 # The name of the varkw (**kw), if any
512 512 varkw : str,
513 513 # The values (as strings) of all default arguments. Note
514 514 # that these must be matched *in reverse* with the 'args'
515 515 # list above, since the first positional args have no default
516 516 # value at all.
517 517 defaults : list,
518 518 },
519 519
520 520 # For instances, provide the constructor signature (the definition of
521 521 # the __init__ method):
522 522 'init_definition' : str,
523 523
524 524 # Docstrings: for any object (function, method, module, package) with a
525 525 # docstring, we show it. But in addition, we may provide additional
526 526 # docstrings. For example, for instances we will show the constructor
527 527 # and class docstrings as well, if available.
528 528 'docstring' : str,
529 529
530 530 # For instances, provide the constructor and class docstrings
531 531 'init_docstring' : str,
532 532 'class_docstring' : str,
533 533
534 534 # If it's a callable object whose call method has a separate docstring and
535 535 # definition line:
536 536 'call_def' : str,
537 537 'call_docstring' : str,
538 538
539 539 # If detail_level was 1, we also try to find the source code that
540 540 # defines the object, if possible. The string 'None' will indicate
541 541 # that no source was found.
542 542 'source' : str,
543 543 }
544 544 '
545 545
546 546 Complete
547 547 --------
548 548
549 549 Message type: ``complete_request``::
550 550
551 551 content = {
552 552 # The text to be completed, such as 'a.is'
553 553 'text' : str,
554 554
555 555 # The full line, such as 'print a.is'. This allows completers to
556 556 # make decisions that may require information about more than just the
557 557 # current word.
558 558 'line' : str,
559 559
560 560 # The entire block of text where the line is. This may be useful in the
561 561 # case of multiline completions where more context may be needed. Note: if
562 562 # in practice this field proves unnecessary, remove it to lighten the
563 563 # messages.
564 564
565 565 'block' : str,
566 566
567 567 # The position of the cursor where the user hit 'TAB' on the line.
568 568 'cursor_pos' : int,
569 569 }
570 570
571 571 Message type: ``complete_reply``::
572 572
573 573 content = {
574 574 # The list of all matches to the completion request, such as
575 575 # ['a.isalnum', 'a.isalpha'] for the above example.
576 576 'matches' : list
577 577 }
578 578
579 579
580 580 History
581 581 -------
582 582
583 583 For clients to explicitly request history from a kernel. The kernel has all
584 584 the actual execution history stored in a single location, so clients can
585 585 request it from the kernel when needed.
586 586
587 587 Message type: ``history_request``::
588 588
589 589 content = {
590 590
591 591 # If True, also return output history in the resulting dict.
592 592 'output' : bool,
593 593
594 594 # If True, return the raw input history, else the transformed input.
595 595 'raw' : bool,
596 596
597 597 # This parameter can be one of: A number, a pair of numbers, None
598 598 # If not given, last 40 are returned.
599 599 # - number n: return the last n entries.
600 600 # - pair n1, n2: return entries in the range(n1, n2).
601 601 # - None: return all history
602 602 'index' : n or (n1, n2) or None,
603 603 }
604 604
605 605 Message type: ``history_reply``::
606 606
607 607 content = {
608 608 # A dict with prompt numbers as keys and either (input, output) or input
609 609 # as the value depending on whether output was True or False,
610 610 # respectively.
611 611 'history' : dict,
612 612 }
613 613
614 614
615 615 Connect
616 616 -------
617 617
618 618 When a client connects to the request/reply socket of the kernel, it can issue
619 619 a connect request to get basic information about the kernel, such as the ports
620 620 the other ZeroMQ sockets are listening on. This allows clients to only have
621 621 to know about a single port (the XREQ/XREP channel) to connect to a kernel.
622 622
623 623 Message type: ``connect_request``::
624 624
625 625 content = {
626 626 }
627 627
628 628 Message type: ``connect_reply``::
629 629
630 630 content = {
631 631 'xrep_port' : int # The port the XREP socket is listening on.
632 632 'pub_port' : int # The port the PUB socket is listening on.
633 633 'req_port' : int # The port the REQ socket is listening on.
634 634 'hb_port' : int # The port the heartbeat socket is listening on.
635 635 }
636 636
637 637
638 638
639 639 Kernel shutdown
640 640 ---------------
641 641
642 642 The clients can request the kernel to shut itself down; this is used in
643 643 multiple cases:
644 644
645 645 - when the user chooses to close the client application via a menu or window
646 646 control.
647 647 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
648 648 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
649 649 IPythonQt client) to force a kernel restart to get a clean kernel without
650 650 losing client-side state like history or inlined figures.
651 651
652 652 The client sends a shutdown request to the kernel, and once it receives the
653 653 reply message (which is otherwise empty), it can assume that the kernel has
654 654 completed shutdown safely.
655 655
656 656 Upon their own shutdown, client applications will typically execute a last
657 657 minute sanity check and forcefully terminate any kernel that is still alive, to
658 658 avoid leaving stray processes in the user's machine.
659 659
660 660 For both shutdown request and reply, there is no actual content that needs to
661 661 be sent, so the content dict is empty.
662 662
663 663 Message type: ``shutdown_request``::
664 664
665 665 content = {
666 666 'restart' : bool # whether the shutdown is final, or precedes a restart
667 667 }
668 668
669 669 Message type: ``shutdown_reply``::
670 670
671 671 content = {
672 672 'restart' : bool # whether the shutdown is final, or precedes a restart
673 673 }
674 674
675 675 .. Note::
676 676
677 677 When the clients detect a dead kernel thanks to inactivity on the heartbeat
678 678 socket, they simply send a forceful process termination signal, since a dead
679 679 process is unlikely to respond in any useful way to messages.
680 680
681 681
682 682 Messages on the PUB/SUB socket
683 683 ==============================
684 684
685 685 Streams (stdout, stderr, etc)
686 686 ------------------------------
687 687
688 688 Message type: ``stream``::
689 689
690 690 content = {
691 691 # The name of the stream is one of 'stdin', 'stdout', 'stderr'
692 692 'name' : str,
693 693
694 694 # The data is an arbitrary string to be written to that stream
695 695 'data' : str,
696 696 }
697 697
698 698 When a kernel receives a raw_input call, it should also broadcast it on the pub
699 699 socket with the names 'stdin' and 'stdin_reply'. This will allow other clients
700 700 to monitor/display kernel interactions and possibly replay them to their user
701 701 or otherwise expose them.
702 702
703 Representation Data
704 -------------------
703 Display Data
704 ------------
705 705
706 This type of message is used to bring back representations (text, html, svg,
707 etc.) of Python objects to the frontend. Each message can have multiple
708 representations of the object; it is up to the frontend to decide which to use
709 and how. A single message should contain the different representations of a
710 single Python object. Each representation should be a JSON'able data structure,
711 and should be a valid MIME type.
706 This type of message is used to bring back data that should be diplayed (text,
707 html, svg, etc.) in the frontends. This data is published to all frontends.
708 Each message can have multiple representations of the data; it is up to the
709 frontend to decide which to use and how. A single message should contain all
710 possible representations of the same information. Each representation should
711 be a JSON'able data structure, and should be a valid MIME type.
712 712
713 713 Some questions remain about this design:
714 714
715 * Do we use this message type for pyout/displayhook?
716 * What is the best way to organize the content dict of the message?
715 * Do we use this message type for pyout/displayhook? Probably not, because
716 the displayhook also has to handle the Out prompt display. On the other hand
717 we could put that information into the metadata secion.
717 718
718 Message type: ``repr_data``::
719 Message type: ``display_data``::
719 720
720 # Option 1: if we only allow a single source.
721 721 content = {
722 722 'source' : str # Who create the data
723 723 'data' : dict # {'mimetype1' : data1, 'mimetype2' : data2}
724 724 'metadata' : dict # Any metadata that describes the data
725 725 }
726 726
727 Other options for ``display_data`` content::
728
727 729 # Option 2: allowing for a different source for each representation,
728 730 but not keyed by anything.
729 731 content = {
730 732 'data' = [(source, type, data), (source, type, data)]
731 733 'metadata' = dict
732 734 }
733 735
734 736 # Option 3: like option 2, but keyed by the MIME types.
735 737 content = {
736 738 'data' = {'mimetype1' : (source, data), 'mimetype2' : (source, data)}
737 739 'metadata' = dict
738 740 }
739 741
740 742 # Option 4: like option 2, but keyed by the source.
741 743 content = {
742 744 'data' = {'source' : (mimetype, data), 'source' : (mimetype, data)}
743 745 'metadata' = dict
744 746 }
745 747
746 748 Python inputs
747 749 -------------
748 750
749 751 These messages are the re-broadcast of the ``execute_request``.
750 752
751 753 Message type: ``pyin``::
752 754
753 755 content = {
754 756 'code' : str # Source code to be executed, one or more lines
755 757 }
756 758
757 759 Python outputs
758 760 --------------
759 761
760 762 When Python produces output from code that has been compiled in with the
761 763 'single' flag to :func:`compile`, any expression that produces a value (such as
762 764 ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with
763 765 this value whatever it wants. The default behavior of ``sys.displayhook`` in
764 766 the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of
765 767 the value as long as it is not ``None`` (which isn't printed at all). In our
766 768 case, the kernel instantiates as ``sys.displayhook`` an object which has
767 769 similar behavior, but which instead of printing to stdout, broadcasts these
768 770 values as ``pyout`` messages for clients to display appropriately.
769 771
770 772 IPython's displayhook can handle multiple simultaneous formats depending on its
771 773 configuration. The default pretty-printed repr text is always given with the
772 774 ``data`` entry in this message. Any other formats are provided in the
773 775 ``extra_formats`` list. Frontends are free to display any or all of these
774 776 according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID
775 777 string, a type string, and the data. The ID is unique to the formatter
776 778 implementation that created the data. Frontends will typically ignore the ID
777 779 unless if it has requested a particular formatter. The type string tells the
778 780 frontend how to interpret the data. It is often, but not always a MIME type.
779 781 Frontends should ignore types that it does not understand. The data itself is
780 782 any JSON object and depends on the format. It is often, but not always a string.
781 783
782 784 Message type: ``pyout``::
783 785
784 786 content = {
785 787 # The data is typically the repr() of the object. It should be displayed
786 788 # as monospaced text.
787 789 'data' : str,
788 790
789 791 # The counter for this execution is also provided so that clients can
790 792 # display it, since IPython automatically creates variables called _N
791 793 # (for prompt N).
792 794 'execution_count' : int,
793 795
794 796 # Any extra formats.
795 797 # The tuples are of the form (ID, type, data).
796 798 'extra_formats' : [
797 799 [str, str, object]
798 800 ]
799 801 }
800 802
801 803 Python errors
802 804 -------------
803 805
804 806 When an error occurs during code execution
805 807
806 808 Message type: ``pyerr``::
807 809
808 810 content = {
809 811 # Similar content to the execute_reply messages for the 'error' case,
810 812 # except the 'status' field is omitted.
811 813 }
812 814
813 815 Kernel status
814 816 -------------
815 817
816 818 This message type is used by frontends to monitor the status of the kernel.
817 819
818 820 Message type: ``status``::
819 821
820 822 content = {
821 823 # When the kernel starts to execute code, it will enter the 'busy'
822 824 # state and when it finishes, it will enter the 'idle' state.
823 825 execution_state : ('busy', 'idle')
824 826 }
825 827
826 828 Kernel crashes
827 829 --------------
828 830
829 831 When the kernel has an unexpected exception, caught by the last-resort
830 832 sys.excepthook, we should broadcast the crash handler's output before exiting.
831 833 This will allow clients to notice that a kernel died, inform the user and
832 834 propose further actions.
833 835
834 836 Message type: ``crash``::
835 837
836 838 content = {
837 839 # Similarly to the 'error' case for execute_reply messages, this will
838 840 # contain exc_name, exc_type and traceback fields.
839 841
840 842 # An additional field with supplementary information such as where to
841 843 # send the crash message
842 844 'info' : str,
843 845 }
844 846
845 847
846 848 Future ideas
847 849 ------------
848 850
849 851 Other potential message types, currently unimplemented, listed below as ideas.
850 852
851 853 Message type: ``file``::
852 854
853 855 content = {
854 856 'path' : 'cool.jpg',
855 857 'mimetype' : str,
856 858 'data' : str,
857 859 }
858 860
859 861
860 862 Messages on the REQ/REP socket
861 863 ==============================
862 864
863 865 This is a socket that goes in the opposite direction: from the kernel to a
864 866 *single* frontend, and its purpose is to allow ``raw_input`` and similar
865 867 operations that read from ``sys.stdin`` on the kernel to be fulfilled by the
866 868 client. For now we will keep these messages as simple as possible, since they
867 869 basically only mean to convey the ``raw_input(prompt)`` call.
868 870
869 871 Message type: ``input_request``::
870 872
871 873 content = { 'prompt' : str }
872 874
873 875 Message type: ``input_reply``::
874 876
875 877 content = { 'value' : str }
876 878
877 879 .. Note::
878 880
879 881 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
880 882 practice the kernel should behave like an interactive program. When a
881 883 program is opened on the console, the keyboard effectively takes over the
882 884 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
883 885 Since the IPython kernel effectively behaves like a console program (albeit
884 886 one whose "keyboard" is actually living in a separate process and
885 887 transported over the zmq connection), raw ``stdin`` isn't expected to be
886 888 available.
887 889
888 890
889 891 Heartbeat for kernels
890 892 =====================
891 893
892 894 Initially we had considered using messages like those above over ZMQ for a
893 895 kernel 'heartbeat' (a way to detect quickly and reliably whether a kernel is
894 896 alive at all, even if it may be busy executing user code). But this has the
895 897 problem that if the kernel is locked inside extension code, it wouldn't execute
896 898 the python heartbeat code. But it turns out that we can implement a basic
897 899 heartbeat with pure ZMQ, without using any Python messaging at all.
898 900
899 901 The monitor sends out a single zmq message (right now, it is a str of the
900 902 monitor's lifetime in seconds), and gets the same message right back, prefixed
901 903 with the zmq identity of the XREQ socket in the heartbeat process. This can be
902 904 a uuid, or even a full message, but there doesn't seem to be a need for packing
903 905 up a message when the sender and receiver are the exact same Python object.
904 906
905 907 The model is this::
906 908
907 909 monitor.send(str(self.lifetime)) # '1.2345678910'
908 910
909 911 and the monitor receives some number of messages of the form::
910 912
911 913 ['uuid-abcd-dead-beef', '1.2345678910']
912 914
913 915 where the first part is the zmq.IDENTITY of the heart's XREQ on the engine, and
914 916 the rest is the message sent by the monitor. No Python code ever has any
915 917 access to the message between the monitor's send, and the monitor's recv.
916 918
917 919
918 920 ToDo
919 921 ====
920 922
921 923 Missing things include:
922 924
923 925 * Important: finish thinking through the payload concept and API.
924 926
925 927 * Important: ensure that we have a good solution for magics like %edit. It's
926 928 likely that with the payload concept we can build a full solution, but not
927 929 100% clear yet.
928 930
929 931 * Finishing the details of the heartbeat protocol.
930 932
931 933 * Signal handling: specify what kind of information kernel should broadcast (or
932 934 not) when it receives signals.
933 935
934 936 .. include:: ../links.rst
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now