##// END OF EJS Templates
Mostly final version of display data....
Brian Granger -
Show More
@@ -1,40 +1,103 b''
1 # -*- coding: utf-8 -*-
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 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2010 The IPython Development Team
10 # Copyright (C) 2008-2010 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 from IPython.config.configurable import Configurable
20 from IPython.config.configurable import Configurable
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Main payload class
23 # Main payload class
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 class DisplayPublisher(Configurable):
26 class DisplayPublisher(Configurable):
27
27
28 def _validate_data(self, source, data, metadata=None):
28 def _validate_data(self, source, data, metadata=None):
29 if not isinstance(source, str):
29 if not isinstance(source, str):
30 raise TypeError('source must be a str, got: %r' % source)
30 raise TypeError('source must be a str, got: %r' % source)
31 if not isinstance(data, dict):
31 if not isinstance(data, dict):
32 raise TypeError('data must be a dict, got: %r' % data)
32 raise TypeError('data must be a dict, got: %r' % data)
33 if metadata is not None:
33 if metadata is not None:
34 if not isinstance(metadata, dict):
34 if not isinstance(metadata, dict):
35 raise TypeError('metadata must be a dict, got: %r' % data)
35 raise TypeError('metadata must be a dict, got: %r' % data)
36
36
37 def publish(self, source, data, metadata=None):
37 def publish(self, source, data, metadata=None):
38 """Publish data and metadata to all frontends."""
38 """Publish data and metadata to all frontends.
39 pass
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 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import atexit
23 import atexit
24 import codeop
24 import codeop
25 import os
25 import os
26 import re
26 import re
27 import sys
27 import sys
28 import tempfile
28 import tempfile
29 import types
29 import types
30 from contextlib import nested
30 from contextlib import nested
31
31
32 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
33 from IPython.core import debugger, oinspect
33 from IPython.core import debugger, oinspect
34 from IPython.core import history as ipcorehist
34 from IPython.core import history as ipcorehist
35 from IPython.core import page
35 from IPython.core import page
36 from IPython.core import prefilter
36 from IPython.core import prefilter
37 from IPython.core import shadowns
37 from IPython.core import shadowns
38 from IPython.core import ultratb
38 from IPython.core import ultratb
39 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.compilerop import CachingCompiler
41 from IPython.core.compilerop import CachingCompiler
42 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.displayhook import DisplayHook
43 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displaypub import DisplayPublisher
44 from IPython.core.error import TryNext, UsageError
45 from IPython.core.error import TryNext, UsageError
45 from IPython.core.extensions import ExtensionManager
46 from IPython.core.extensions import ExtensionManager
46 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 from IPython.core.history import HistoryManager
48 from IPython.core.history import HistoryManager
48 from IPython.core.inputsplitter import IPythonInputSplitter
49 from IPython.core.inputsplitter import IPythonInputSplitter
49 from IPython.core.logger import Logger
50 from IPython.core.logger import Logger
50 from IPython.core.magic import Magic
51 from IPython.core.magic import Magic
51 from IPython.core.payload import PayloadManager
52 from IPython.core.payload import PayloadManager
52 from IPython.core.plugin import PluginManager
53 from IPython.core.plugin import PluginManager
53 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 from IPython.external.Itpl import ItplNS
55 from IPython.external.Itpl import ItplNS
55 from IPython.utils import PyColorize
56 from IPython.utils import PyColorize
56 from IPython.utils import io
57 from IPython.utils import io
57 from IPython.utils import pickleshare
58 from IPython.utils import pickleshare
58 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.ipstruct import Struct
61 from IPython.utils.ipstruct import Struct
61 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.process import system, getoutput
63 from IPython.utils.process import system, getoutput
63 from IPython.utils.strdispatch import StrDispatch
64 from IPython.utils.strdispatch import StrDispatch
64 from IPython.utils.syspathcontext import prepended_to_syspath
65 from IPython.utils.syspathcontext import prepended_to_syspath
65 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
66 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 List, Unicode, Instance, Type)
68 List, Unicode, Instance, Type)
68 from IPython.utils.warn import warn, error, fatal
69 from IPython.utils.warn import warn, error, fatal
69 import IPython.core.hooks
70 import IPython.core.hooks
70
71
71 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
72 # Globals
73 # Globals
73 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
74
75
75 # compiled regexps for autoindent management
76 # compiled regexps for autoindent management
76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77
78
78 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
79 # Utilities
80 # Utilities
80 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
81
82
82 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
83 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
84 raw_input_original = raw_input
85 raw_input_original = raw_input
85
86
86 def softspace(file, newvalue):
87 def softspace(file, newvalue):
87 """Copied from code.py, to remove the dependency"""
88 """Copied from code.py, to remove the dependency"""
88
89
89 oldvalue = 0
90 oldvalue = 0
90 try:
91 try:
91 oldvalue = file.softspace
92 oldvalue = file.softspace
92 except AttributeError:
93 except AttributeError:
93 pass
94 pass
94 try:
95 try:
95 file.softspace = newvalue
96 file.softspace = newvalue
96 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
97 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
98 pass
99 pass
99 return oldvalue
100 return oldvalue
100
101
101
102
102 def no_op(*a, **kw): pass
103 def no_op(*a, **kw): pass
103
104
104 class SpaceInInput(Exception): pass
105 class SpaceInInput(Exception): pass
105
106
106 class Bunch: pass
107 class Bunch: pass
107
108
108
109
109 def get_default_colors():
110 def get_default_colors():
110 if sys.platform=='darwin':
111 if sys.platform=='darwin':
111 return "LightBG"
112 return "LightBG"
112 elif os.name=='nt':
113 elif os.name=='nt':
113 return 'Linux'
114 return 'Linux'
114 else:
115 else:
115 return 'Linux'
116 return 'Linux'
116
117
117
118
118 class SeparateStr(Str):
119 class SeparateStr(Str):
119 """A Str subclass to validate separate_in, separate_out, etc.
120 """A Str subclass to validate separate_in, separate_out, etc.
120
121
121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 """
123 """
123
124
124 def validate(self, obj, value):
125 def validate(self, obj, value):
125 if value == '0': value = ''
126 if value == '0': value = ''
126 value = value.replace('\\n','\n')
127 value = value.replace('\\n','\n')
127 return super(SeparateStr, self).validate(obj, value)
128 return super(SeparateStr, self).validate(obj, value)
128
129
129 class MultipleInstanceError(Exception):
130 class MultipleInstanceError(Exception):
130 pass
131 pass
131
132
132
133
133 #-----------------------------------------------------------------------------
134 #-----------------------------------------------------------------------------
134 # Main IPython class
135 # Main IPython class
135 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
136
137
137 class InteractiveShell(Configurable, Magic):
138 class InteractiveShell(Configurable, Magic):
138 """An enhanced, interactive shell for Python."""
139 """An enhanced, interactive shell for Python."""
139
140
140 _instance = None
141 _instance = None
141 autocall = Enum((0,1,2), default_value=1, config=True)
142 autocall = Enum((0,1,2), default_value=1, config=True)
142 # TODO: remove all autoindent logic and put into frontends.
143 # TODO: remove all autoindent logic and put into frontends.
143 # We can't do this yet because even runlines uses the autoindent.
144 # We can't do this yet because even runlines uses the autoindent.
144 autoindent = CBool(True, config=True)
145 autoindent = CBool(True, config=True)
145 automagic = CBool(True, config=True)
146 automagic = CBool(True, config=True)
146 cache_size = Int(1000, config=True)
147 cache_size = Int(1000, config=True)
147 color_info = CBool(True, config=True)
148 color_info = CBool(True, config=True)
148 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
149 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
149 default_value=get_default_colors(), config=True)
150 default_value=get_default_colors(), config=True)
150 debug = CBool(False, config=True)
151 debug = CBool(False, config=True)
151 deep_reload = CBool(False, config=True)
152 deep_reload = CBool(False, config=True)
152 displayhook_class = Type(DisplayHook)
153 displayhook_class = Type(DisplayHook)
154 display_pub_class = Type(DisplayPublisher)
155
153 exit_now = CBool(False)
156 exit_now = CBool(False)
154 # Monotonically increasing execution counter
157 # Monotonically increasing execution counter
155 execution_count = Int(1)
158 execution_count = Int(1)
156 filename = Str("<ipython console>")
159 filename = Str("<ipython console>")
157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
160 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158
161
159 # Input splitter, to split entire cells of input into either individual
162 # Input splitter, to split entire cells of input into either individual
160 # interactive statements or whole blocks.
163 # interactive statements or whole blocks.
161 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
164 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 (), {})
165 (), {})
163 logstart = CBool(False, config=True)
166 logstart = CBool(False, config=True)
164 logfile = Str('', config=True)
167 logfile = Str('', config=True)
165 logappend = Str('', config=True)
168 logappend = Str('', config=True)
166 object_info_string_level = Enum((0,1,2), default_value=0,
169 object_info_string_level = Enum((0,1,2), default_value=0,
167 config=True)
170 config=True)
168 pdb = CBool(False, config=True)
171 pdb = CBool(False, config=True)
169
172
170 pprint = CBool(True, config=True)
173 pprint = CBool(True, config=True)
171 profile = Str('', config=True)
174 profile = Str('', config=True)
172 prompt_in1 = Str('In [\\#]: ', config=True)
175 prompt_in1 = Str('In [\\#]: ', config=True)
173 prompt_in2 = Str(' .\\D.: ', config=True)
176 prompt_in2 = Str(' .\\D.: ', config=True)
174 prompt_out = Str('Out[\\#]: ', config=True)
177 prompt_out = Str('Out[\\#]: ', config=True)
175 prompts_pad_left = CBool(True, config=True)
178 prompts_pad_left = CBool(True, config=True)
176 quiet = CBool(False, config=True)
179 quiet = CBool(False, config=True)
177
180
178 history_length = Int(10000, config=True)
181 history_length = Int(10000, config=True)
179
182
180 # The readline stuff will eventually be moved to the terminal subclass
183 # The readline stuff will eventually be moved to the terminal subclass
181 # but for now, we can't do that as readline is welded in everywhere.
184 # but for now, we can't do that as readline is welded in everywhere.
182 readline_use = CBool(True, config=True)
185 readline_use = CBool(True, config=True)
183 readline_merge_completions = CBool(True, config=True)
186 readline_merge_completions = CBool(True, config=True)
184 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
187 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
185 readline_remove_delims = Str('-/~', config=True)
188 readline_remove_delims = Str('-/~', config=True)
186 readline_parse_and_bind = List([
189 readline_parse_and_bind = List([
187 'tab: complete',
190 'tab: complete',
188 '"\C-l": clear-screen',
191 '"\C-l": clear-screen',
189 'set show-all-if-ambiguous on',
192 'set show-all-if-ambiguous on',
190 '"\C-o": tab-insert',
193 '"\C-o": tab-insert',
191 '"\M-i": " "',
194 '"\M-i": " "',
192 '"\M-o": "\d\d\d\d"',
195 '"\M-o": "\d\d\d\d"',
193 '"\M-I": "\d\d\d\d"',
196 '"\M-I": "\d\d\d\d"',
194 '"\C-r": reverse-search-history',
197 '"\C-r": reverse-search-history',
195 '"\C-s": forward-search-history',
198 '"\C-s": forward-search-history',
196 '"\C-p": history-search-backward',
199 '"\C-p": history-search-backward',
197 '"\C-n": history-search-forward',
200 '"\C-n": history-search-forward',
198 '"\e[A": history-search-backward',
201 '"\e[A": history-search-backward',
199 '"\e[B": history-search-forward',
202 '"\e[B": history-search-forward',
200 '"\C-k": kill-line',
203 '"\C-k": kill-line',
201 '"\C-u": unix-line-discard',
204 '"\C-u": unix-line-discard',
202 ], allow_none=False, config=True)
205 ], allow_none=False, config=True)
203
206
204 # TODO: this part of prompt management should be moved to the frontends.
207 # TODO: this part of prompt management should be moved to the frontends.
205 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
208 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
206 separate_in = SeparateStr('\n', config=True)
209 separate_in = SeparateStr('\n', config=True)
207 separate_out = SeparateStr('', config=True)
210 separate_out = SeparateStr('', config=True)
208 separate_out2 = SeparateStr('', config=True)
211 separate_out2 = SeparateStr('', config=True)
209 wildcards_case_sensitive = CBool(True, config=True)
212 wildcards_case_sensitive = CBool(True, config=True)
210 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
213 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
211 default_value='Context', config=True)
214 default_value='Context', config=True)
212
215
213 # Subcomponents of InteractiveShell
216 # Subcomponents of InteractiveShell
214 alias_manager = Instance('IPython.core.alias.AliasManager')
217 alias_manager = Instance('IPython.core.alias.AliasManager')
215 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
218 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
216 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
219 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
217 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
220 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
218 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
221 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
219 plugin_manager = Instance('IPython.core.plugin.PluginManager')
222 plugin_manager = Instance('IPython.core.plugin.PluginManager')
220 payload_manager = Instance('IPython.core.payload.PayloadManager')
223 payload_manager = Instance('IPython.core.payload.PayloadManager')
221 history_manager = Instance('IPython.core.history.HistoryManager')
224 history_manager = Instance('IPython.core.history.HistoryManager')
222
225
223 # Private interface
226 # Private interface
224 _post_execute = set()
227 _post_execute = set()
225
228
226 def __init__(self, config=None, ipython_dir=None,
229 def __init__(self, config=None, ipython_dir=None,
227 user_ns=None, user_global_ns=None,
230 user_ns=None, user_global_ns=None,
228 custom_exceptions=((), None)):
231 custom_exceptions=((), None)):
229
232
230 # This is where traits with a config_key argument are updated
233 # This is where traits with a config_key argument are updated
231 # from the values on config.
234 # from the values on config.
232 super(InteractiveShell, self).__init__(config=config)
235 super(InteractiveShell, self).__init__(config=config)
233
236
234 # These are relatively independent and stateless
237 # These are relatively independent and stateless
235 self.init_ipython_dir(ipython_dir)
238 self.init_ipython_dir(ipython_dir)
236 self.init_instance_attrs()
239 self.init_instance_attrs()
237 self.init_environment()
240 self.init_environment()
238
241
239 # Create namespaces (user_ns, user_global_ns, etc.)
242 # Create namespaces (user_ns, user_global_ns, etc.)
240 self.init_create_namespaces(user_ns, user_global_ns)
243 self.init_create_namespaces(user_ns, user_global_ns)
241 # This has to be done after init_create_namespaces because it uses
244 # This has to be done after init_create_namespaces because it uses
242 # something in self.user_ns, but before init_sys_modules, which
245 # something in self.user_ns, but before init_sys_modules, which
243 # is the first thing to modify sys.
246 # is the first thing to modify sys.
244 # TODO: When we override sys.stdout and sys.stderr before this class
247 # TODO: When we override sys.stdout and sys.stderr before this class
245 # is created, we are saving the overridden ones here. Not sure if this
248 # is created, we are saving the overridden ones here. Not sure if this
246 # is what we want to do.
249 # is what we want to do.
247 self.save_sys_module_state()
250 self.save_sys_module_state()
248 self.init_sys_modules()
251 self.init_sys_modules()
249
252
250 self.init_history()
253 self.init_history()
251 self.init_encoding()
254 self.init_encoding()
252 self.init_prefilter()
255 self.init_prefilter()
253
256
254 Magic.__init__(self, self)
257 Magic.__init__(self, self)
255
258
256 self.init_syntax_highlighting()
259 self.init_syntax_highlighting()
257 self.init_hooks()
260 self.init_hooks()
258 self.init_pushd_popd_magic()
261 self.init_pushd_popd_magic()
259 # self.init_traceback_handlers use to be here, but we moved it below
262 # self.init_traceback_handlers use to be here, but we moved it below
260 # because it and init_io have to come after init_readline.
263 # because it and init_io have to come after init_readline.
261 self.init_user_ns()
264 self.init_user_ns()
262 self.init_logger()
265 self.init_logger()
263 self.init_alias()
266 self.init_alias()
264 self.init_builtins()
267 self.init_builtins()
265
268
266 # pre_config_initialization
269 # pre_config_initialization
267
270
268 # The next section should contain everything that was in ipmaker.
271 # The next section should contain everything that was in ipmaker.
269 self.init_logstart()
272 self.init_logstart()
270
273
271 # The following was in post_config_initialization
274 # The following was in post_config_initialization
272 self.init_inspector()
275 self.init_inspector()
273 # init_readline() must come before init_io(), because init_io uses
276 # init_readline() must come before init_io(), because init_io uses
274 # readline related things.
277 # readline related things.
275 self.init_readline()
278 self.init_readline()
276 # init_completer must come after init_readline, because it needs to
279 # init_completer must come after init_readline, because it needs to
277 # know whether readline is present or not system-wide to configure the
280 # know whether readline is present or not system-wide to configure the
278 # completers, since the completion machinery can now operate
281 # completers, since the completion machinery can now operate
279 # independently of readline (e.g. over the network)
282 # independently of readline (e.g. over the network)
280 self.init_completer()
283 self.init_completer()
281 # TODO: init_io() needs to happen before init_traceback handlers
284 # TODO: init_io() needs to happen before init_traceback handlers
282 # because the traceback handlers hardcode the stdout/stderr streams.
285 # because the traceback handlers hardcode the stdout/stderr streams.
283 # This logic in in debugger.Pdb and should eventually be changed.
286 # This logic in in debugger.Pdb and should eventually be changed.
284 self.init_io()
287 self.init_io()
285 self.init_traceback_handlers(custom_exceptions)
288 self.init_traceback_handlers(custom_exceptions)
286 self.init_prompts()
289 self.init_prompts()
290 self.init_display_pub()
287 self.init_displayhook()
291 self.init_displayhook()
288 self.init_reload_doctest()
292 self.init_reload_doctest()
289 self.init_magics()
293 self.init_magics()
290 self.init_pdb()
294 self.init_pdb()
291 self.init_extension_manager()
295 self.init_extension_manager()
292 self.init_plugin_manager()
296 self.init_plugin_manager()
293 self.init_payload()
297 self.init_payload()
294 self.hooks.late_startup_hook()
298 self.hooks.late_startup_hook()
295 atexit.register(self.atexit_operations)
299 atexit.register(self.atexit_operations)
296
300
297 # While we're trying to have each part of the code directly access what it
301 # While we're trying to have each part of the code directly access what it
298 # needs without keeping redundant references to objects, we have too much
302 # needs without keeping redundant references to objects, we have too much
299 # legacy code that expects ip.db to exist, so let's make it a property that
303 # legacy code that expects ip.db to exist, so let's make it a property that
300 # retrieves the underlying object from our new history manager.
304 # retrieves the underlying object from our new history manager.
301 @property
305 @property
302 def db(self):
306 def db(self):
303 return self.history_manager.shadow_db
307 return self.history_manager.shadow_db
304
308
305 @classmethod
309 @classmethod
306 def instance(cls, *args, **kwargs):
310 def instance(cls, *args, **kwargs):
307 """Returns a global InteractiveShell instance."""
311 """Returns a global InteractiveShell instance."""
308 if cls._instance is None:
312 if cls._instance is None:
309 inst = cls(*args, **kwargs)
313 inst = cls(*args, **kwargs)
310 # Now make sure that the instance will also be returned by
314 # Now make sure that the instance will also be returned by
311 # the subclasses instance attribute.
315 # the subclasses instance attribute.
312 for subclass in cls.mro():
316 for subclass in cls.mro():
313 if issubclass(cls, subclass) and \
317 if issubclass(cls, subclass) and \
314 issubclass(subclass, InteractiveShell):
318 issubclass(subclass, InteractiveShell):
315 subclass._instance = inst
319 subclass._instance = inst
316 else:
320 else:
317 break
321 break
318 if isinstance(cls._instance, cls):
322 if isinstance(cls._instance, cls):
319 return cls._instance
323 return cls._instance
320 else:
324 else:
321 raise MultipleInstanceError(
325 raise MultipleInstanceError(
322 'Multiple incompatible subclass instances of '
326 'Multiple incompatible subclass instances of '
323 'InteractiveShell are being created.'
327 'InteractiveShell are being created.'
324 )
328 )
325
329
326 @classmethod
330 @classmethod
327 def initialized(cls):
331 def initialized(cls):
328 return hasattr(cls, "_instance")
332 return hasattr(cls, "_instance")
329
333
330 def get_ipython(self):
334 def get_ipython(self):
331 """Return the currently running IPython instance."""
335 """Return the currently running IPython instance."""
332 return self
336 return self
333
337
334 #-------------------------------------------------------------------------
338 #-------------------------------------------------------------------------
335 # Trait changed handlers
339 # Trait changed handlers
336 #-------------------------------------------------------------------------
340 #-------------------------------------------------------------------------
337
341
338 def _ipython_dir_changed(self, name, new):
342 def _ipython_dir_changed(self, name, new):
339 if not os.path.isdir(new):
343 if not os.path.isdir(new):
340 os.makedirs(new, mode = 0777)
344 os.makedirs(new, mode = 0777)
341
345
342 def set_autoindent(self,value=None):
346 def set_autoindent(self,value=None):
343 """Set the autoindent flag, checking for readline support.
347 """Set the autoindent flag, checking for readline support.
344
348
345 If called with no arguments, it acts as a toggle."""
349 If called with no arguments, it acts as a toggle."""
346
350
347 if not self.has_readline:
351 if not self.has_readline:
348 if os.name == 'posix':
352 if os.name == 'posix':
349 warn("The auto-indent feature requires the readline library")
353 warn("The auto-indent feature requires the readline library")
350 self.autoindent = 0
354 self.autoindent = 0
351 return
355 return
352 if value is None:
356 if value is None:
353 self.autoindent = not self.autoindent
357 self.autoindent = not self.autoindent
354 else:
358 else:
355 self.autoindent = value
359 self.autoindent = value
356
360
357 #-------------------------------------------------------------------------
361 #-------------------------------------------------------------------------
358 # init_* methods called by __init__
362 # init_* methods called by __init__
359 #-------------------------------------------------------------------------
363 #-------------------------------------------------------------------------
360
364
361 def init_ipython_dir(self, ipython_dir):
365 def init_ipython_dir(self, ipython_dir):
362 if ipython_dir is not None:
366 if ipython_dir is not None:
363 self.ipython_dir = ipython_dir
367 self.ipython_dir = ipython_dir
364 self.config.Global.ipython_dir = self.ipython_dir
368 self.config.Global.ipython_dir = self.ipython_dir
365 return
369 return
366
370
367 if hasattr(self.config.Global, 'ipython_dir'):
371 if hasattr(self.config.Global, 'ipython_dir'):
368 self.ipython_dir = self.config.Global.ipython_dir
372 self.ipython_dir = self.config.Global.ipython_dir
369 else:
373 else:
370 self.ipython_dir = get_ipython_dir()
374 self.ipython_dir = get_ipython_dir()
371
375
372 # All children can just read this
376 # All children can just read this
373 self.config.Global.ipython_dir = self.ipython_dir
377 self.config.Global.ipython_dir = self.ipython_dir
374
378
375 def init_instance_attrs(self):
379 def init_instance_attrs(self):
376 self.more = False
380 self.more = False
377
381
378 # command compiler
382 # command compiler
379 self.compile = CachingCompiler()
383 self.compile = CachingCompiler()
380
384
381 # User input buffers
385 # User input buffers
382 # NOTE: these variables are slated for full removal, once we are 100%
386 # NOTE: these variables are slated for full removal, once we are 100%
383 # sure that the new execution logic is solid. We will delte runlines,
387 # sure that the new execution logic is solid. We will delte runlines,
384 # push_line and these buffers, as all input will be managed by the
388 # push_line and these buffers, as all input will be managed by the
385 # frontends via an inputsplitter instance.
389 # frontends via an inputsplitter instance.
386 self.buffer = []
390 self.buffer = []
387 self.buffer_raw = []
391 self.buffer_raw = []
388
392
389 # Make an empty namespace, which extension writers can rely on both
393 # Make an empty namespace, which extension writers can rely on both
390 # existing and NEVER being used by ipython itself. This gives them a
394 # existing and NEVER being used by ipython itself. This gives them a
391 # convenient location for storing additional information and state
395 # convenient location for storing additional information and state
392 # their extensions may require, without fear of collisions with other
396 # their extensions may require, without fear of collisions with other
393 # ipython names that may develop later.
397 # ipython names that may develop later.
394 self.meta = Struct()
398 self.meta = Struct()
395
399
396 # Object variable to store code object waiting execution. This is
400 # Object variable to store code object waiting execution. This is
397 # used mainly by the multithreaded shells, but it can come in handy in
401 # used mainly by the multithreaded shells, but it can come in handy in
398 # other situations. No need to use a Queue here, since it's a single
402 # other situations. No need to use a Queue here, since it's a single
399 # item which gets cleared once run.
403 # item which gets cleared once run.
400 self.code_to_run = None
404 self.code_to_run = None
401
405
402 # Temporary files used for various purposes. Deleted at exit.
406 # Temporary files used for various purposes. Deleted at exit.
403 self.tempfiles = []
407 self.tempfiles = []
404
408
405 # Keep track of readline usage (later set by init_readline)
409 # Keep track of readline usage (later set by init_readline)
406 self.has_readline = False
410 self.has_readline = False
407
411
408 # keep track of where we started running (mainly for crash post-mortem)
412 # keep track of where we started running (mainly for crash post-mortem)
409 # This is not being used anywhere currently.
413 # This is not being used anywhere currently.
410 self.starting_dir = os.getcwd()
414 self.starting_dir = os.getcwd()
411
415
412 # Indentation management
416 # Indentation management
413 self.indent_current_nsp = 0
417 self.indent_current_nsp = 0
414
418
415 def init_environment(self):
419 def init_environment(self):
416 """Any changes we need to make to the user's environment."""
420 """Any changes we need to make to the user's environment."""
417 pass
421 pass
418
422
419 def init_encoding(self):
423 def init_encoding(self):
420 # Get system encoding at startup time. Certain terminals (like Emacs
424 # Get system encoding at startup time. Certain terminals (like Emacs
421 # under Win32 have it set to None, and we need to have a known valid
425 # under Win32 have it set to None, and we need to have a known valid
422 # encoding to use in the raw_input() method
426 # encoding to use in the raw_input() method
423 try:
427 try:
424 self.stdin_encoding = sys.stdin.encoding or 'ascii'
428 self.stdin_encoding = sys.stdin.encoding or 'ascii'
425 except AttributeError:
429 except AttributeError:
426 self.stdin_encoding = 'ascii'
430 self.stdin_encoding = 'ascii'
427
431
428 def init_syntax_highlighting(self):
432 def init_syntax_highlighting(self):
429 # Python source parser/formatter for syntax highlighting
433 # Python source parser/formatter for syntax highlighting
430 pyformat = PyColorize.Parser().format
434 pyformat = PyColorize.Parser().format
431 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
435 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
432
436
433 def init_pushd_popd_magic(self):
437 def init_pushd_popd_magic(self):
434 # for pushd/popd management
438 # for pushd/popd management
435 try:
439 try:
436 self.home_dir = get_home_dir()
440 self.home_dir = get_home_dir()
437 except HomeDirError, msg:
441 except HomeDirError, msg:
438 fatal(msg)
442 fatal(msg)
439
443
440 self.dir_stack = []
444 self.dir_stack = []
441
445
442 def init_logger(self):
446 def init_logger(self):
443 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
447 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
444 logmode='rotate')
448 logmode='rotate')
445
449
446 def init_logstart(self):
450 def init_logstart(self):
447 """Initialize logging in case it was requested at the command line.
451 """Initialize logging in case it was requested at the command line.
448 """
452 """
449 if self.logappend:
453 if self.logappend:
450 self.magic_logstart(self.logappend + ' append')
454 self.magic_logstart(self.logappend + ' append')
451 elif self.logfile:
455 elif self.logfile:
452 self.magic_logstart(self.logfile)
456 self.magic_logstart(self.logfile)
453 elif self.logstart:
457 elif self.logstart:
454 self.magic_logstart()
458 self.magic_logstart()
455
459
456 def init_builtins(self):
460 def init_builtins(self):
457 self.builtin_trap = BuiltinTrap(shell=self)
461 self.builtin_trap = BuiltinTrap(shell=self)
458
462
459 def init_inspector(self):
463 def init_inspector(self):
460 # Object inspector
464 # Object inspector
461 self.inspector = oinspect.Inspector(oinspect.InspectColors,
465 self.inspector = oinspect.Inspector(oinspect.InspectColors,
462 PyColorize.ANSICodeColors,
466 PyColorize.ANSICodeColors,
463 'NoColor',
467 'NoColor',
464 self.object_info_string_level)
468 self.object_info_string_level)
465
469
466 def init_io(self):
470 def init_io(self):
467 # This will just use sys.stdout and sys.stderr. If you want to
471 # This will just use sys.stdout and sys.stderr. If you want to
468 # override sys.stdout and sys.stderr themselves, you need to do that
472 # override sys.stdout and sys.stderr themselves, you need to do that
469 # *before* instantiating this class, because Term holds onto
473 # *before* instantiating this class, because Term holds onto
470 # references to the underlying streams.
474 # references to the underlying streams.
471 if sys.platform == 'win32' and self.has_readline:
475 if sys.platform == 'win32' and self.has_readline:
472 Term = io.IOTerm(cout=self.readline._outputfile,
476 Term = io.IOTerm(cout=self.readline._outputfile,
473 cerr=self.readline._outputfile)
477 cerr=self.readline._outputfile)
474 else:
478 else:
475 Term = io.IOTerm()
479 Term = io.IOTerm()
476 io.Term = Term
480 io.Term = Term
477
481
478 def init_prompts(self):
482 def init_prompts(self):
479 # TODO: This is a pass for now because the prompts are managed inside
483 # TODO: This is a pass for now because the prompts are managed inside
480 # the DisplayHook. Once there is a separate prompt manager, this
484 # the DisplayHook. Once there is a separate prompt manager, this
481 # will initialize that object and all prompt related information.
485 # will initialize that object and all prompt related information.
482 pass
486 pass
483
487
488 def init_display_pub(self):
489 self.display_pub = self.display_pub_class(config=self.config)
490
484 def init_displayhook(self):
491 def init_displayhook(self):
485 # Initialize displayhook, set in/out prompts and printing system
492 # Initialize displayhook, set in/out prompts and printing system
486 self.displayhook = self.displayhook_class(
493 self.displayhook = self.displayhook_class(
487 config=self.config,
494 config=self.config,
488 shell=self,
495 shell=self,
489 cache_size=self.cache_size,
496 cache_size=self.cache_size,
490 input_sep = self.separate_in,
497 input_sep = self.separate_in,
491 output_sep = self.separate_out,
498 output_sep = self.separate_out,
492 output_sep2 = self.separate_out2,
499 output_sep2 = self.separate_out2,
493 ps1 = self.prompt_in1,
500 ps1 = self.prompt_in1,
494 ps2 = self.prompt_in2,
501 ps2 = self.prompt_in2,
495 ps_out = self.prompt_out,
502 ps_out = self.prompt_out,
496 pad_left = self.prompts_pad_left
503 pad_left = self.prompts_pad_left
497 )
504 )
498 # This is a context manager that installs/revmoes the displayhook at
505 # This is a context manager that installs/revmoes the displayhook at
499 # the appropriate time.
506 # the appropriate time.
500 self.display_trap = DisplayTrap(hook=self.displayhook)
507 self.display_trap = DisplayTrap(hook=self.displayhook)
501
508
502 def init_reload_doctest(self):
509 def init_reload_doctest(self):
503 # Do a proper resetting of doctest, including the necessary displayhook
510 # Do a proper resetting of doctest, including the necessary displayhook
504 # monkeypatching
511 # monkeypatching
505 try:
512 try:
506 doctest_reload()
513 doctest_reload()
507 except ImportError:
514 except ImportError:
508 warn("doctest module does not exist.")
515 warn("doctest module does not exist.")
509
516
510 #-------------------------------------------------------------------------
517 #-------------------------------------------------------------------------
511 # Things related to injections into the sys module
518 # Things related to injections into the sys module
512 #-------------------------------------------------------------------------
519 #-------------------------------------------------------------------------
513
520
514 def save_sys_module_state(self):
521 def save_sys_module_state(self):
515 """Save the state of hooks in the sys module.
522 """Save the state of hooks in the sys module.
516
523
517 This has to be called after self.user_ns is created.
524 This has to be called after self.user_ns is created.
518 """
525 """
519 self._orig_sys_module_state = {}
526 self._orig_sys_module_state = {}
520 self._orig_sys_module_state['stdin'] = sys.stdin
527 self._orig_sys_module_state['stdin'] = sys.stdin
521 self._orig_sys_module_state['stdout'] = sys.stdout
528 self._orig_sys_module_state['stdout'] = sys.stdout
522 self._orig_sys_module_state['stderr'] = sys.stderr
529 self._orig_sys_module_state['stderr'] = sys.stderr
523 self._orig_sys_module_state['excepthook'] = sys.excepthook
530 self._orig_sys_module_state['excepthook'] = sys.excepthook
524 try:
531 try:
525 self._orig_sys_modules_main_name = self.user_ns['__name__']
532 self._orig_sys_modules_main_name = self.user_ns['__name__']
526 except KeyError:
533 except KeyError:
527 pass
534 pass
528
535
529 def restore_sys_module_state(self):
536 def restore_sys_module_state(self):
530 """Restore the state of the sys module."""
537 """Restore the state of the sys module."""
531 try:
538 try:
532 for k, v in self._orig_sys_module_state.iteritems():
539 for k, v in self._orig_sys_module_state.iteritems():
533 setattr(sys, k, v)
540 setattr(sys, k, v)
534 except AttributeError:
541 except AttributeError:
535 pass
542 pass
536 # Reset what what done in self.init_sys_modules
543 # Reset what what done in self.init_sys_modules
537 try:
544 try:
538 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
545 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
539 except (AttributeError, KeyError):
546 except (AttributeError, KeyError):
540 pass
547 pass
541
548
542 #-------------------------------------------------------------------------
549 #-------------------------------------------------------------------------
543 # Things related to hooks
550 # Things related to hooks
544 #-------------------------------------------------------------------------
551 #-------------------------------------------------------------------------
545
552
546 def init_hooks(self):
553 def init_hooks(self):
547 # hooks holds pointers used for user-side customizations
554 # hooks holds pointers used for user-side customizations
548 self.hooks = Struct()
555 self.hooks = Struct()
549
556
550 self.strdispatchers = {}
557 self.strdispatchers = {}
551
558
552 # Set all default hooks, defined in the IPython.hooks module.
559 # Set all default hooks, defined in the IPython.hooks module.
553 hooks = IPython.core.hooks
560 hooks = IPython.core.hooks
554 for hook_name in hooks.__all__:
561 for hook_name in hooks.__all__:
555 # default hooks have priority 100, i.e. low; user hooks should have
562 # default hooks have priority 100, i.e. low; user hooks should have
556 # 0-100 priority
563 # 0-100 priority
557 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
564 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
558
565
559 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
566 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
560 """set_hook(name,hook) -> sets an internal IPython hook.
567 """set_hook(name,hook) -> sets an internal IPython hook.
561
568
562 IPython exposes some of its internal API as user-modifiable hooks. By
569 IPython exposes some of its internal API as user-modifiable hooks. By
563 adding your function to one of these hooks, you can modify IPython's
570 adding your function to one of these hooks, you can modify IPython's
564 behavior to call at runtime your own routines."""
571 behavior to call at runtime your own routines."""
565
572
566 # At some point in the future, this should validate the hook before it
573 # At some point in the future, this should validate the hook before it
567 # accepts it. Probably at least check that the hook takes the number
574 # accepts it. Probably at least check that the hook takes the number
568 # of args it's supposed to.
575 # of args it's supposed to.
569
576
570 f = types.MethodType(hook,self)
577 f = types.MethodType(hook,self)
571
578
572 # check if the hook is for strdispatcher first
579 # check if the hook is for strdispatcher first
573 if str_key is not None:
580 if str_key is not None:
574 sdp = self.strdispatchers.get(name, StrDispatch())
581 sdp = self.strdispatchers.get(name, StrDispatch())
575 sdp.add_s(str_key, f, priority )
582 sdp.add_s(str_key, f, priority )
576 self.strdispatchers[name] = sdp
583 self.strdispatchers[name] = sdp
577 return
584 return
578 if re_key is not None:
585 if re_key is not None:
579 sdp = self.strdispatchers.get(name, StrDispatch())
586 sdp = self.strdispatchers.get(name, StrDispatch())
580 sdp.add_re(re.compile(re_key), f, priority )
587 sdp.add_re(re.compile(re_key), f, priority )
581 self.strdispatchers[name] = sdp
588 self.strdispatchers[name] = sdp
582 return
589 return
583
590
584 dp = getattr(self.hooks, name, None)
591 dp = getattr(self.hooks, name, None)
585 if name not in IPython.core.hooks.__all__:
592 if name not in IPython.core.hooks.__all__:
586 print "Warning! Hook '%s' is not one of %s" % \
593 print "Warning! Hook '%s' is not one of %s" % \
587 (name, IPython.core.hooks.__all__ )
594 (name, IPython.core.hooks.__all__ )
588 if not dp:
595 if not dp:
589 dp = IPython.core.hooks.CommandChainDispatcher()
596 dp = IPython.core.hooks.CommandChainDispatcher()
590
597
591 try:
598 try:
592 dp.add(f,priority)
599 dp.add(f,priority)
593 except AttributeError:
600 except AttributeError:
594 # it was not commandchain, plain old func - replace
601 # it was not commandchain, plain old func - replace
595 dp = f
602 dp = f
596
603
597 setattr(self.hooks,name, dp)
604 setattr(self.hooks,name, dp)
598
605
599 def register_post_execute(self, func):
606 def register_post_execute(self, func):
600 """Register a function for calling after code execution.
607 """Register a function for calling after code execution.
601 """
608 """
602 if not callable(func):
609 if not callable(func):
603 raise ValueError('argument %s must be callable' % func)
610 raise ValueError('argument %s must be callable' % func)
604 self._post_execute.add(func)
611 self._post_execute.add(func)
605
612
606 #-------------------------------------------------------------------------
613 #-------------------------------------------------------------------------
607 # Things related to the "main" module
614 # Things related to the "main" module
608 #-------------------------------------------------------------------------
615 #-------------------------------------------------------------------------
609
616
610 def new_main_mod(self,ns=None):
617 def new_main_mod(self,ns=None):
611 """Return a new 'main' module object for user code execution.
618 """Return a new 'main' module object for user code execution.
612 """
619 """
613 main_mod = self._user_main_module
620 main_mod = self._user_main_module
614 init_fakemod_dict(main_mod,ns)
621 init_fakemod_dict(main_mod,ns)
615 return main_mod
622 return main_mod
616
623
617 def cache_main_mod(self,ns,fname):
624 def cache_main_mod(self,ns,fname):
618 """Cache a main module's namespace.
625 """Cache a main module's namespace.
619
626
620 When scripts are executed via %run, we must keep a reference to the
627 When scripts are executed via %run, we must keep a reference to the
621 namespace of their __main__ module (a FakeModule instance) around so
628 namespace of their __main__ module (a FakeModule instance) around so
622 that Python doesn't clear it, rendering objects defined therein
629 that Python doesn't clear it, rendering objects defined therein
623 useless.
630 useless.
624
631
625 This method keeps said reference in a private dict, keyed by the
632 This method keeps said reference in a private dict, keyed by the
626 absolute path of the module object (which corresponds to the script
633 absolute path of the module object (which corresponds to the script
627 path). This way, for multiple executions of the same script we only
634 path). This way, for multiple executions of the same script we only
628 keep one copy of the namespace (the last one), thus preventing memory
635 keep one copy of the namespace (the last one), thus preventing memory
629 leaks from old references while allowing the objects from the last
636 leaks from old references while allowing the objects from the last
630 execution to be accessible.
637 execution to be accessible.
631
638
632 Note: we can not allow the actual FakeModule instances to be deleted,
639 Note: we can not allow the actual FakeModule instances to be deleted,
633 because of how Python tears down modules (it hard-sets all their
640 because of how Python tears down modules (it hard-sets all their
634 references to None without regard for reference counts). This method
641 references to None without regard for reference counts). This method
635 must therefore make a *copy* of the given namespace, to allow the
642 must therefore make a *copy* of the given namespace, to allow the
636 original module's __dict__ to be cleared and reused.
643 original module's __dict__ to be cleared and reused.
637
644
638
645
639 Parameters
646 Parameters
640 ----------
647 ----------
641 ns : a namespace (a dict, typically)
648 ns : a namespace (a dict, typically)
642
649
643 fname : str
650 fname : str
644 Filename associated with the namespace.
651 Filename associated with the namespace.
645
652
646 Examples
653 Examples
647 --------
654 --------
648
655
649 In [10]: import IPython
656 In [10]: import IPython
650
657
651 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
658 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
652
659
653 In [12]: IPython.__file__ in _ip._main_ns_cache
660 In [12]: IPython.__file__ in _ip._main_ns_cache
654 Out[12]: True
661 Out[12]: True
655 """
662 """
656 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
663 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
657
664
658 def clear_main_mod_cache(self):
665 def clear_main_mod_cache(self):
659 """Clear the cache of main modules.
666 """Clear the cache of main modules.
660
667
661 Mainly for use by utilities like %reset.
668 Mainly for use by utilities like %reset.
662
669
663 Examples
670 Examples
664 --------
671 --------
665
672
666 In [15]: import IPython
673 In [15]: import IPython
667
674
668 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
675 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
669
676
670 In [17]: len(_ip._main_ns_cache) > 0
677 In [17]: len(_ip._main_ns_cache) > 0
671 Out[17]: True
678 Out[17]: True
672
679
673 In [18]: _ip.clear_main_mod_cache()
680 In [18]: _ip.clear_main_mod_cache()
674
681
675 In [19]: len(_ip._main_ns_cache) == 0
682 In [19]: len(_ip._main_ns_cache) == 0
676 Out[19]: True
683 Out[19]: True
677 """
684 """
678 self._main_ns_cache.clear()
685 self._main_ns_cache.clear()
679
686
680 #-------------------------------------------------------------------------
687 #-------------------------------------------------------------------------
681 # Things related to debugging
688 # Things related to debugging
682 #-------------------------------------------------------------------------
689 #-------------------------------------------------------------------------
683
690
684 def init_pdb(self):
691 def init_pdb(self):
685 # Set calling of pdb on exceptions
692 # Set calling of pdb on exceptions
686 # self.call_pdb is a property
693 # self.call_pdb is a property
687 self.call_pdb = self.pdb
694 self.call_pdb = self.pdb
688
695
689 def _get_call_pdb(self):
696 def _get_call_pdb(self):
690 return self._call_pdb
697 return self._call_pdb
691
698
692 def _set_call_pdb(self,val):
699 def _set_call_pdb(self,val):
693
700
694 if val not in (0,1,False,True):
701 if val not in (0,1,False,True):
695 raise ValueError,'new call_pdb value must be boolean'
702 raise ValueError,'new call_pdb value must be boolean'
696
703
697 # store value in instance
704 # store value in instance
698 self._call_pdb = val
705 self._call_pdb = val
699
706
700 # notify the actual exception handlers
707 # notify the actual exception handlers
701 self.InteractiveTB.call_pdb = val
708 self.InteractiveTB.call_pdb = val
702
709
703 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
710 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
704 'Control auto-activation of pdb at exceptions')
711 'Control auto-activation of pdb at exceptions')
705
712
706 def debugger(self,force=False):
713 def debugger(self,force=False):
707 """Call the pydb/pdb debugger.
714 """Call the pydb/pdb debugger.
708
715
709 Keywords:
716 Keywords:
710
717
711 - force(False): by default, this routine checks the instance call_pdb
718 - force(False): by default, this routine checks the instance call_pdb
712 flag and does not actually invoke the debugger if the flag is false.
719 flag and does not actually invoke the debugger if the flag is false.
713 The 'force' option forces the debugger to activate even if the flag
720 The 'force' option forces the debugger to activate even if the flag
714 is false.
721 is false.
715 """
722 """
716
723
717 if not (force or self.call_pdb):
724 if not (force or self.call_pdb):
718 return
725 return
719
726
720 if not hasattr(sys,'last_traceback'):
727 if not hasattr(sys,'last_traceback'):
721 error('No traceback has been produced, nothing to debug.')
728 error('No traceback has been produced, nothing to debug.')
722 return
729 return
723
730
724 # use pydb if available
731 # use pydb if available
725 if debugger.has_pydb:
732 if debugger.has_pydb:
726 from pydb import pm
733 from pydb import pm
727 else:
734 else:
728 # fallback to our internal debugger
735 # fallback to our internal debugger
729 pm = lambda : self.InteractiveTB.debugger(force=True)
736 pm = lambda : self.InteractiveTB.debugger(force=True)
730 self.history_saving_wrapper(pm)()
737 self.history_saving_wrapper(pm)()
731
738
732 #-------------------------------------------------------------------------
739 #-------------------------------------------------------------------------
733 # Things related to IPython's various namespaces
740 # Things related to IPython's various namespaces
734 #-------------------------------------------------------------------------
741 #-------------------------------------------------------------------------
735
742
736 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
743 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
737 # Create the namespace where the user will operate. user_ns is
744 # Create the namespace where the user will operate. user_ns is
738 # normally the only one used, and it is passed to the exec calls as
745 # normally the only one used, and it is passed to the exec calls as
739 # the locals argument. But we do carry a user_global_ns namespace
746 # the locals argument. But we do carry a user_global_ns namespace
740 # given as the exec 'globals' argument, This is useful in embedding
747 # given as the exec 'globals' argument, This is useful in embedding
741 # situations where the ipython shell opens in a context where the
748 # situations where the ipython shell opens in a context where the
742 # distinction between locals and globals is meaningful. For
749 # distinction between locals and globals is meaningful. For
743 # non-embedded contexts, it is just the same object as the user_ns dict.
750 # non-embedded contexts, it is just the same object as the user_ns dict.
744
751
745 # FIXME. For some strange reason, __builtins__ is showing up at user
752 # FIXME. For some strange reason, __builtins__ is showing up at user
746 # level as a dict instead of a module. This is a manual fix, but I
753 # level as a dict instead of a module. This is a manual fix, but I
747 # should really track down where the problem is coming from. Alex
754 # should really track down where the problem is coming from. Alex
748 # Schmolck reported this problem first.
755 # Schmolck reported this problem first.
749
756
750 # A useful post by Alex Martelli on this topic:
757 # A useful post by Alex Martelli on this topic:
751 # Re: inconsistent value from __builtins__
758 # Re: inconsistent value from __builtins__
752 # Von: Alex Martelli <aleaxit@yahoo.com>
759 # Von: Alex Martelli <aleaxit@yahoo.com>
753 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
760 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
754 # Gruppen: comp.lang.python
761 # Gruppen: comp.lang.python
755
762
756 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
763 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
757 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
764 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
758 # > <type 'dict'>
765 # > <type 'dict'>
759 # > >>> print type(__builtins__)
766 # > >>> print type(__builtins__)
760 # > <type 'module'>
767 # > <type 'module'>
761 # > Is this difference in return value intentional?
768 # > Is this difference in return value intentional?
762
769
763 # Well, it's documented that '__builtins__' can be either a dictionary
770 # Well, it's documented that '__builtins__' can be either a dictionary
764 # or a module, and it's been that way for a long time. Whether it's
771 # or a module, and it's been that way for a long time. Whether it's
765 # intentional (or sensible), I don't know. In any case, the idea is
772 # intentional (or sensible), I don't know. In any case, the idea is
766 # that if you need to access the built-in namespace directly, you
773 # that if you need to access the built-in namespace directly, you
767 # should start with "import __builtin__" (note, no 's') which will
774 # should start with "import __builtin__" (note, no 's') which will
768 # definitely give you a module. Yeah, it's somewhat confusing:-(.
775 # definitely give you a module. Yeah, it's somewhat confusing:-(.
769
776
770 # These routines return properly built dicts as needed by the rest of
777 # These routines return properly built dicts as needed by the rest of
771 # the code, and can also be used by extension writers to generate
778 # the code, and can also be used by extension writers to generate
772 # properly initialized namespaces.
779 # properly initialized namespaces.
773 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
780 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
774 user_global_ns)
781 user_global_ns)
775
782
776 # Assign namespaces
783 # Assign namespaces
777 # This is the namespace where all normal user variables live
784 # This is the namespace where all normal user variables live
778 self.user_ns = user_ns
785 self.user_ns = user_ns
779 self.user_global_ns = user_global_ns
786 self.user_global_ns = user_global_ns
780
787
781 # An auxiliary namespace that checks what parts of the user_ns were
788 # An auxiliary namespace that checks what parts of the user_ns were
782 # loaded at startup, so we can list later only variables defined in
789 # loaded at startup, so we can list later only variables defined in
783 # actual interactive use. Since it is always a subset of user_ns, it
790 # actual interactive use. Since it is always a subset of user_ns, it
784 # doesn't need to be separately tracked in the ns_table.
791 # doesn't need to be separately tracked in the ns_table.
785 self.user_ns_hidden = {}
792 self.user_ns_hidden = {}
786
793
787 # A namespace to keep track of internal data structures to prevent
794 # A namespace to keep track of internal data structures to prevent
788 # them from cluttering user-visible stuff. Will be updated later
795 # them from cluttering user-visible stuff. Will be updated later
789 self.internal_ns = {}
796 self.internal_ns = {}
790
797
791 # Now that FakeModule produces a real module, we've run into a nasty
798 # Now that FakeModule produces a real module, we've run into a nasty
792 # problem: after script execution (via %run), the module where the user
799 # problem: after script execution (via %run), the module where the user
793 # code ran is deleted. Now that this object is a true module (needed
800 # code ran is deleted. Now that this object is a true module (needed
794 # so docetst and other tools work correctly), the Python module
801 # so docetst and other tools work correctly), the Python module
795 # teardown mechanism runs over it, and sets to None every variable
802 # teardown mechanism runs over it, and sets to None every variable
796 # present in that module. Top-level references to objects from the
803 # present in that module. Top-level references to objects from the
797 # script survive, because the user_ns is updated with them. However,
804 # script survive, because the user_ns is updated with them. However,
798 # calling functions defined in the script that use other things from
805 # calling functions defined in the script that use other things from
799 # the script will fail, because the function's closure had references
806 # the script will fail, because the function's closure had references
800 # to the original objects, which are now all None. So we must protect
807 # to the original objects, which are now all None. So we must protect
801 # these modules from deletion by keeping a cache.
808 # these modules from deletion by keeping a cache.
802 #
809 #
803 # To avoid keeping stale modules around (we only need the one from the
810 # To avoid keeping stale modules around (we only need the one from the
804 # last run), we use a dict keyed with the full path to the script, so
811 # last run), we use a dict keyed with the full path to the script, so
805 # only the last version of the module is held in the cache. Note,
812 # only the last version of the module is held in the cache. Note,
806 # however, that we must cache the module *namespace contents* (their
813 # however, that we must cache the module *namespace contents* (their
807 # __dict__). Because if we try to cache the actual modules, old ones
814 # __dict__). Because if we try to cache the actual modules, old ones
808 # (uncached) could be destroyed while still holding references (such as
815 # (uncached) could be destroyed while still holding references (such as
809 # those held by GUI objects that tend to be long-lived)>
816 # those held by GUI objects that tend to be long-lived)>
810 #
817 #
811 # The %reset command will flush this cache. See the cache_main_mod()
818 # The %reset command will flush this cache. See the cache_main_mod()
812 # and clear_main_mod_cache() methods for details on use.
819 # and clear_main_mod_cache() methods for details on use.
813
820
814 # This is the cache used for 'main' namespaces
821 # This is the cache used for 'main' namespaces
815 self._main_ns_cache = {}
822 self._main_ns_cache = {}
816 # And this is the single instance of FakeModule whose __dict__ we keep
823 # And this is the single instance of FakeModule whose __dict__ we keep
817 # copying and clearing for reuse on each %run
824 # copying and clearing for reuse on each %run
818 self._user_main_module = FakeModule()
825 self._user_main_module = FakeModule()
819
826
820 # A table holding all the namespaces IPython deals with, so that
827 # A table holding all the namespaces IPython deals with, so that
821 # introspection facilities can search easily.
828 # introspection facilities can search easily.
822 self.ns_table = {'user':user_ns,
829 self.ns_table = {'user':user_ns,
823 'user_global':user_global_ns,
830 'user_global':user_global_ns,
824 'internal':self.internal_ns,
831 'internal':self.internal_ns,
825 'builtin':__builtin__.__dict__
832 'builtin':__builtin__.__dict__
826 }
833 }
827
834
828 # Similarly, track all namespaces where references can be held and that
835 # Similarly, track all namespaces where references can be held and that
829 # we can safely clear (so it can NOT include builtin). This one can be
836 # we can safely clear (so it can NOT include builtin). This one can be
830 # a simple list. Note that the main execution namespaces, user_ns and
837 # a simple list. Note that the main execution namespaces, user_ns and
831 # user_global_ns, can NOT be listed here, as clearing them blindly
838 # user_global_ns, can NOT be listed here, as clearing them blindly
832 # causes errors in object __del__ methods. Instead, the reset() method
839 # causes errors in object __del__ methods. Instead, the reset() method
833 # clears them manually and carefully.
840 # clears them manually and carefully.
834 self.ns_refs_table = [ self.user_ns_hidden,
841 self.ns_refs_table = [ self.user_ns_hidden,
835 self.internal_ns, self._main_ns_cache ]
842 self.internal_ns, self._main_ns_cache ]
836
843
837 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
844 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
838 """Return a valid local and global user interactive namespaces.
845 """Return a valid local and global user interactive namespaces.
839
846
840 This builds a dict with the minimal information needed to operate as a
847 This builds a dict with the minimal information needed to operate as a
841 valid IPython user namespace, which you can pass to the various
848 valid IPython user namespace, which you can pass to the various
842 embedding classes in ipython. The default implementation returns the
849 embedding classes in ipython. The default implementation returns the
843 same dict for both the locals and the globals to allow functions to
850 same dict for both the locals and the globals to allow functions to
844 refer to variables in the namespace. Customized implementations can
851 refer to variables in the namespace. Customized implementations can
845 return different dicts. The locals dictionary can actually be anything
852 return different dicts. The locals dictionary can actually be anything
846 following the basic mapping protocol of a dict, but the globals dict
853 following the basic mapping protocol of a dict, but the globals dict
847 must be a true dict, not even a subclass. It is recommended that any
854 must be a true dict, not even a subclass. It is recommended that any
848 custom object for the locals namespace synchronize with the globals
855 custom object for the locals namespace synchronize with the globals
849 dict somehow.
856 dict somehow.
850
857
851 Raises TypeError if the provided globals namespace is not a true dict.
858 Raises TypeError if the provided globals namespace is not a true dict.
852
859
853 Parameters
860 Parameters
854 ----------
861 ----------
855 user_ns : dict-like, optional
862 user_ns : dict-like, optional
856 The current user namespace. The items in this namespace should
863 The current user namespace. The items in this namespace should
857 be included in the output. If None, an appropriate blank
864 be included in the output. If None, an appropriate blank
858 namespace should be created.
865 namespace should be created.
859 user_global_ns : dict, optional
866 user_global_ns : dict, optional
860 The current user global namespace. The items in this namespace
867 The current user global namespace. The items in this namespace
861 should be included in the output. If None, an appropriate
868 should be included in the output. If None, an appropriate
862 blank namespace should be created.
869 blank namespace should be created.
863
870
864 Returns
871 Returns
865 -------
872 -------
866 A pair of dictionary-like object to be used as the local namespace
873 A pair of dictionary-like object to be used as the local namespace
867 of the interpreter and a dict to be used as the global namespace.
874 of the interpreter and a dict to be used as the global namespace.
868 """
875 """
869
876
870
877
871 # We must ensure that __builtin__ (without the final 's') is always
878 # We must ensure that __builtin__ (without the final 's') is always
872 # available and pointing to the __builtin__ *module*. For more details:
879 # available and pointing to the __builtin__ *module*. For more details:
873 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
880 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
874
881
875 if user_ns is None:
882 if user_ns is None:
876 # Set __name__ to __main__ to better match the behavior of the
883 # Set __name__ to __main__ to better match the behavior of the
877 # normal interpreter.
884 # normal interpreter.
878 user_ns = {'__name__' :'__main__',
885 user_ns = {'__name__' :'__main__',
879 '__builtin__' : __builtin__,
886 '__builtin__' : __builtin__,
880 '__builtins__' : __builtin__,
887 '__builtins__' : __builtin__,
881 }
888 }
882 else:
889 else:
883 user_ns.setdefault('__name__','__main__')
890 user_ns.setdefault('__name__','__main__')
884 user_ns.setdefault('__builtin__',__builtin__)
891 user_ns.setdefault('__builtin__',__builtin__)
885 user_ns.setdefault('__builtins__',__builtin__)
892 user_ns.setdefault('__builtins__',__builtin__)
886
893
887 if user_global_ns is None:
894 if user_global_ns is None:
888 user_global_ns = user_ns
895 user_global_ns = user_ns
889 if type(user_global_ns) is not dict:
896 if type(user_global_ns) is not dict:
890 raise TypeError("user_global_ns must be a true dict; got %r"
897 raise TypeError("user_global_ns must be a true dict; got %r"
891 % type(user_global_ns))
898 % type(user_global_ns))
892
899
893 return user_ns, user_global_ns
900 return user_ns, user_global_ns
894
901
895 def init_sys_modules(self):
902 def init_sys_modules(self):
896 # We need to insert into sys.modules something that looks like a
903 # We need to insert into sys.modules something that looks like a
897 # module but which accesses the IPython namespace, for shelve and
904 # module but which accesses the IPython namespace, for shelve and
898 # pickle to work interactively. Normally they rely on getting
905 # pickle to work interactively. Normally they rely on getting
899 # everything out of __main__, but for embedding purposes each IPython
906 # everything out of __main__, but for embedding purposes each IPython
900 # instance has its own private namespace, so we can't go shoving
907 # instance has its own private namespace, so we can't go shoving
901 # everything into __main__.
908 # everything into __main__.
902
909
903 # note, however, that we should only do this for non-embedded
910 # note, however, that we should only do this for non-embedded
904 # ipythons, which really mimic the __main__.__dict__ with their own
911 # ipythons, which really mimic the __main__.__dict__ with their own
905 # namespace. Embedded instances, on the other hand, should not do
912 # namespace. Embedded instances, on the other hand, should not do
906 # this because they need to manage the user local/global namespaces
913 # this because they need to manage the user local/global namespaces
907 # only, but they live within a 'normal' __main__ (meaning, they
914 # only, but they live within a 'normal' __main__ (meaning, they
908 # shouldn't overtake the execution environment of the script they're
915 # shouldn't overtake the execution environment of the script they're
909 # embedded in).
916 # embedded in).
910
917
911 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
918 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
912
919
913 try:
920 try:
914 main_name = self.user_ns['__name__']
921 main_name = self.user_ns['__name__']
915 except KeyError:
922 except KeyError:
916 raise KeyError('user_ns dictionary MUST have a "__name__" key')
923 raise KeyError('user_ns dictionary MUST have a "__name__" key')
917 else:
924 else:
918 sys.modules[main_name] = FakeModule(self.user_ns)
925 sys.modules[main_name] = FakeModule(self.user_ns)
919
926
920 def init_user_ns(self):
927 def init_user_ns(self):
921 """Initialize all user-visible namespaces to their minimum defaults.
928 """Initialize all user-visible namespaces to their minimum defaults.
922
929
923 Certain history lists are also initialized here, as they effectively
930 Certain history lists are also initialized here, as they effectively
924 act as user namespaces.
931 act as user namespaces.
925
932
926 Notes
933 Notes
927 -----
934 -----
928 All data structures here are only filled in, they are NOT reset by this
935 All data structures here are only filled in, they are NOT reset by this
929 method. If they were not empty before, data will simply be added to
936 method. If they were not empty before, data will simply be added to
930 therm.
937 therm.
931 """
938 """
932 # This function works in two parts: first we put a few things in
939 # This function works in two parts: first we put a few things in
933 # user_ns, and we sync that contents into user_ns_hidden so that these
940 # user_ns, and we sync that contents into user_ns_hidden so that these
934 # initial variables aren't shown by %who. After the sync, we add the
941 # initial variables aren't shown by %who. After the sync, we add the
935 # rest of what we *do* want the user to see with %who even on a new
942 # rest of what we *do* want the user to see with %who even on a new
936 # session (probably nothing, so theye really only see their own stuff)
943 # session (probably nothing, so theye really only see their own stuff)
937
944
938 # The user dict must *always* have a __builtin__ reference to the
945 # The user dict must *always* have a __builtin__ reference to the
939 # Python standard __builtin__ namespace, which must be imported.
946 # Python standard __builtin__ namespace, which must be imported.
940 # This is so that certain operations in prompt evaluation can be
947 # This is so that certain operations in prompt evaluation can be
941 # reliably executed with builtins. Note that we can NOT use
948 # reliably executed with builtins. Note that we can NOT use
942 # __builtins__ (note the 's'), because that can either be a dict or a
949 # __builtins__ (note the 's'), because that can either be a dict or a
943 # module, and can even mutate at runtime, depending on the context
950 # module, and can even mutate at runtime, depending on the context
944 # (Python makes no guarantees on it). In contrast, __builtin__ is
951 # (Python makes no guarantees on it). In contrast, __builtin__ is
945 # always a module object, though it must be explicitly imported.
952 # always a module object, though it must be explicitly imported.
946
953
947 # For more details:
954 # For more details:
948 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
955 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
949 ns = dict(__builtin__ = __builtin__)
956 ns = dict(__builtin__ = __builtin__)
950
957
951 # Put 'help' in the user namespace
958 # Put 'help' in the user namespace
952 try:
959 try:
953 from site import _Helper
960 from site import _Helper
954 ns['help'] = _Helper()
961 ns['help'] = _Helper()
955 except ImportError:
962 except ImportError:
956 warn('help() not available - check site.py')
963 warn('help() not available - check site.py')
957
964
958 # make global variables for user access to the histories
965 # make global variables for user access to the histories
959 ns['_ih'] = self.history_manager.input_hist_parsed
966 ns['_ih'] = self.history_manager.input_hist_parsed
960 ns['_oh'] = self.history_manager.output_hist
967 ns['_oh'] = self.history_manager.output_hist
961 ns['_dh'] = self.history_manager.dir_hist
968 ns['_dh'] = self.history_manager.dir_hist
962
969
963 ns['_sh'] = shadowns
970 ns['_sh'] = shadowns
964
971
965 # user aliases to input and output histories. These shouldn't show up
972 # user aliases to input and output histories. These shouldn't show up
966 # in %who, as they can have very large reprs.
973 # in %who, as they can have very large reprs.
967 ns['In'] = self.history_manager.input_hist_parsed
974 ns['In'] = self.history_manager.input_hist_parsed
968 ns['Out'] = self.history_manager.output_hist
975 ns['Out'] = self.history_manager.output_hist
969
976
970 # Store myself as the public api!!!
977 # Store myself as the public api!!!
971 ns['get_ipython'] = self.get_ipython
978 ns['get_ipython'] = self.get_ipython
972
979
973 # Sync what we've added so far to user_ns_hidden so these aren't seen
980 # Sync what we've added so far to user_ns_hidden so these aren't seen
974 # by %who
981 # by %who
975 self.user_ns_hidden.update(ns)
982 self.user_ns_hidden.update(ns)
976
983
977 # Anything put into ns now would show up in %who. Think twice before
984 # Anything put into ns now would show up in %who. Think twice before
978 # putting anything here, as we really want %who to show the user their
985 # putting anything here, as we really want %who to show the user their
979 # stuff, not our variables.
986 # stuff, not our variables.
980
987
981 # Finally, update the real user's namespace
988 # Finally, update the real user's namespace
982 self.user_ns.update(ns)
989 self.user_ns.update(ns)
983
990
984 def reset(self):
991 def reset(self):
985 """Clear all internal namespaces.
992 """Clear all internal namespaces.
986
993
987 Note that this is much more aggressive than %reset, since it clears
994 Note that this is much more aggressive than %reset, since it clears
988 fully all namespaces, as well as all input/output lists.
995 fully all namespaces, as well as all input/output lists.
989 """
996 """
990 # Clear histories
997 # Clear histories
991 self.history_manager.reset()
998 self.history_manager.reset()
992
999
993 # Reset counter used to index all histories
1000 # Reset counter used to index all histories
994 self.execution_count = 0
1001 self.execution_count = 0
995
1002
996 # Restore the user namespaces to minimal usability
1003 # Restore the user namespaces to minimal usability
997 for ns in self.ns_refs_table:
1004 for ns in self.ns_refs_table:
998 ns.clear()
1005 ns.clear()
999
1006
1000 # The main execution namespaces must be cleared very carefully,
1007 # The main execution namespaces must be cleared very carefully,
1001 # skipping the deletion of the builtin-related keys, because doing so
1008 # skipping the deletion of the builtin-related keys, because doing so
1002 # would cause errors in many object's __del__ methods.
1009 # would cause errors in many object's __del__ methods.
1003 for ns in [self.user_ns, self.user_global_ns]:
1010 for ns in [self.user_ns, self.user_global_ns]:
1004 drop_keys = set(ns.keys())
1011 drop_keys = set(ns.keys())
1005 drop_keys.discard('__builtin__')
1012 drop_keys.discard('__builtin__')
1006 drop_keys.discard('__builtins__')
1013 drop_keys.discard('__builtins__')
1007 for k in drop_keys:
1014 for k in drop_keys:
1008 del ns[k]
1015 del ns[k]
1009
1016
1010 # Restore the user namespaces to minimal usability
1017 # Restore the user namespaces to minimal usability
1011 self.init_user_ns()
1018 self.init_user_ns()
1012
1019
1013 # Restore the default and user aliases
1020 # Restore the default and user aliases
1014 self.alias_manager.clear_aliases()
1021 self.alias_manager.clear_aliases()
1015 self.alias_manager.init_aliases()
1022 self.alias_manager.init_aliases()
1016
1023
1017 def reset_selective(self, regex=None):
1024 def reset_selective(self, regex=None):
1018 """Clear selective variables from internal namespaces based on a
1025 """Clear selective variables from internal namespaces based on a
1019 specified regular expression.
1026 specified regular expression.
1020
1027
1021 Parameters
1028 Parameters
1022 ----------
1029 ----------
1023 regex : string or compiled pattern, optional
1030 regex : string or compiled pattern, optional
1024 A regular expression pattern that will be used in searching
1031 A regular expression pattern that will be used in searching
1025 variable names in the users namespaces.
1032 variable names in the users namespaces.
1026 """
1033 """
1027 if regex is not None:
1034 if regex is not None:
1028 try:
1035 try:
1029 m = re.compile(regex)
1036 m = re.compile(regex)
1030 except TypeError:
1037 except TypeError:
1031 raise TypeError('regex must be a string or compiled pattern')
1038 raise TypeError('regex must be a string or compiled pattern')
1032 # Search for keys in each namespace that match the given regex
1039 # Search for keys in each namespace that match the given regex
1033 # If a match is found, delete the key/value pair.
1040 # If a match is found, delete the key/value pair.
1034 for ns in self.ns_refs_table:
1041 for ns in self.ns_refs_table:
1035 for var in ns:
1042 for var in ns:
1036 if m.search(var):
1043 if m.search(var):
1037 del ns[var]
1044 del ns[var]
1038
1045
1039 def push(self, variables, interactive=True):
1046 def push(self, variables, interactive=True):
1040 """Inject a group of variables into the IPython user namespace.
1047 """Inject a group of variables into the IPython user namespace.
1041
1048
1042 Parameters
1049 Parameters
1043 ----------
1050 ----------
1044 variables : dict, str or list/tuple of str
1051 variables : dict, str or list/tuple of str
1045 The variables to inject into the user's namespace. If a dict, a
1052 The variables to inject into the user's namespace. If a dict, a
1046 simple update is done. If a str, the string is assumed to have
1053 simple update is done. If a str, the string is assumed to have
1047 variable names separated by spaces. A list/tuple of str can also
1054 variable names separated by spaces. A list/tuple of str can also
1048 be used to give the variable names. If just the variable names are
1055 be used to give the variable names. If just the variable names are
1049 give (list/tuple/str) then the variable values looked up in the
1056 give (list/tuple/str) then the variable values looked up in the
1050 callers frame.
1057 callers frame.
1051 interactive : bool
1058 interactive : bool
1052 If True (default), the variables will be listed with the ``who``
1059 If True (default), the variables will be listed with the ``who``
1053 magic.
1060 magic.
1054 """
1061 """
1055 vdict = None
1062 vdict = None
1056
1063
1057 # We need a dict of name/value pairs to do namespace updates.
1064 # We need a dict of name/value pairs to do namespace updates.
1058 if isinstance(variables, dict):
1065 if isinstance(variables, dict):
1059 vdict = variables
1066 vdict = variables
1060 elif isinstance(variables, (basestring, list, tuple)):
1067 elif isinstance(variables, (basestring, list, tuple)):
1061 if isinstance(variables, basestring):
1068 if isinstance(variables, basestring):
1062 vlist = variables.split()
1069 vlist = variables.split()
1063 else:
1070 else:
1064 vlist = variables
1071 vlist = variables
1065 vdict = {}
1072 vdict = {}
1066 cf = sys._getframe(1)
1073 cf = sys._getframe(1)
1067 for name in vlist:
1074 for name in vlist:
1068 try:
1075 try:
1069 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1076 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1070 except:
1077 except:
1071 print ('Could not get variable %s from %s' %
1078 print ('Could not get variable %s from %s' %
1072 (name,cf.f_code.co_name))
1079 (name,cf.f_code.co_name))
1073 else:
1080 else:
1074 raise ValueError('variables must be a dict/str/list/tuple')
1081 raise ValueError('variables must be a dict/str/list/tuple')
1075
1082
1076 # Propagate variables to user namespace
1083 # Propagate variables to user namespace
1077 self.user_ns.update(vdict)
1084 self.user_ns.update(vdict)
1078
1085
1079 # And configure interactive visibility
1086 # And configure interactive visibility
1080 config_ns = self.user_ns_hidden
1087 config_ns = self.user_ns_hidden
1081 if interactive:
1088 if interactive:
1082 for name, val in vdict.iteritems():
1089 for name, val in vdict.iteritems():
1083 config_ns.pop(name, None)
1090 config_ns.pop(name, None)
1084 else:
1091 else:
1085 for name,val in vdict.iteritems():
1092 for name,val in vdict.iteritems():
1086 config_ns[name] = val
1093 config_ns[name] = val
1087
1094
1088 #-------------------------------------------------------------------------
1095 #-------------------------------------------------------------------------
1089 # Things related to object introspection
1096 # Things related to object introspection
1090 #-------------------------------------------------------------------------
1097 #-------------------------------------------------------------------------
1091
1098
1092 def _ofind(self, oname, namespaces=None):
1099 def _ofind(self, oname, namespaces=None):
1093 """Find an object in the available namespaces.
1100 """Find an object in the available namespaces.
1094
1101
1095 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1102 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1096
1103
1097 Has special code to detect magic functions.
1104 Has special code to detect magic functions.
1098 """
1105 """
1099 #oname = oname.strip()
1106 #oname = oname.strip()
1100 #print '1- oname: <%r>' % oname # dbg
1107 #print '1- oname: <%r>' % oname # dbg
1101 try:
1108 try:
1102 oname = oname.strip().encode('ascii')
1109 oname = oname.strip().encode('ascii')
1103 #print '2- oname: <%r>' % oname # dbg
1110 #print '2- oname: <%r>' % oname # dbg
1104 except UnicodeEncodeError:
1111 except UnicodeEncodeError:
1105 print 'Python identifiers can only contain ascii characters.'
1112 print 'Python identifiers can only contain ascii characters.'
1106 return dict(found=False)
1113 return dict(found=False)
1107
1114
1108 alias_ns = None
1115 alias_ns = None
1109 if namespaces is None:
1116 if namespaces is None:
1110 # Namespaces to search in:
1117 # Namespaces to search in:
1111 # Put them in a list. The order is important so that we
1118 # Put them in a list. The order is important so that we
1112 # find things in the same order that Python finds them.
1119 # find things in the same order that Python finds them.
1113 namespaces = [ ('Interactive', self.user_ns),
1120 namespaces = [ ('Interactive', self.user_ns),
1114 ('IPython internal', self.internal_ns),
1121 ('IPython internal', self.internal_ns),
1115 ('Python builtin', __builtin__.__dict__),
1122 ('Python builtin', __builtin__.__dict__),
1116 ('Alias', self.alias_manager.alias_table),
1123 ('Alias', self.alias_manager.alias_table),
1117 ]
1124 ]
1118 alias_ns = self.alias_manager.alias_table
1125 alias_ns = self.alias_manager.alias_table
1119
1126
1120 # initialize results to 'null'
1127 # initialize results to 'null'
1121 found = False; obj = None; ospace = None; ds = None;
1128 found = False; obj = None; ospace = None; ds = None;
1122 ismagic = False; isalias = False; parent = None
1129 ismagic = False; isalias = False; parent = None
1123
1130
1124 # We need to special-case 'print', which as of python2.6 registers as a
1131 # We need to special-case 'print', which as of python2.6 registers as a
1125 # function but should only be treated as one if print_function was
1132 # function but should only be treated as one if print_function was
1126 # loaded with a future import. In this case, just bail.
1133 # loaded with a future import. In this case, just bail.
1127 if (oname == 'print' and not (self.compile.compiler_flags &
1134 if (oname == 'print' and not (self.compile.compiler_flags &
1128 __future__.CO_FUTURE_PRINT_FUNCTION)):
1135 __future__.CO_FUTURE_PRINT_FUNCTION)):
1129 return {'found':found, 'obj':obj, 'namespace':ospace,
1136 return {'found':found, 'obj':obj, 'namespace':ospace,
1130 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1137 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1131
1138
1132 # Look for the given name by splitting it in parts. If the head is
1139 # Look for the given name by splitting it in parts. If the head is
1133 # found, then we look for all the remaining parts as members, and only
1140 # found, then we look for all the remaining parts as members, and only
1134 # declare success if we can find them all.
1141 # declare success if we can find them all.
1135 oname_parts = oname.split('.')
1142 oname_parts = oname.split('.')
1136 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1143 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1137 for nsname,ns in namespaces:
1144 for nsname,ns in namespaces:
1138 try:
1145 try:
1139 obj = ns[oname_head]
1146 obj = ns[oname_head]
1140 except KeyError:
1147 except KeyError:
1141 continue
1148 continue
1142 else:
1149 else:
1143 #print 'oname_rest:', oname_rest # dbg
1150 #print 'oname_rest:', oname_rest # dbg
1144 for part in oname_rest:
1151 for part in oname_rest:
1145 try:
1152 try:
1146 parent = obj
1153 parent = obj
1147 obj = getattr(obj,part)
1154 obj = getattr(obj,part)
1148 except:
1155 except:
1149 # Blanket except b/c some badly implemented objects
1156 # Blanket except b/c some badly implemented objects
1150 # allow __getattr__ to raise exceptions other than
1157 # allow __getattr__ to raise exceptions other than
1151 # AttributeError, which then crashes IPython.
1158 # AttributeError, which then crashes IPython.
1152 break
1159 break
1153 else:
1160 else:
1154 # If we finish the for loop (no break), we got all members
1161 # If we finish the for loop (no break), we got all members
1155 found = True
1162 found = True
1156 ospace = nsname
1163 ospace = nsname
1157 if ns == alias_ns:
1164 if ns == alias_ns:
1158 isalias = True
1165 isalias = True
1159 break # namespace loop
1166 break # namespace loop
1160
1167
1161 # Try to see if it's magic
1168 # Try to see if it's magic
1162 if not found:
1169 if not found:
1163 if oname.startswith(ESC_MAGIC):
1170 if oname.startswith(ESC_MAGIC):
1164 oname = oname[1:]
1171 oname = oname[1:]
1165 obj = getattr(self,'magic_'+oname,None)
1172 obj = getattr(self,'magic_'+oname,None)
1166 if obj is not None:
1173 if obj is not None:
1167 found = True
1174 found = True
1168 ospace = 'IPython internal'
1175 ospace = 'IPython internal'
1169 ismagic = True
1176 ismagic = True
1170
1177
1171 # Last try: special-case some literals like '', [], {}, etc:
1178 # Last try: special-case some literals like '', [], {}, etc:
1172 if not found and oname_head in ["''",'""','[]','{}','()']:
1179 if not found and oname_head in ["''",'""','[]','{}','()']:
1173 obj = eval(oname_head)
1180 obj = eval(oname_head)
1174 found = True
1181 found = True
1175 ospace = 'Interactive'
1182 ospace = 'Interactive'
1176
1183
1177 return {'found':found, 'obj':obj, 'namespace':ospace,
1184 return {'found':found, 'obj':obj, 'namespace':ospace,
1178 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1185 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1179
1186
1180 def _ofind_property(self, oname, info):
1187 def _ofind_property(self, oname, info):
1181 """Second part of object finding, to look for property details."""
1188 """Second part of object finding, to look for property details."""
1182 if info.found:
1189 if info.found:
1183 # Get the docstring of the class property if it exists.
1190 # Get the docstring of the class property if it exists.
1184 path = oname.split('.')
1191 path = oname.split('.')
1185 root = '.'.join(path[:-1])
1192 root = '.'.join(path[:-1])
1186 if info.parent is not None:
1193 if info.parent is not None:
1187 try:
1194 try:
1188 target = getattr(info.parent, '__class__')
1195 target = getattr(info.parent, '__class__')
1189 # The object belongs to a class instance.
1196 # The object belongs to a class instance.
1190 try:
1197 try:
1191 target = getattr(target, path[-1])
1198 target = getattr(target, path[-1])
1192 # The class defines the object.
1199 # The class defines the object.
1193 if isinstance(target, property):
1200 if isinstance(target, property):
1194 oname = root + '.__class__.' + path[-1]
1201 oname = root + '.__class__.' + path[-1]
1195 info = Struct(self._ofind(oname))
1202 info = Struct(self._ofind(oname))
1196 except AttributeError: pass
1203 except AttributeError: pass
1197 except AttributeError: pass
1204 except AttributeError: pass
1198
1205
1199 # We return either the new info or the unmodified input if the object
1206 # We return either the new info or the unmodified input if the object
1200 # hadn't been found
1207 # hadn't been found
1201 return info
1208 return info
1202
1209
1203 def _object_find(self, oname, namespaces=None):
1210 def _object_find(self, oname, namespaces=None):
1204 """Find an object and return a struct with info about it."""
1211 """Find an object and return a struct with info about it."""
1205 inf = Struct(self._ofind(oname, namespaces))
1212 inf = Struct(self._ofind(oname, namespaces))
1206 return Struct(self._ofind_property(oname, inf))
1213 return Struct(self._ofind_property(oname, inf))
1207
1214
1208 def _inspect(self, meth, oname, namespaces=None, **kw):
1215 def _inspect(self, meth, oname, namespaces=None, **kw):
1209 """Generic interface to the inspector system.
1216 """Generic interface to the inspector system.
1210
1217
1211 This function is meant to be called by pdef, pdoc & friends."""
1218 This function is meant to be called by pdef, pdoc & friends."""
1212 info = self._object_find(oname)
1219 info = self._object_find(oname)
1213 if info.found:
1220 if info.found:
1214 pmethod = getattr(self.inspector, meth)
1221 pmethod = getattr(self.inspector, meth)
1215 formatter = format_screen if info.ismagic else None
1222 formatter = format_screen if info.ismagic else None
1216 if meth == 'pdoc':
1223 if meth == 'pdoc':
1217 pmethod(info.obj, oname, formatter)
1224 pmethod(info.obj, oname, formatter)
1218 elif meth == 'pinfo':
1225 elif meth == 'pinfo':
1219 pmethod(info.obj, oname, formatter, info, **kw)
1226 pmethod(info.obj, oname, formatter, info, **kw)
1220 else:
1227 else:
1221 pmethod(info.obj, oname)
1228 pmethod(info.obj, oname)
1222 else:
1229 else:
1223 print 'Object `%s` not found.' % oname
1230 print 'Object `%s` not found.' % oname
1224 return 'not found' # so callers can take other action
1231 return 'not found' # so callers can take other action
1225
1232
1226 def object_inspect(self, oname):
1233 def object_inspect(self, oname):
1227 info = self._object_find(oname)
1234 info = self._object_find(oname)
1228 if info.found:
1235 if info.found:
1229 return self.inspector.info(info.obj, oname, info=info)
1236 return self.inspector.info(info.obj, oname, info=info)
1230 else:
1237 else:
1231 return oinspect.object_info(name=oname, found=False)
1238 return oinspect.object_info(name=oname, found=False)
1232
1239
1233 #-------------------------------------------------------------------------
1240 #-------------------------------------------------------------------------
1234 # Things related to history management
1241 # Things related to history management
1235 #-------------------------------------------------------------------------
1242 #-------------------------------------------------------------------------
1236
1243
1237 def init_history(self):
1244 def init_history(self):
1238 """Sets up the command history, and starts regular autosaves."""
1245 """Sets up the command history, and starts regular autosaves."""
1239 self.history_manager = HistoryManager(shell=self)
1246 self.history_manager = HistoryManager(shell=self)
1240
1247
1241 def save_history(self):
1248 def save_history(self):
1242 """Save input history to a file (via readline library)."""
1249 """Save input history to a file (via readline library)."""
1243 self.history_manager.save_history()
1250 self.history_manager.save_history()
1244
1251
1245 def reload_history(self):
1252 def reload_history(self):
1246 """Reload the input history from disk file."""
1253 """Reload the input history from disk file."""
1247 self.history_manager.reload_history()
1254 self.history_manager.reload_history()
1248
1255
1249 def history_saving_wrapper(self, func):
1256 def history_saving_wrapper(self, func):
1250 """ Wrap func for readline history saving
1257 """ Wrap func for readline history saving
1251
1258
1252 Convert func into callable that saves & restores
1259 Convert func into callable that saves & restores
1253 history around the call """
1260 history around the call """
1254
1261
1255 if self.has_readline:
1262 if self.has_readline:
1256 from IPython.utils import rlineimpl as readline
1263 from IPython.utils import rlineimpl as readline
1257 else:
1264 else:
1258 return func
1265 return func
1259
1266
1260 def wrapper():
1267 def wrapper():
1261 self.save_history()
1268 self.save_history()
1262 try:
1269 try:
1263 func()
1270 func()
1264 finally:
1271 finally:
1265 self.reload_history()
1272 self.reload_history()
1266 return wrapper
1273 return wrapper
1267
1274
1268 def get_history(self, index=None, raw=False, output=True):
1275 def get_history(self, index=None, raw=False, output=True):
1269 return self.history_manager.get_history(index, raw, output)
1276 return self.history_manager.get_history(index, raw, output)
1270
1277
1271
1278
1272 #-------------------------------------------------------------------------
1279 #-------------------------------------------------------------------------
1273 # Things related to exception handling and tracebacks (not debugging)
1280 # Things related to exception handling and tracebacks (not debugging)
1274 #-------------------------------------------------------------------------
1281 #-------------------------------------------------------------------------
1275
1282
1276 def init_traceback_handlers(self, custom_exceptions):
1283 def init_traceback_handlers(self, custom_exceptions):
1277 # Syntax error handler.
1284 # Syntax error handler.
1278 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1285 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1279
1286
1280 # The interactive one is initialized with an offset, meaning we always
1287 # The interactive one is initialized with an offset, meaning we always
1281 # want to remove the topmost item in the traceback, which is our own
1288 # want to remove the topmost item in the traceback, which is our own
1282 # internal code. Valid modes: ['Plain','Context','Verbose']
1289 # internal code. Valid modes: ['Plain','Context','Verbose']
1283 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1290 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1284 color_scheme='NoColor',
1291 color_scheme='NoColor',
1285 tb_offset = 1,
1292 tb_offset = 1,
1286 check_cache=self.compile.check_cache)
1293 check_cache=self.compile.check_cache)
1287
1294
1288 # The instance will store a pointer to the system-wide exception hook,
1295 # The instance will store a pointer to the system-wide exception hook,
1289 # so that runtime code (such as magics) can access it. This is because
1296 # so that runtime code (such as magics) can access it. This is because
1290 # during the read-eval loop, it may get temporarily overwritten.
1297 # during the read-eval loop, it may get temporarily overwritten.
1291 self.sys_excepthook = sys.excepthook
1298 self.sys_excepthook = sys.excepthook
1292
1299
1293 # and add any custom exception handlers the user may have specified
1300 # and add any custom exception handlers the user may have specified
1294 self.set_custom_exc(*custom_exceptions)
1301 self.set_custom_exc(*custom_exceptions)
1295
1302
1296 # Set the exception mode
1303 # Set the exception mode
1297 self.InteractiveTB.set_mode(mode=self.xmode)
1304 self.InteractiveTB.set_mode(mode=self.xmode)
1298
1305
1299 def set_custom_exc(self, exc_tuple, handler):
1306 def set_custom_exc(self, exc_tuple, handler):
1300 """set_custom_exc(exc_tuple,handler)
1307 """set_custom_exc(exc_tuple,handler)
1301
1308
1302 Set a custom exception handler, which will be called if any of the
1309 Set a custom exception handler, which will be called if any of the
1303 exceptions in exc_tuple occur in the mainloop (specifically, in the
1310 exceptions in exc_tuple occur in the mainloop (specifically, in the
1304 run_code() method.
1311 run_code() method.
1305
1312
1306 Inputs:
1313 Inputs:
1307
1314
1308 - exc_tuple: a *tuple* of valid exceptions to call the defined
1315 - exc_tuple: a *tuple* of valid exceptions to call the defined
1309 handler for. It is very important that you use a tuple, and NOT A
1316 handler for. It is very important that you use a tuple, and NOT A
1310 LIST here, because of the way Python's except statement works. If
1317 LIST here, because of the way Python's except statement works. If
1311 you only want to trap a single exception, use a singleton tuple:
1318 you only want to trap a single exception, use a singleton tuple:
1312
1319
1313 exc_tuple == (MyCustomException,)
1320 exc_tuple == (MyCustomException,)
1314
1321
1315 - handler: this must be defined as a function with the following
1322 - handler: this must be defined as a function with the following
1316 basic interface::
1323 basic interface::
1317
1324
1318 def my_handler(self, etype, value, tb, tb_offset=None)
1325 def my_handler(self, etype, value, tb, tb_offset=None)
1319 ...
1326 ...
1320 # The return value must be
1327 # The return value must be
1321 return structured_traceback
1328 return structured_traceback
1322
1329
1323 This will be made into an instance method (via types.MethodType)
1330 This will be made into an instance method (via types.MethodType)
1324 of IPython itself, and it will be called if any of the exceptions
1331 of IPython itself, and it will be called if any of the exceptions
1325 listed in the exc_tuple are caught. If the handler is None, an
1332 listed in the exc_tuple are caught. If the handler is None, an
1326 internal basic one is used, which just prints basic info.
1333 internal basic one is used, which just prints basic info.
1327
1334
1328 WARNING: by putting in your own exception handler into IPython's main
1335 WARNING: by putting in your own exception handler into IPython's main
1329 execution loop, you run a very good chance of nasty crashes. This
1336 execution loop, you run a very good chance of nasty crashes. This
1330 facility should only be used if you really know what you are doing."""
1337 facility should only be used if you really know what you are doing."""
1331
1338
1332 assert type(exc_tuple)==type(()) , \
1339 assert type(exc_tuple)==type(()) , \
1333 "The custom exceptions must be given AS A TUPLE."
1340 "The custom exceptions must be given AS A TUPLE."
1334
1341
1335 def dummy_handler(self,etype,value,tb):
1342 def dummy_handler(self,etype,value,tb):
1336 print '*** Simple custom exception handler ***'
1343 print '*** Simple custom exception handler ***'
1337 print 'Exception type :',etype
1344 print 'Exception type :',etype
1338 print 'Exception value:',value
1345 print 'Exception value:',value
1339 print 'Traceback :',tb
1346 print 'Traceback :',tb
1340 print 'Source code :','\n'.join(self.buffer)
1347 print 'Source code :','\n'.join(self.buffer)
1341
1348
1342 if handler is None: handler = dummy_handler
1349 if handler is None: handler = dummy_handler
1343
1350
1344 self.CustomTB = types.MethodType(handler,self)
1351 self.CustomTB = types.MethodType(handler,self)
1345 self.custom_exceptions = exc_tuple
1352 self.custom_exceptions = exc_tuple
1346
1353
1347 def excepthook(self, etype, value, tb):
1354 def excepthook(self, etype, value, tb):
1348 """One more defense for GUI apps that call sys.excepthook.
1355 """One more defense for GUI apps that call sys.excepthook.
1349
1356
1350 GUI frameworks like wxPython trap exceptions and call
1357 GUI frameworks like wxPython trap exceptions and call
1351 sys.excepthook themselves. I guess this is a feature that
1358 sys.excepthook themselves. I guess this is a feature that
1352 enables them to keep running after exceptions that would
1359 enables them to keep running after exceptions that would
1353 otherwise kill their mainloop. This is a bother for IPython
1360 otherwise kill their mainloop. This is a bother for IPython
1354 which excepts to catch all of the program exceptions with a try:
1361 which excepts to catch all of the program exceptions with a try:
1355 except: statement.
1362 except: statement.
1356
1363
1357 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1364 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1358 any app directly invokes sys.excepthook, it will look to the user like
1365 any app directly invokes sys.excepthook, it will look to the user like
1359 IPython crashed. In order to work around this, we can disable the
1366 IPython crashed. In order to work around this, we can disable the
1360 CrashHandler and replace it with this excepthook instead, which prints a
1367 CrashHandler and replace it with this excepthook instead, which prints a
1361 regular traceback using our InteractiveTB. In this fashion, apps which
1368 regular traceback using our InteractiveTB. In this fashion, apps which
1362 call sys.excepthook will generate a regular-looking exception from
1369 call sys.excepthook will generate a regular-looking exception from
1363 IPython, and the CrashHandler will only be triggered by real IPython
1370 IPython, and the CrashHandler will only be triggered by real IPython
1364 crashes.
1371 crashes.
1365
1372
1366 This hook should be used sparingly, only in places which are not likely
1373 This hook should be used sparingly, only in places which are not likely
1367 to be true IPython errors.
1374 to be true IPython errors.
1368 """
1375 """
1369 self.showtraceback((etype,value,tb),tb_offset=0)
1376 self.showtraceback((etype,value,tb),tb_offset=0)
1370
1377
1371 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1378 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1372 exception_only=False):
1379 exception_only=False):
1373 """Display the exception that just occurred.
1380 """Display the exception that just occurred.
1374
1381
1375 If nothing is known about the exception, this is the method which
1382 If nothing is known about the exception, this is the method which
1376 should be used throughout the code for presenting user tracebacks,
1383 should be used throughout the code for presenting user tracebacks,
1377 rather than directly invoking the InteractiveTB object.
1384 rather than directly invoking the InteractiveTB object.
1378
1385
1379 A specific showsyntaxerror() also exists, but this method can take
1386 A specific showsyntaxerror() also exists, but this method can take
1380 care of calling it if needed, so unless you are explicitly catching a
1387 care of calling it if needed, so unless you are explicitly catching a
1381 SyntaxError exception, don't try to analyze the stack manually and
1388 SyntaxError exception, don't try to analyze the stack manually and
1382 simply call this method."""
1389 simply call this method."""
1383
1390
1384 try:
1391 try:
1385 if exc_tuple is None:
1392 if exc_tuple is None:
1386 etype, value, tb = sys.exc_info()
1393 etype, value, tb = sys.exc_info()
1387 else:
1394 else:
1388 etype, value, tb = exc_tuple
1395 etype, value, tb = exc_tuple
1389
1396
1390 if etype is None:
1397 if etype is None:
1391 if hasattr(sys, 'last_type'):
1398 if hasattr(sys, 'last_type'):
1392 etype, value, tb = sys.last_type, sys.last_value, \
1399 etype, value, tb = sys.last_type, sys.last_value, \
1393 sys.last_traceback
1400 sys.last_traceback
1394 else:
1401 else:
1395 self.write_err('No traceback available to show.\n')
1402 self.write_err('No traceback available to show.\n')
1396 return
1403 return
1397
1404
1398 if etype is SyntaxError:
1405 if etype is SyntaxError:
1399 # Though this won't be called by syntax errors in the input
1406 # Though this won't be called by syntax errors in the input
1400 # line, there may be SyntaxError cases whith imported code.
1407 # line, there may be SyntaxError cases whith imported code.
1401 self.showsyntaxerror(filename)
1408 self.showsyntaxerror(filename)
1402 elif etype is UsageError:
1409 elif etype is UsageError:
1403 print "UsageError:", value
1410 print "UsageError:", value
1404 else:
1411 else:
1405 # WARNING: these variables are somewhat deprecated and not
1412 # WARNING: these variables are somewhat deprecated and not
1406 # necessarily safe to use in a threaded environment, but tools
1413 # necessarily safe to use in a threaded environment, but tools
1407 # like pdb depend on their existence, so let's set them. If we
1414 # like pdb depend on their existence, so let's set them. If we
1408 # find problems in the field, we'll need to revisit their use.
1415 # find problems in the field, we'll need to revisit their use.
1409 sys.last_type = etype
1416 sys.last_type = etype
1410 sys.last_value = value
1417 sys.last_value = value
1411 sys.last_traceback = tb
1418 sys.last_traceback = tb
1412
1419
1413 if etype in self.custom_exceptions:
1420 if etype in self.custom_exceptions:
1414 # FIXME: Old custom traceback objects may just return a
1421 # FIXME: Old custom traceback objects may just return a
1415 # string, in that case we just put it into a list
1422 # string, in that case we just put it into a list
1416 stb = self.CustomTB(etype, value, tb, tb_offset)
1423 stb = self.CustomTB(etype, value, tb, tb_offset)
1417 if isinstance(ctb, basestring):
1424 if isinstance(ctb, basestring):
1418 stb = [stb]
1425 stb = [stb]
1419 else:
1426 else:
1420 if exception_only:
1427 if exception_only:
1421 stb = ['An exception has occurred, use %tb to see '
1428 stb = ['An exception has occurred, use %tb to see '
1422 'the full traceback.\n']
1429 'the full traceback.\n']
1423 stb.extend(self.InteractiveTB.get_exception_only(etype,
1430 stb.extend(self.InteractiveTB.get_exception_only(etype,
1424 value))
1431 value))
1425 else:
1432 else:
1426 stb = self.InteractiveTB.structured_traceback(etype,
1433 stb = self.InteractiveTB.structured_traceback(etype,
1427 value, tb, tb_offset=tb_offset)
1434 value, tb, tb_offset=tb_offset)
1428 # FIXME: the pdb calling should be done by us, not by
1435 # FIXME: the pdb calling should be done by us, not by
1429 # the code computing the traceback.
1436 # the code computing the traceback.
1430 if self.InteractiveTB.call_pdb:
1437 if self.InteractiveTB.call_pdb:
1431 # pdb mucks up readline, fix it back
1438 # pdb mucks up readline, fix it back
1432 self.set_readline_completer()
1439 self.set_readline_completer()
1433
1440
1434 # Actually show the traceback
1441 # Actually show the traceback
1435 self._showtraceback(etype, value, stb)
1442 self._showtraceback(etype, value, stb)
1436
1443
1437 except KeyboardInterrupt:
1444 except KeyboardInterrupt:
1438 self.write_err("\nKeyboardInterrupt\n")
1445 self.write_err("\nKeyboardInterrupt\n")
1439
1446
1440 def _showtraceback(self, etype, evalue, stb):
1447 def _showtraceback(self, etype, evalue, stb):
1441 """Actually show a traceback.
1448 """Actually show a traceback.
1442
1449
1443 Subclasses may override this method to put the traceback on a different
1450 Subclasses may override this method to put the traceback on a different
1444 place, like a side channel.
1451 place, like a side channel.
1445 """
1452 """
1446 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1453 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1447
1454
1448 def showsyntaxerror(self, filename=None):
1455 def showsyntaxerror(self, filename=None):
1449 """Display the syntax error that just occurred.
1456 """Display the syntax error that just occurred.
1450
1457
1451 This doesn't display a stack trace because there isn't one.
1458 This doesn't display a stack trace because there isn't one.
1452
1459
1453 If a filename is given, it is stuffed in the exception instead
1460 If a filename is given, it is stuffed in the exception instead
1454 of what was there before (because Python's parser always uses
1461 of what was there before (because Python's parser always uses
1455 "<string>" when reading from a string).
1462 "<string>" when reading from a string).
1456 """
1463 """
1457 etype, value, last_traceback = sys.exc_info()
1464 etype, value, last_traceback = sys.exc_info()
1458
1465
1459 # See note about these variables in showtraceback() above
1466 # See note about these variables in showtraceback() above
1460 sys.last_type = etype
1467 sys.last_type = etype
1461 sys.last_value = value
1468 sys.last_value = value
1462 sys.last_traceback = last_traceback
1469 sys.last_traceback = last_traceback
1463
1470
1464 if filename and etype is SyntaxError:
1471 if filename and etype is SyntaxError:
1465 # Work hard to stuff the correct filename in the exception
1472 # Work hard to stuff the correct filename in the exception
1466 try:
1473 try:
1467 msg, (dummy_filename, lineno, offset, line) = value
1474 msg, (dummy_filename, lineno, offset, line) = value
1468 except:
1475 except:
1469 # Not the format we expect; leave it alone
1476 # Not the format we expect; leave it alone
1470 pass
1477 pass
1471 else:
1478 else:
1472 # Stuff in the right filename
1479 # Stuff in the right filename
1473 try:
1480 try:
1474 # Assume SyntaxError is a class exception
1481 # Assume SyntaxError is a class exception
1475 value = SyntaxError(msg, (filename, lineno, offset, line))
1482 value = SyntaxError(msg, (filename, lineno, offset, line))
1476 except:
1483 except:
1477 # If that failed, assume SyntaxError is a string
1484 # If that failed, assume SyntaxError is a string
1478 value = msg, (filename, lineno, offset, line)
1485 value = msg, (filename, lineno, offset, line)
1479 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1486 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1480 self._showtraceback(etype, value, stb)
1487 self._showtraceback(etype, value, stb)
1481
1488
1482 #-------------------------------------------------------------------------
1489 #-------------------------------------------------------------------------
1483 # Things related to readline
1490 # Things related to readline
1484 #-------------------------------------------------------------------------
1491 #-------------------------------------------------------------------------
1485
1492
1486 def init_readline(self):
1493 def init_readline(self):
1487 """Command history completion/saving/reloading."""
1494 """Command history completion/saving/reloading."""
1488
1495
1489 if self.readline_use:
1496 if self.readline_use:
1490 import IPython.utils.rlineimpl as readline
1497 import IPython.utils.rlineimpl as readline
1491
1498
1492 self.rl_next_input = None
1499 self.rl_next_input = None
1493 self.rl_do_indent = False
1500 self.rl_do_indent = False
1494
1501
1495 if not self.readline_use or not readline.have_readline:
1502 if not self.readline_use or not readline.have_readline:
1496 self.has_readline = False
1503 self.has_readline = False
1497 self.readline = None
1504 self.readline = None
1498 # Set a number of methods that depend on readline to be no-op
1505 # Set a number of methods that depend on readline to be no-op
1499 self.set_readline_completer = no_op
1506 self.set_readline_completer = no_op
1500 self.set_custom_completer = no_op
1507 self.set_custom_completer = no_op
1501 self.set_completer_frame = no_op
1508 self.set_completer_frame = no_op
1502 warn('Readline services not available or not loaded.')
1509 warn('Readline services not available or not loaded.')
1503 else:
1510 else:
1504 self.has_readline = True
1511 self.has_readline = True
1505 self.readline = readline
1512 self.readline = readline
1506 sys.modules['readline'] = readline
1513 sys.modules['readline'] = readline
1507
1514
1508 # Platform-specific configuration
1515 # Platform-specific configuration
1509 if os.name == 'nt':
1516 if os.name == 'nt':
1510 # FIXME - check with Frederick to see if we can harmonize
1517 # FIXME - check with Frederick to see if we can harmonize
1511 # naming conventions with pyreadline to avoid this
1518 # naming conventions with pyreadline to avoid this
1512 # platform-dependent check
1519 # platform-dependent check
1513 self.readline_startup_hook = readline.set_pre_input_hook
1520 self.readline_startup_hook = readline.set_pre_input_hook
1514 else:
1521 else:
1515 self.readline_startup_hook = readline.set_startup_hook
1522 self.readline_startup_hook = readline.set_startup_hook
1516
1523
1517 # Load user's initrc file (readline config)
1524 # Load user's initrc file (readline config)
1518 # Or if libedit is used, load editrc.
1525 # Or if libedit is used, load editrc.
1519 inputrc_name = os.environ.get('INPUTRC')
1526 inputrc_name = os.environ.get('INPUTRC')
1520 if inputrc_name is None:
1527 if inputrc_name is None:
1521 home_dir = get_home_dir()
1528 home_dir = get_home_dir()
1522 if home_dir is not None:
1529 if home_dir is not None:
1523 inputrc_name = '.inputrc'
1530 inputrc_name = '.inputrc'
1524 if readline.uses_libedit:
1531 if readline.uses_libedit:
1525 inputrc_name = '.editrc'
1532 inputrc_name = '.editrc'
1526 inputrc_name = os.path.join(home_dir, inputrc_name)
1533 inputrc_name = os.path.join(home_dir, inputrc_name)
1527 if os.path.isfile(inputrc_name):
1534 if os.path.isfile(inputrc_name):
1528 try:
1535 try:
1529 readline.read_init_file(inputrc_name)
1536 readline.read_init_file(inputrc_name)
1530 except:
1537 except:
1531 warn('Problems reading readline initialization file <%s>'
1538 warn('Problems reading readline initialization file <%s>'
1532 % inputrc_name)
1539 % inputrc_name)
1533
1540
1534 # Configure readline according to user's prefs
1541 # Configure readline according to user's prefs
1535 # This is only done if GNU readline is being used. If libedit
1542 # This is only done if GNU readline is being used. If libedit
1536 # is being used (as on Leopard) the readline config is
1543 # is being used (as on Leopard) the readline config is
1537 # not run as the syntax for libedit is different.
1544 # not run as the syntax for libedit is different.
1538 if not readline.uses_libedit:
1545 if not readline.uses_libedit:
1539 for rlcommand in self.readline_parse_and_bind:
1546 for rlcommand in self.readline_parse_and_bind:
1540 #print "loading rl:",rlcommand # dbg
1547 #print "loading rl:",rlcommand # dbg
1541 readline.parse_and_bind(rlcommand)
1548 readline.parse_and_bind(rlcommand)
1542
1549
1543 # Remove some chars from the delimiters list. If we encounter
1550 # Remove some chars from the delimiters list. If we encounter
1544 # unicode chars, discard them.
1551 # unicode chars, discard them.
1545 delims = readline.get_completer_delims().encode("ascii", "ignore")
1552 delims = readline.get_completer_delims().encode("ascii", "ignore")
1546 delims = delims.translate(None, self.readline_remove_delims)
1553 delims = delims.translate(None, self.readline_remove_delims)
1547 delims = delims.replace(ESC_MAGIC, '')
1554 delims = delims.replace(ESC_MAGIC, '')
1548 readline.set_completer_delims(delims)
1555 readline.set_completer_delims(delims)
1549 # otherwise we end up with a monster history after a while:
1556 # otherwise we end up with a monster history after a while:
1550 readline.set_history_length(self.history_length)
1557 readline.set_history_length(self.history_length)
1551 try:
1558 try:
1552 #print '*** Reading readline history' # dbg
1559 #print '*** Reading readline history' # dbg
1553 self.reload_history()
1560 self.reload_history()
1554 except IOError:
1561 except IOError:
1555 pass # It doesn't exist yet.
1562 pass # It doesn't exist yet.
1556
1563
1557 # Configure auto-indent for all platforms
1564 # Configure auto-indent for all platforms
1558 self.set_autoindent(self.autoindent)
1565 self.set_autoindent(self.autoindent)
1559
1566
1560 def set_next_input(self, s):
1567 def set_next_input(self, s):
1561 """ Sets the 'default' input string for the next command line.
1568 """ Sets the 'default' input string for the next command line.
1562
1569
1563 Requires readline.
1570 Requires readline.
1564
1571
1565 Example:
1572 Example:
1566
1573
1567 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1574 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1568 [D:\ipython]|2> Hello Word_ # cursor is here
1575 [D:\ipython]|2> Hello Word_ # cursor is here
1569 """
1576 """
1570
1577
1571 self.rl_next_input = s
1578 self.rl_next_input = s
1572
1579
1573 # Maybe move this to the terminal subclass?
1580 # Maybe move this to the terminal subclass?
1574 def pre_readline(self):
1581 def pre_readline(self):
1575 """readline hook to be used at the start of each line.
1582 """readline hook to be used at the start of each line.
1576
1583
1577 Currently it handles auto-indent only."""
1584 Currently it handles auto-indent only."""
1578
1585
1579 if self.rl_do_indent:
1586 if self.rl_do_indent:
1580 self.readline.insert_text(self._indent_current_str())
1587 self.readline.insert_text(self._indent_current_str())
1581 if self.rl_next_input is not None:
1588 if self.rl_next_input is not None:
1582 self.readline.insert_text(self.rl_next_input)
1589 self.readline.insert_text(self.rl_next_input)
1583 self.rl_next_input = None
1590 self.rl_next_input = None
1584
1591
1585 def _indent_current_str(self):
1592 def _indent_current_str(self):
1586 """return the current level of indentation as a string"""
1593 """return the current level of indentation as a string"""
1587 return self.input_splitter.indent_spaces * ' '
1594 return self.input_splitter.indent_spaces * ' '
1588
1595
1589 #-------------------------------------------------------------------------
1596 #-------------------------------------------------------------------------
1590 # Things related to text completion
1597 # Things related to text completion
1591 #-------------------------------------------------------------------------
1598 #-------------------------------------------------------------------------
1592
1599
1593 def init_completer(self):
1600 def init_completer(self):
1594 """Initialize the completion machinery.
1601 """Initialize the completion machinery.
1595
1602
1596 This creates completion machinery that can be used by client code,
1603 This creates completion machinery that can be used by client code,
1597 either interactively in-process (typically triggered by the readline
1604 either interactively in-process (typically triggered by the readline
1598 library), programatically (such as in test suites) or out-of-prcess
1605 library), programatically (such as in test suites) or out-of-prcess
1599 (typically over the network by remote frontends).
1606 (typically over the network by remote frontends).
1600 """
1607 """
1601 from IPython.core.completer import IPCompleter
1608 from IPython.core.completer import IPCompleter
1602 from IPython.core.completerlib import (module_completer,
1609 from IPython.core.completerlib import (module_completer,
1603 magic_run_completer, cd_completer)
1610 magic_run_completer, cd_completer)
1604
1611
1605 self.Completer = IPCompleter(self,
1612 self.Completer = IPCompleter(self,
1606 self.user_ns,
1613 self.user_ns,
1607 self.user_global_ns,
1614 self.user_global_ns,
1608 self.readline_omit__names,
1615 self.readline_omit__names,
1609 self.alias_manager.alias_table,
1616 self.alias_manager.alias_table,
1610 self.has_readline)
1617 self.has_readline)
1611
1618
1612 # Add custom completers to the basic ones built into IPCompleter
1619 # Add custom completers to the basic ones built into IPCompleter
1613 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1620 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1614 self.strdispatchers['complete_command'] = sdisp
1621 self.strdispatchers['complete_command'] = sdisp
1615 self.Completer.custom_completers = sdisp
1622 self.Completer.custom_completers = sdisp
1616
1623
1617 self.set_hook('complete_command', module_completer, str_key = 'import')
1624 self.set_hook('complete_command', module_completer, str_key = 'import')
1618 self.set_hook('complete_command', module_completer, str_key = 'from')
1625 self.set_hook('complete_command', module_completer, str_key = 'from')
1619 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1626 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1620 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1627 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1621
1628
1622 # Only configure readline if we truly are using readline. IPython can
1629 # Only configure readline if we truly are using readline. IPython can
1623 # do tab-completion over the network, in GUIs, etc, where readline
1630 # do tab-completion over the network, in GUIs, etc, where readline
1624 # itself may be absent
1631 # itself may be absent
1625 if self.has_readline:
1632 if self.has_readline:
1626 self.set_readline_completer()
1633 self.set_readline_completer()
1627
1634
1628 def complete(self, text, line=None, cursor_pos=None):
1635 def complete(self, text, line=None, cursor_pos=None):
1629 """Return the completed text and a list of completions.
1636 """Return the completed text and a list of completions.
1630
1637
1631 Parameters
1638 Parameters
1632 ----------
1639 ----------
1633
1640
1634 text : string
1641 text : string
1635 A string of text to be completed on. It can be given as empty and
1642 A string of text to be completed on. It can be given as empty and
1636 instead a line/position pair are given. In this case, the
1643 instead a line/position pair are given. In this case, the
1637 completer itself will split the line like readline does.
1644 completer itself will split the line like readline does.
1638
1645
1639 line : string, optional
1646 line : string, optional
1640 The complete line that text is part of.
1647 The complete line that text is part of.
1641
1648
1642 cursor_pos : int, optional
1649 cursor_pos : int, optional
1643 The position of the cursor on the input line.
1650 The position of the cursor on the input line.
1644
1651
1645 Returns
1652 Returns
1646 -------
1653 -------
1647 text : string
1654 text : string
1648 The actual text that was completed.
1655 The actual text that was completed.
1649
1656
1650 matches : list
1657 matches : list
1651 A sorted list with all possible completions.
1658 A sorted list with all possible completions.
1652
1659
1653 The optional arguments allow the completion to take more context into
1660 The optional arguments allow the completion to take more context into
1654 account, and are part of the low-level completion API.
1661 account, and are part of the low-level completion API.
1655
1662
1656 This is a wrapper around the completion mechanism, similar to what
1663 This is a wrapper around the completion mechanism, similar to what
1657 readline does at the command line when the TAB key is hit. By
1664 readline does at the command line when the TAB key is hit. By
1658 exposing it as a method, it can be used by other non-readline
1665 exposing it as a method, it can be used by other non-readline
1659 environments (such as GUIs) for text completion.
1666 environments (such as GUIs) for text completion.
1660
1667
1661 Simple usage example:
1668 Simple usage example:
1662
1669
1663 In [1]: x = 'hello'
1670 In [1]: x = 'hello'
1664
1671
1665 In [2]: _ip.complete('x.l')
1672 In [2]: _ip.complete('x.l')
1666 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1673 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1667 """
1674 """
1668
1675
1669 # Inject names into __builtin__ so we can complete on the added names.
1676 # Inject names into __builtin__ so we can complete on the added names.
1670 with self.builtin_trap:
1677 with self.builtin_trap:
1671 return self.Completer.complete(text, line, cursor_pos)
1678 return self.Completer.complete(text, line, cursor_pos)
1672
1679
1673 def set_custom_completer(self, completer, pos=0):
1680 def set_custom_completer(self, completer, pos=0):
1674 """Adds a new custom completer function.
1681 """Adds a new custom completer function.
1675
1682
1676 The position argument (defaults to 0) is the index in the completers
1683 The position argument (defaults to 0) is the index in the completers
1677 list where you want the completer to be inserted."""
1684 list where you want the completer to be inserted."""
1678
1685
1679 newcomp = types.MethodType(completer,self.Completer)
1686 newcomp = types.MethodType(completer,self.Completer)
1680 self.Completer.matchers.insert(pos,newcomp)
1687 self.Completer.matchers.insert(pos,newcomp)
1681
1688
1682 def set_readline_completer(self):
1689 def set_readline_completer(self):
1683 """Reset readline's completer to be our own."""
1690 """Reset readline's completer to be our own."""
1684 self.readline.set_completer(self.Completer.rlcomplete)
1691 self.readline.set_completer(self.Completer.rlcomplete)
1685
1692
1686 def set_completer_frame(self, frame=None):
1693 def set_completer_frame(self, frame=None):
1687 """Set the frame of the completer."""
1694 """Set the frame of the completer."""
1688 if frame:
1695 if frame:
1689 self.Completer.namespace = frame.f_locals
1696 self.Completer.namespace = frame.f_locals
1690 self.Completer.global_namespace = frame.f_globals
1697 self.Completer.global_namespace = frame.f_globals
1691 else:
1698 else:
1692 self.Completer.namespace = self.user_ns
1699 self.Completer.namespace = self.user_ns
1693 self.Completer.global_namespace = self.user_global_ns
1700 self.Completer.global_namespace = self.user_global_ns
1694
1701
1695 #-------------------------------------------------------------------------
1702 #-------------------------------------------------------------------------
1696 # Things related to magics
1703 # Things related to magics
1697 #-------------------------------------------------------------------------
1704 #-------------------------------------------------------------------------
1698
1705
1699 def init_magics(self):
1706 def init_magics(self):
1700 # FIXME: Move the color initialization to the DisplayHook, which
1707 # FIXME: Move the color initialization to the DisplayHook, which
1701 # should be split into a prompt manager and displayhook. We probably
1708 # should be split into a prompt manager and displayhook. We probably
1702 # even need a centralize colors management object.
1709 # even need a centralize colors management object.
1703 self.magic_colors(self.colors)
1710 self.magic_colors(self.colors)
1704 # History was moved to a separate module
1711 # History was moved to a separate module
1705 from . import history
1712 from . import history
1706 history.init_ipython(self)
1713 history.init_ipython(self)
1707
1714
1708 def magic(self,arg_s):
1715 def magic(self,arg_s):
1709 """Call a magic function by name.
1716 """Call a magic function by name.
1710
1717
1711 Input: a string containing the name of the magic function to call and
1718 Input: a string containing the name of the magic function to call and
1712 any additional arguments to be passed to the magic.
1719 any additional arguments to be passed to the magic.
1713
1720
1714 magic('name -opt foo bar') is equivalent to typing at the ipython
1721 magic('name -opt foo bar') is equivalent to typing at the ipython
1715 prompt:
1722 prompt:
1716
1723
1717 In[1]: %name -opt foo bar
1724 In[1]: %name -opt foo bar
1718
1725
1719 To call a magic without arguments, simply use magic('name').
1726 To call a magic without arguments, simply use magic('name').
1720
1727
1721 This provides a proper Python function to call IPython's magics in any
1728 This provides a proper Python function to call IPython's magics in any
1722 valid Python code you can type at the interpreter, including loops and
1729 valid Python code you can type at the interpreter, including loops and
1723 compound statements.
1730 compound statements.
1724 """
1731 """
1725 args = arg_s.split(' ',1)
1732 args = arg_s.split(' ',1)
1726 magic_name = args[0]
1733 magic_name = args[0]
1727 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1734 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1728
1735
1729 try:
1736 try:
1730 magic_args = args[1]
1737 magic_args = args[1]
1731 except IndexError:
1738 except IndexError:
1732 magic_args = ''
1739 magic_args = ''
1733 fn = getattr(self,'magic_'+magic_name,None)
1740 fn = getattr(self,'magic_'+magic_name,None)
1734 if fn is None:
1741 if fn is None:
1735 error("Magic function `%s` not found." % magic_name)
1742 error("Magic function `%s` not found." % magic_name)
1736 else:
1743 else:
1737 magic_args = self.var_expand(magic_args,1)
1744 magic_args = self.var_expand(magic_args,1)
1738 with nested(self.builtin_trap,):
1745 with nested(self.builtin_trap,):
1739 result = fn(magic_args)
1746 result = fn(magic_args)
1740 return result
1747 return result
1741
1748
1742 def define_magic(self, magicname, func):
1749 def define_magic(self, magicname, func):
1743 """Expose own function as magic function for ipython
1750 """Expose own function as magic function for ipython
1744
1751
1745 def foo_impl(self,parameter_s=''):
1752 def foo_impl(self,parameter_s=''):
1746 'My very own magic!. (Use docstrings, IPython reads them).'
1753 'My very own magic!. (Use docstrings, IPython reads them).'
1747 print 'Magic function. Passed parameter is between < >:'
1754 print 'Magic function. Passed parameter is between < >:'
1748 print '<%s>' % parameter_s
1755 print '<%s>' % parameter_s
1749 print 'The self object is:',self
1756 print 'The self object is:',self
1750
1757
1751 self.define_magic('foo',foo_impl)
1758 self.define_magic('foo',foo_impl)
1752 """
1759 """
1753
1760
1754 import new
1761 import new
1755 im = types.MethodType(func,self)
1762 im = types.MethodType(func,self)
1756 old = getattr(self, "magic_" + magicname, None)
1763 old = getattr(self, "magic_" + magicname, None)
1757 setattr(self, "magic_" + magicname, im)
1764 setattr(self, "magic_" + magicname, im)
1758 return old
1765 return old
1759
1766
1760 #-------------------------------------------------------------------------
1767 #-------------------------------------------------------------------------
1761 # Things related to macros
1768 # Things related to macros
1762 #-------------------------------------------------------------------------
1769 #-------------------------------------------------------------------------
1763
1770
1764 def define_macro(self, name, themacro):
1771 def define_macro(self, name, themacro):
1765 """Define a new macro
1772 """Define a new macro
1766
1773
1767 Parameters
1774 Parameters
1768 ----------
1775 ----------
1769 name : str
1776 name : str
1770 The name of the macro.
1777 The name of the macro.
1771 themacro : str or Macro
1778 themacro : str or Macro
1772 The action to do upon invoking the macro. If a string, a new
1779 The action to do upon invoking the macro. If a string, a new
1773 Macro object is created by passing the string to it.
1780 Macro object is created by passing the string to it.
1774 """
1781 """
1775
1782
1776 from IPython.core import macro
1783 from IPython.core import macro
1777
1784
1778 if isinstance(themacro, basestring):
1785 if isinstance(themacro, basestring):
1779 themacro = macro.Macro(themacro)
1786 themacro = macro.Macro(themacro)
1780 if not isinstance(themacro, macro.Macro):
1787 if not isinstance(themacro, macro.Macro):
1781 raise ValueError('A macro must be a string or a Macro instance.')
1788 raise ValueError('A macro must be a string or a Macro instance.')
1782 self.user_ns[name] = themacro
1789 self.user_ns[name] = themacro
1783
1790
1784 #-------------------------------------------------------------------------
1791 #-------------------------------------------------------------------------
1785 # Things related to the running of system commands
1792 # Things related to the running of system commands
1786 #-------------------------------------------------------------------------
1793 #-------------------------------------------------------------------------
1787
1794
1788 def system(self, cmd):
1795 def system(self, cmd):
1789 """Call the given cmd in a subprocess.
1796 """Call the given cmd in a subprocess.
1790
1797
1791 Parameters
1798 Parameters
1792 ----------
1799 ----------
1793 cmd : str
1800 cmd : str
1794 Command to execute (can not end in '&', as bacground processes are
1801 Command to execute (can not end in '&', as bacground processes are
1795 not supported.
1802 not supported.
1796 """
1803 """
1797 # We do not support backgrounding processes because we either use
1804 # We do not support backgrounding processes because we either use
1798 # pexpect or pipes to read from. Users can always just call
1805 # pexpect or pipes to read from. Users can always just call
1799 # os.system() if they really want a background process.
1806 # os.system() if they really want a background process.
1800 if cmd.endswith('&'):
1807 if cmd.endswith('&'):
1801 raise OSError("Background processes not supported.")
1808 raise OSError("Background processes not supported.")
1802
1809
1803 return system(self.var_expand(cmd, depth=2))
1810 return system(self.var_expand(cmd, depth=2))
1804
1811
1805 def getoutput(self, cmd, split=True):
1812 def getoutput(self, cmd, split=True):
1806 """Get output (possibly including stderr) from a subprocess.
1813 """Get output (possibly including stderr) from a subprocess.
1807
1814
1808 Parameters
1815 Parameters
1809 ----------
1816 ----------
1810 cmd : str
1817 cmd : str
1811 Command to execute (can not end in '&', as background processes are
1818 Command to execute (can not end in '&', as background processes are
1812 not supported.
1819 not supported.
1813 split : bool, optional
1820 split : bool, optional
1814
1821
1815 If True, split the output into an IPython SList. Otherwise, an
1822 If True, split the output into an IPython SList. Otherwise, an
1816 IPython LSString is returned. These are objects similar to normal
1823 IPython LSString is returned. These are objects similar to normal
1817 lists and strings, with a few convenience attributes for easier
1824 lists and strings, with a few convenience attributes for easier
1818 manipulation of line-based output. You can use '?' on them for
1825 manipulation of line-based output. You can use '?' on them for
1819 details.
1826 details.
1820 """
1827 """
1821 if cmd.endswith('&'):
1828 if cmd.endswith('&'):
1822 raise OSError("Background processes not supported.")
1829 raise OSError("Background processes not supported.")
1823 out = getoutput(self.var_expand(cmd, depth=2))
1830 out = getoutput(self.var_expand(cmd, depth=2))
1824 if split:
1831 if split:
1825 out = SList(out.splitlines())
1832 out = SList(out.splitlines())
1826 else:
1833 else:
1827 out = LSString(out)
1834 out = LSString(out)
1828 return out
1835 return out
1829
1836
1830 #-------------------------------------------------------------------------
1837 #-------------------------------------------------------------------------
1831 # Things related to aliases
1838 # Things related to aliases
1832 #-------------------------------------------------------------------------
1839 #-------------------------------------------------------------------------
1833
1840
1834 def init_alias(self):
1841 def init_alias(self):
1835 self.alias_manager = AliasManager(shell=self, config=self.config)
1842 self.alias_manager = AliasManager(shell=self, config=self.config)
1836 self.ns_table['alias'] = self.alias_manager.alias_table,
1843 self.ns_table['alias'] = self.alias_manager.alias_table,
1837
1844
1838 #-------------------------------------------------------------------------
1845 #-------------------------------------------------------------------------
1839 # Things related to extensions and plugins
1846 # Things related to extensions and plugins
1840 #-------------------------------------------------------------------------
1847 #-------------------------------------------------------------------------
1841
1848
1842 def init_extension_manager(self):
1849 def init_extension_manager(self):
1843 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1850 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1844
1851
1845 def init_plugin_manager(self):
1852 def init_plugin_manager(self):
1846 self.plugin_manager = PluginManager(config=self.config)
1853 self.plugin_manager = PluginManager(config=self.config)
1847
1854
1848 #-------------------------------------------------------------------------
1855 #-------------------------------------------------------------------------
1849 # Things related to payloads
1856 # Things related to payloads
1850 #-------------------------------------------------------------------------
1857 #-------------------------------------------------------------------------
1851
1858
1852 def init_payload(self):
1859 def init_payload(self):
1853 self.payload_manager = PayloadManager(config=self.config)
1860 self.payload_manager = PayloadManager(config=self.config)
1854
1861
1855 #-------------------------------------------------------------------------
1862 #-------------------------------------------------------------------------
1856 # Things related to the prefilter
1863 # Things related to the prefilter
1857 #-------------------------------------------------------------------------
1864 #-------------------------------------------------------------------------
1858
1865
1859 def init_prefilter(self):
1866 def init_prefilter(self):
1860 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1867 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1861 # Ultimately this will be refactored in the new interpreter code, but
1868 # Ultimately this will be refactored in the new interpreter code, but
1862 # for now, we should expose the main prefilter method (there's legacy
1869 # for now, we should expose the main prefilter method (there's legacy
1863 # code out there that may rely on this).
1870 # code out there that may rely on this).
1864 self.prefilter = self.prefilter_manager.prefilter_lines
1871 self.prefilter = self.prefilter_manager.prefilter_lines
1865
1872
1866 def auto_rewrite_input(self, cmd):
1873 def auto_rewrite_input(self, cmd):
1867 """Print to the screen the rewritten form of the user's command.
1874 """Print to the screen the rewritten form of the user's command.
1868
1875
1869 This shows visual feedback by rewriting input lines that cause
1876 This shows visual feedback by rewriting input lines that cause
1870 automatic calling to kick in, like::
1877 automatic calling to kick in, like::
1871
1878
1872 /f x
1879 /f x
1873
1880
1874 into::
1881 into::
1875
1882
1876 ------> f(x)
1883 ------> f(x)
1877
1884
1878 after the user's input prompt. This helps the user understand that the
1885 after the user's input prompt. This helps the user understand that the
1879 input line was transformed automatically by IPython.
1886 input line was transformed automatically by IPython.
1880 """
1887 """
1881 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1888 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1882
1889
1883 try:
1890 try:
1884 # plain ascii works better w/ pyreadline, on some machines, so
1891 # plain ascii works better w/ pyreadline, on some machines, so
1885 # we use it and only print uncolored rewrite if we have unicode
1892 # we use it and only print uncolored rewrite if we have unicode
1886 rw = str(rw)
1893 rw = str(rw)
1887 print >> IPython.utils.io.Term.cout, rw
1894 print >> IPython.utils.io.Term.cout, rw
1888 except UnicodeEncodeError:
1895 except UnicodeEncodeError:
1889 print "------> " + cmd
1896 print "------> " + cmd
1890
1897
1891 #-------------------------------------------------------------------------
1898 #-------------------------------------------------------------------------
1892 # Things related to extracting values/expressions from kernel and user_ns
1899 # Things related to extracting values/expressions from kernel and user_ns
1893 #-------------------------------------------------------------------------
1900 #-------------------------------------------------------------------------
1894
1901
1895 def _simple_error(self):
1902 def _simple_error(self):
1896 etype, value = sys.exc_info()[:2]
1903 etype, value = sys.exc_info()[:2]
1897 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1904 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1898
1905
1899 def user_variables(self, names):
1906 def user_variables(self, names):
1900 """Get a list of variable names from the user's namespace.
1907 """Get a list of variable names from the user's namespace.
1901
1908
1902 Parameters
1909 Parameters
1903 ----------
1910 ----------
1904 names : list of strings
1911 names : list of strings
1905 A list of names of variables to be read from the user namespace.
1912 A list of names of variables to be read from the user namespace.
1906
1913
1907 Returns
1914 Returns
1908 -------
1915 -------
1909 A dict, keyed by the input names and with the repr() of each value.
1916 A dict, keyed by the input names and with the repr() of each value.
1910 """
1917 """
1911 out = {}
1918 out = {}
1912 user_ns = self.user_ns
1919 user_ns = self.user_ns
1913 for varname in names:
1920 for varname in names:
1914 try:
1921 try:
1915 value = repr(user_ns[varname])
1922 value = repr(user_ns[varname])
1916 except:
1923 except:
1917 value = self._simple_error()
1924 value = self._simple_error()
1918 out[varname] = value
1925 out[varname] = value
1919 return out
1926 return out
1920
1927
1921 def user_expressions(self, expressions):
1928 def user_expressions(self, expressions):
1922 """Evaluate a dict of expressions in the user's namespace.
1929 """Evaluate a dict of expressions in the user's namespace.
1923
1930
1924 Parameters
1931 Parameters
1925 ----------
1932 ----------
1926 expressions : dict
1933 expressions : dict
1927 A dict with string keys and string values. The expression values
1934 A dict with string keys and string values. The expression values
1928 should be valid Python expressions, each of which will be evaluated
1935 should be valid Python expressions, each of which will be evaluated
1929 in the user namespace.
1936 in the user namespace.
1930
1937
1931 Returns
1938 Returns
1932 -------
1939 -------
1933 A dict, keyed like the input expressions dict, with the repr() of each
1940 A dict, keyed like the input expressions dict, with the repr() of each
1934 value.
1941 value.
1935 """
1942 """
1936 out = {}
1943 out = {}
1937 user_ns = self.user_ns
1944 user_ns = self.user_ns
1938 global_ns = self.user_global_ns
1945 global_ns = self.user_global_ns
1939 for key, expr in expressions.iteritems():
1946 for key, expr in expressions.iteritems():
1940 try:
1947 try:
1941 value = repr(eval(expr, global_ns, user_ns))
1948 value = repr(eval(expr, global_ns, user_ns))
1942 except:
1949 except:
1943 value = self._simple_error()
1950 value = self._simple_error()
1944 out[key] = value
1951 out[key] = value
1945 return out
1952 return out
1946
1953
1947 #-------------------------------------------------------------------------
1954 #-------------------------------------------------------------------------
1948 # Things related to the running of code
1955 # Things related to the running of code
1949 #-------------------------------------------------------------------------
1956 #-------------------------------------------------------------------------
1950
1957
1951 def ex(self, cmd):
1958 def ex(self, cmd):
1952 """Execute a normal python statement in user namespace."""
1959 """Execute a normal python statement in user namespace."""
1953 with nested(self.builtin_trap,):
1960 with nested(self.builtin_trap,):
1954 exec cmd in self.user_global_ns, self.user_ns
1961 exec cmd in self.user_global_ns, self.user_ns
1955
1962
1956 def ev(self, expr):
1963 def ev(self, expr):
1957 """Evaluate python expression expr in user namespace.
1964 """Evaluate python expression expr in user namespace.
1958
1965
1959 Returns the result of evaluation
1966 Returns the result of evaluation
1960 """
1967 """
1961 with nested(self.builtin_trap,):
1968 with nested(self.builtin_trap,):
1962 return eval(expr, self.user_global_ns, self.user_ns)
1969 return eval(expr, self.user_global_ns, self.user_ns)
1963
1970
1964 def safe_execfile(self, fname, *where, **kw):
1971 def safe_execfile(self, fname, *where, **kw):
1965 """A safe version of the builtin execfile().
1972 """A safe version of the builtin execfile().
1966
1973
1967 This version will never throw an exception, but instead print
1974 This version will never throw an exception, but instead print
1968 helpful error messages to the screen. This only works on pure
1975 helpful error messages to the screen. This only works on pure
1969 Python files with the .py extension.
1976 Python files with the .py extension.
1970
1977
1971 Parameters
1978 Parameters
1972 ----------
1979 ----------
1973 fname : string
1980 fname : string
1974 The name of the file to be executed.
1981 The name of the file to be executed.
1975 where : tuple
1982 where : tuple
1976 One or two namespaces, passed to execfile() as (globals,locals).
1983 One or two namespaces, passed to execfile() as (globals,locals).
1977 If only one is given, it is passed as both.
1984 If only one is given, it is passed as both.
1978 exit_ignore : bool (False)
1985 exit_ignore : bool (False)
1979 If True, then silence SystemExit for non-zero status (it is always
1986 If True, then silence SystemExit for non-zero status (it is always
1980 silenced for zero status, as it is so common).
1987 silenced for zero status, as it is so common).
1981 """
1988 """
1982 kw.setdefault('exit_ignore', False)
1989 kw.setdefault('exit_ignore', False)
1983
1990
1984 fname = os.path.abspath(os.path.expanduser(fname))
1991 fname = os.path.abspath(os.path.expanduser(fname))
1985
1992
1986 # Make sure we have a .py file
1993 # Make sure we have a .py file
1987 if not fname.endswith('.py'):
1994 if not fname.endswith('.py'):
1988 warn('File must end with .py to be run using execfile: <%s>' % fname)
1995 warn('File must end with .py to be run using execfile: <%s>' % fname)
1989
1996
1990 # Make sure we can open the file
1997 # Make sure we can open the file
1991 try:
1998 try:
1992 with open(fname) as thefile:
1999 with open(fname) as thefile:
1993 pass
2000 pass
1994 except:
2001 except:
1995 warn('Could not open file <%s> for safe execution.' % fname)
2002 warn('Could not open file <%s> for safe execution.' % fname)
1996 return
2003 return
1997
2004
1998 # Find things also in current directory. This is needed to mimic the
2005 # Find things also in current directory. This is needed to mimic the
1999 # behavior of running a script from the system command line, where
2006 # behavior of running a script from the system command line, where
2000 # Python inserts the script's directory into sys.path
2007 # Python inserts the script's directory into sys.path
2001 dname = os.path.dirname(fname)
2008 dname = os.path.dirname(fname)
2002
2009
2003 with prepended_to_syspath(dname):
2010 with prepended_to_syspath(dname):
2004 try:
2011 try:
2005 execfile(fname,*where)
2012 execfile(fname,*where)
2006 except SystemExit, status:
2013 except SystemExit, status:
2007 # If the call was made with 0 or None exit status (sys.exit(0)
2014 # If the call was made with 0 or None exit status (sys.exit(0)
2008 # or sys.exit() ), don't bother showing a traceback, as both of
2015 # or sys.exit() ), don't bother showing a traceback, as both of
2009 # these are considered normal by the OS:
2016 # these are considered normal by the OS:
2010 # > python -c'import sys;sys.exit(0)'; echo $?
2017 # > python -c'import sys;sys.exit(0)'; echo $?
2011 # 0
2018 # 0
2012 # > python -c'import sys;sys.exit()'; echo $?
2019 # > python -c'import sys;sys.exit()'; echo $?
2013 # 0
2020 # 0
2014 # For other exit status, we show the exception unless
2021 # For other exit status, we show the exception unless
2015 # explicitly silenced, but only in short form.
2022 # explicitly silenced, but only in short form.
2016 if status.code not in (0, None) and not kw['exit_ignore']:
2023 if status.code not in (0, None) and not kw['exit_ignore']:
2017 self.showtraceback(exception_only=True)
2024 self.showtraceback(exception_only=True)
2018 except:
2025 except:
2019 self.showtraceback()
2026 self.showtraceback()
2020
2027
2021 def safe_execfile_ipy(self, fname):
2028 def safe_execfile_ipy(self, fname):
2022 """Like safe_execfile, but for .ipy files with IPython syntax.
2029 """Like safe_execfile, but for .ipy files with IPython syntax.
2023
2030
2024 Parameters
2031 Parameters
2025 ----------
2032 ----------
2026 fname : str
2033 fname : str
2027 The name of the file to execute. The filename must have a
2034 The name of the file to execute. The filename must have a
2028 .ipy extension.
2035 .ipy extension.
2029 """
2036 """
2030 fname = os.path.abspath(os.path.expanduser(fname))
2037 fname = os.path.abspath(os.path.expanduser(fname))
2031
2038
2032 # Make sure we have a .py file
2039 # Make sure we have a .py file
2033 if not fname.endswith('.ipy'):
2040 if not fname.endswith('.ipy'):
2034 warn('File must end with .py to be run using execfile: <%s>' % fname)
2041 warn('File must end with .py to be run using execfile: <%s>' % fname)
2035
2042
2036 # Make sure we can open the file
2043 # Make sure we can open the file
2037 try:
2044 try:
2038 with open(fname) as thefile:
2045 with open(fname) as thefile:
2039 pass
2046 pass
2040 except:
2047 except:
2041 warn('Could not open file <%s> for safe execution.' % fname)
2048 warn('Could not open file <%s> for safe execution.' % fname)
2042 return
2049 return
2043
2050
2044 # Find things also in current directory. This is needed to mimic the
2051 # Find things also in current directory. This is needed to mimic the
2045 # behavior of running a script from the system command line, where
2052 # behavior of running a script from the system command line, where
2046 # Python inserts the script's directory into sys.path
2053 # Python inserts the script's directory into sys.path
2047 dname = os.path.dirname(fname)
2054 dname = os.path.dirname(fname)
2048
2055
2049 with prepended_to_syspath(dname):
2056 with prepended_to_syspath(dname):
2050 try:
2057 try:
2051 with open(fname) as thefile:
2058 with open(fname) as thefile:
2052 # self.run_cell currently captures all exceptions
2059 # self.run_cell currently captures all exceptions
2053 # raised in user code. It would be nice if there were
2060 # raised in user code. It would be nice if there were
2054 # versions of runlines, execfile that did raise, so
2061 # versions of runlines, execfile that did raise, so
2055 # we could catch the errors.
2062 # we could catch the errors.
2056 self.run_cell(thefile.read())
2063 self.run_cell(thefile.read())
2057 except:
2064 except:
2058 self.showtraceback()
2065 self.showtraceback()
2059 warn('Unknown failure executing file: <%s>' % fname)
2066 warn('Unknown failure executing file: <%s>' % fname)
2060
2067
2061 def run_cell(self, cell):
2068 def run_cell(self, cell):
2062 """Run the contents of an entire multiline 'cell' of code.
2069 """Run the contents of an entire multiline 'cell' of code.
2063
2070
2064 The cell is split into separate blocks which can be executed
2071 The cell is split into separate blocks which can be executed
2065 individually. Then, based on how many blocks there are, they are
2072 individually. Then, based on how many blocks there are, they are
2066 executed as follows:
2073 executed as follows:
2067
2074
2068 - A single block: 'single' mode.
2075 - A single block: 'single' mode.
2069
2076
2070 If there's more than one block, it depends:
2077 If there's more than one block, it depends:
2071
2078
2072 - if the last one is no more than two lines long, run all but the last
2079 - if the last one is no more than two lines long, run all but the last
2073 in 'exec' mode and the very last one in 'single' mode. This makes it
2080 in 'exec' mode and the very last one in 'single' mode. This makes it
2074 easy to type simple expressions at the end to see computed values. -
2081 easy to type simple expressions at the end to see computed values. -
2075 otherwise (last one is also multiline), run all in 'exec' mode
2082 otherwise (last one is also multiline), run all in 'exec' mode
2076
2083
2077 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2084 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2078 results are displayed and output prompts are computed. In 'exec' mode,
2085 results are displayed and output prompts are computed. In 'exec' mode,
2079 no results are displayed unless :func:`print` is called explicitly;
2086 no results are displayed unless :func:`print` is called explicitly;
2080 this mode is more akin to running a script.
2087 this mode is more akin to running a script.
2081
2088
2082 Parameters
2089 Parameters
2083 ----------
2090 ----------
2084 cell : str
2091 cell : str
2085 A single or multiline string.
2092 A single or multiline string.
2086 """
2093 """
2087
2094
2088 # We need to break up the input into executable blocks that can be run
2095 # We need to break up the input into executable blocks that can be run
2089 # in 'single' mode, to provide comfortable user behavior.
2096 # in 'single' mode, to provide comfortable user behavior.
2090 blocks = self.input_splitter.split_blocks(cell)
2097 blocks = self.input_splitter.split_blocks(cell)
2091
2098
2092 if not blocks:
2099 if not blocks:
2093 return
2100 return
2094
2101
2095 # Store the 'ipython' version of the cell as well, since that's what
2102 # Store the 'ipython' version of the cell as well, since that's what
2096 # needs to go into the translated history and get executed (the
2103 # needs to go into the translated history and get executed (the
2097 # original cell may contain non-python syntax).
2104 # original cell may contain non-python syntax).
2098 ipy_cell = ''.join(blocks)
2105 ipy_cell = ''.join(blocks)
2099
2106
2100 # Store raw and processed history
2107 # Store raw and processed history
2101 self.history_manager.store_inputs(ipy_cell, cell)
2108 self.history_manager.store_inputs(ipy_cell, cell)
2102
2109
2103 self.logger.log(ipy_cell, cell)
2110 self.logger.log(ipy_cell, cell)
2104 # dbg code!!!
2111 # dbg code!!!
2105 if 0:
2112 if 0:
2106 def myapp(self, val): # dbg
2113 def myapp(self, val): # dbg
2107 import traceback as tb
2114 import traceback as tb
2108 stack = ''.join(tb.format_stack())
2115 stack = ''.join(tb.format_stack())
2109 print 'Value:', val
2116 print 'Value:', val
2110 print 'Stack:\n', stack
2117 print 'Stack:\n', stack
2111 list.append(self, val)
2118 list.append(self, val)
2112
2119
2113 import new
2120 import new
2114 self.history_manager.input_hist_parsed.append = types.MethodType(myapp,
2121 self.history_manager.input_hist_parsed.append = types.MethodType(myapp,
2115 self.history_manager.input_hist_parsed)
2122 self.history_manager.input_hist_parsed)
2116 # End dbg
2123 # End dbg
2117
2124
2118 # All user code execution must happen with our context managers active
2125 # All user code execution must happen with our context managers active
2119 with nested(self.builtin_trap, self.display_trap):
2126 with nested(self.builtin_trap, self.display_trap):
2120
2127
2121 # Single-block input should behave like an interactive prompt
2128 # Single-block input should behave like an interactive prompt
2122 if len(blocks) == 1:
2129 if len(blocks) == 1:
2123 # since we return here, we need to update the execution count
2130 # since we return here, we need to update the execution count
2124 out = self.run_one_block(blocks[0])
2131 out = self.run_one_block(blocks[0])
2125 self.execution_count += 1
2132 self.execution_count += 1
2126 return out
2133 return out
2127
2134
2128 # In multi-block input, if the last block is a simple (one-two
2135 # In multi-block input, if the last block is a simple (one-two
2129 # lines) expression, run it in single mode so it produces output.
2136 # lines) expression, run it in single mode so it produces output.
2130 # Otherwise just feed the whole thing to run_code. This seems like
2137 # Otherwise just feed the whole thing to run_code. This seems like
2131 # a reasonable usability design.
2138 # a reasonable usability design.
2132 last = blocks[-1]
2139 last = blocks[-1]
2133 last_nlines = len(last.splitlines())
2140 last_nlines = len(last.splitlines())
2134
2141
2135 # Note: below, whenever we call run_code, we must sync history
2142 # Note: below, whenever we call run_code, we must sync history
2136 # ourselves, because run_code is NOT meant to manage history at all.
2143 # ourselves, because run_code is NOT meant to manage history at all.
2137 if last_nlines < 2:
2144 if last_nlines < 2:
2138 # Here we consider the cell split between 'body' and 'last',
2145 # Here we consider the cell split between 'body' and 'last',
2139 # store all history and execute 'body', and if successful, then
2146 # store all history and execute 'body', and if successful, then
2140 # proceed to execute 'last'.
2147 # proceed to execute 'last'.
2141
2148
2142 # Get the main body to run as a cell
2149 # Get the main body to run as a cell
2143 ipy_body = ''.join(blocks[:-1])
2150 ipy_body = ''.join(blocks[:-1])
2144 retcode = self.run_source(ipy_body, symbol='exec',
2151 retcode = self.run_source(ipy_body, symbol='exec',
2145 post_execute=False)
2152 post_execute=False)
2146 if retcode==0:
2153 if retcode==0:
2147 # And the last expression via runlines so it produces output
2154 # And the last expression via runlines so it produces output
2148 self.run_one_block(last)
2155 self.run_one_block(last)
2149 else:
2156 else:
2150 # Run the whole cell as one entity, storing both raw and
2157 # Run the whole cell as one entity, storing both raw and
2151 # processed input in history
2158 # processed input in history
2152 self.run_source(ipy_cell, symbol='exec')
2159 self.run_source(ipy_cell, symbol='exec')
2153
2160
2154 # Each cell is a *single* input, regardless of how many lines it has
2161 # Each cell is a *single* input, regardless of how many lines it has
2155 self.execution_count += 1
2162 self.execution_count += 1
2156
2163
2157 def run_one_block(self, block):
2164 def run_one_block(self, block):
2158 """Run a single interactive block.
2165 """Run a single interactive block.
2159
2166
2160 If the block is single-line, dynamic transformations are applied to it
2167 If the block is single-line, dynamic transformations are applied to it
2161 (like automagics, autocall and alias recognition).
2168 (like automagics, autocall and alias recognition).
2162 """
2169 """
2163 if len(block.splitlines()) <= 1:
2170 if len(block.splitlines()) <= 1:
2164 out = self.run_single_line(block)
2171 out = self.run_single_line(block)
2165 else:
2172 else:
2166 out = self.run_code(block)
2173 out = self.run_code(block)
2167 return out
2174 return out
2168
2175
2169 def run_single_line(self, line):
2176 def run_single_line(self, line):
2170 """Run a single-line interactive statement.
2177 """Run a single-line interactive statement.
2171
2178
2172 This assumes the input has been transformed to IPython syntax by
2179 This assumes the input has been transformed to IPython syntax by
2173 applying all static transformations (those with an explicit prefix like
2180 applying all static transformations (those with an explicit prefix like
2174 % or !), but it will further try to apply the dynamic ones.
2181 % or !), but it will further try to apply the dynamic ones.
2175
2182
2176 It does not update history.
2183 It does not update history.
2177 """
2184 """
2178 tline = self.prefilter_manager.prefilter_line(line)
2185 tline = self.prefilter_manager.prefilter_line(line)
2179 return self.run_source(tline)
2186 return self.run_source(tline)
2180
2187
2181 # PENDING REMOVAL: this method is slated for deletion, once our new
2188 # PENDING REMOVAL: this method is slated for deletion, once our new
2182 # input logic has been 100% moved to frontends and is stable.
2189 # input logic has been 100% moved to frontends and is stable.
2183 def runlines(self, lines, clean=False):
2190 def runlines(self, lines, clean=False):
2184 """Run a string of one or more lines of source.
2191 """Run a string of one or more lines of source.
2185
2192
2186 This method is capable of running a string containing multiple source
2193 This method is capable of running a string containing multiple source
2187 lines, as if they had been entered at the IPython prompt. Since it
2194 lines, as if they had been entered at the IPython prompt. Since it
2188 exposes IPython's processing machinery, the given strings can contain
2195 exposes IPython's processing machinery, the given strings can contain
2189 magic calls (%magic), special shell access (!cmd), etc.
2196 magic calls (%magic), special shell access (!cmd), etc.
2190 """
2197 """
2191
2198
2192 if isinstance(lines, (list, tuple)):
2199 if isinstance(lines, (list, tuple)):
2193 lines = '\n'.join(lines)
2200 lines = '\n'.join(lines)
2194
2201
2195 if clean:
2202 if clean:
2196 lines = self._cleanup_ipy_script(lines)
2203 lines = self._cleanup_ipy_script(lines)
2197
2204
2198 # We must start with a clean buffer, in case this is run from an
2205 # We must start with a clean buffer, in case this is run from an
2199 # interactive IPython session (via a magic, for example).
2206 # interactive IPython session (via a magic, for example).
2200 self.reset_buffer()
2207 self.reset_buffer()
2201 lines = lines.splitlines()
2208 lines = lines.splitlines()
2202
2209
2203 # Since we will prefilter all lines, store the user's raw input too
2210 # Since we will prefilter all lines, store the user's raw input too
2204 # before we apply any transformations
2211 # before we apply any transformations
2205 self.buffer_raw[:] = [ l+'\n' for l in lines]
2212 self.buffer_raw[:] = [ l+'\n' for l in lines]
2206
2213
2207 more = False
2214 more = False
2208 prefilter_lines = self.prefilter_manager.prefilter_lines
2215 prefilter_lines = self.prefilter_manager.prefilter_lines
2209 with nested(self.builtin_trap, self.display_trap):
2216 with nested(self.builtin_trap, self.display_trap):
2210 for line in lines:
2217 for line in lines:
2211 # skip blank lines so we don't mess up the prompt counter, but
2218 # skip blank lines so we don't mess up the prompt counter, but
2212 # do NOT skip even a blank line if we are in a code block (more
2219 # do NOT skip even a blank line if we are in a code block (more
2213 # is true)
2220 # is true)
2214
2221
2215 if line or more:
2222 if line or more:
2216 more = self.push_line(prefilter_lines(line, more))
2223 more = self.push_line(prefilter_lines(line, more))
2217 # IPython's run_source returns None if there was an error
2224 # IPython's run_source returns None if there was an error
2218 # compiling the code. This allows us to stop processing
2225 # compiling the code. This allows us to stop processing
2219 # right away, so the user gets the error message at the
2226 # right away, so the user gets the error message at the
2220 # right place.
2227 # right place.
2221 if more is None:
2228 if more is None:
2222 break
2229 break
2223 # final newline in case the input didn't have it, so that the code
2230 # final newline in case the input didn't have it, so that the code
2224 # actually does get executed
2231 # actually does get executed
2225 if more:
2232 if more:
2226 self.push_line('\n')
2233 self.push_line('\n')
2227
2234
2228 def run_source(self, source, filename=None,
2235 def run_source(self, source, filename=None,
2229 symbol='single', post_execute=True):
2236 symbol='single', post_execute=True):
2230 """Compile and run some source in the interpreter.
2237 """Compile and run some source in the interpreter.
2231
2238
2232 Arguments are as for compile_command().
2239 Arguments are as for compile_command().
2233
2240
2234 One several things can happen:
2241 One several things can happen:
2235
2242
2236 1) The input is incorrect; compile_command() raised an
2243 1) The input is incorrect; compile_command() raised an
2237 exception (SyntaxError or OverflowError). A syntax traceback
2244 exception (SyntaxError or OverflowError). A syntax traceback
2238 will be printed by calling the showsyntaxerror() method.
2245 will be printed by calling the showsyntaxerror() method.
2239
2246
2240 2) The input is incomplete, and more input is required;
2247 2) The input is incomplete, and more input is required;
2241 compile_command() returned None. Nothing happens.
2248 compile_command() returned None. Nothing happens.
2242
2249
2243 3) The input is complete; compile_command() returned a code
2250 3) The input is complete; compile_command() returned a code
2244 object. The code is executed by calling self.run_code() (which
2251 object. The code is executed by calling self.run_code() (which
2245 also handles run-time exceptions, except for SystemExit).
2252 also handles run-time exceptions, except for SystemExit).
2246
2253
2247 The return value is:
2254 The return value is:
2248
2255
2249 - True in case 2
2256 - True in case 2
2250
2257
2251 - False in the other cases, unless an exception is raised, where
2258 - False in the other cases, unless an exception is raised, where
2252 None is returned instead. This can be used by external callers to
2259 None is returned instead. This can be used by external callers to
2253 know whether to continue feeding input or not.
2260 know whether to continue feeding input or not.
2254
2261
2255 The return value can be used to decide whether to use sys.ps1 or
2262 The return value can be used to decide whether to use sys.ps1 or
2256 sys.ps2 to prompt the next line."""
2263 sys.ps2 to prompt the next line."""
2257
2264
2258 # We need to ensure that the source is unicode from here on.
2265 # We need to ensure that the source is unicode from here on.
2259 if type(source)==str:
2266 if type(source)==str:
2260 usource = source.decode(self.stdin_encoding)
2267 usource = source.decode(self.stdin_encoding)
2261 else:
2268 else:
2262 usource = source
2269 usource = source
2263
2270
2264 if 0: # dbg
2271 if 0: # dbg
2265 print 'Source:', repr(source) # dbg
2272 print 'Source:', repr(source) # dbg
2266 print 'USource:', repr(usource) # dbg
2273 print 'USource:', repr(usource) # dbg
2267 print 'type:', type(source) # dbg
2274 print 'type:', type(source) # dbg
2268 print 'encoding', self.stdin_encoding # dbg
2275 print 'encoding', self.stdin_encoding # dbg
2269
2276
2270 try:
2277 try:
2271 code = self.compile(usource, symbol, self.execution_count)
2278 code = self.compile(usource, symbol, self.execution_count)
2272 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2279 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2273 # Case 1
2280 # Case 1
2274 self.showsyntaxerror(filename)
2281 self.showsyntaxerror(filename)
2275 return None
2282 return None
2276
2283
2277 if code is None:
2284 if code is None:
2278 # Case 2
2285 # Case 2
2279 return True
2286 return True
2280
2287
2281 # Case 3
2288 # Case 3
2282 # We store the code object so that threaded shells and
2289 # We store the code object so that threaded shells and
2283 # custom exception handlers can access all this info if needed.
2290 # custom exception handlers can access all this info if needed.
2284 # The source corresponding to this can be obtained from the
2291 # The source corresponding to this can be obtained from the
2285 # buffer attribute as '\n'.join(self.buffer).
2292 # buffer attribute as '\n'.join(self.buffer).
2286 self.code_to_run = code
2293 self.code_to_run = code
2287 # now actually execute the code object
2294 # now actually execute the code object
2288 if self.run_code(code, post_execute) == 0:
2295 if self.run_code(code, post_execute) == 0:
2289 return False
2296 return False
2290 else:
2297 else:
2291 return None
2298 return None
2292
2299
2293 # For backwards compatibility
2300 # For backwards compatibility
2294 runsource = run_source
2301 runsource = run_source
2295
2302
2296 def run_code(self, code_obj, post_execute=True):
2303 def run_code(self, code_obj, post_execute=True):
2297 """Execute a code object.
2304 """Execute a code object.
2298
2305
2299 When an exception occurs, self.showtraceback() is called to display a
2306 When an exception occurs, self.showtraceback() is called to display a
2300 traceback.
2307 traceback.
2301
2308
2302 Return value: a flag indicating whether the code to be run completed
2309 Return value: a flag indicating whether the code to be run completed
2303 successfully:
2310 successfully:
2304
2311
2305 - 0: successful execution.
2312 - 0: successful execution.
2306 - 1: an error occurred.
2313 - 1: an error occurred.
2307 """
2314 """
2308
2315
2309 # Set our own excepthook in case the user code tries to call it
2316 # Set our own excepthook in case the user code tries to call it
2310 # directly, so that the IPython crash handler doesn't get triggered
2317 # directly, so that the IPython crash handler doesn't get triggered
2311 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2318 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2312
2319
2313 # we save the original sys.excepthook in the instance, in case config
2320 # we save the original sys.excepthook in the instance, in case config
2314 # code (such as magics) needs access to it.
2321 # code (such as magics) needs access to it.
2315 self.sys_excepthook = old_excepthook
2322 self.sys_excepthook = old_excepthook
2316 outflag = 1 # happens in more places, so it's easier as default
2323 outflag = 1 # happens in more places, so it's easier as default
2317 try:
2324 try:
2318 try:
2325 try:
2319 self.hooks.pre_run_code_hook()
2326 self.hooks.pre_run_code_hook()
2320 #rprint('Running code') # dbg
2327 #rprint('Running code') # dbg
2321 exec code_obj in self.user_global_ns, self.user_ns
2328 exec code_obj in self.user_global_ns, self.user_ns
2322 finally:
2329 finally:
2323 # Reset our crash handler in place
2330 # Reset our crash handler in place
2324 sys.excepthook = old_excepthook
2331 sys.excepthook = old_excepthook
2325 except SystemExit:
2332 except SystemExit:
2326 self.reset_buffer()
2333 self.reset_buffer()
2327 self.showtraceback(exception_only=True)
2334 self.showtraceback(exception_only=True)
2328 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2335 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2329 except self.custom_exceptions:
2336 except self.custom_exceptions:
2330 etype,value,tb = sys.exc_info()
2337 etype,value,tb = sys.exc_info()
2331 self.CustomTB(etype,value,tb)
2338 self.CustomTB(etype,value,tb)
2332 except:
2339 except:
2333 self.showtraceback()
2340 self.showtraceback()
2334 else:
2341 else:
2335 outflag = 0
2342 outflag = 0
2336 if softspace(sys.stdout, 0):
2343 if softspace(sys.stdout, 0):
2337 print
2344 print
2338
2345
2339 # Execute any registered post-execution functions. Here, any errors
2346 # Execute any registered post-execution functions. Here, any errors
2340 # are reported only minimally and just on the terminal, because the
2347 # are reported only minimally and just on the terminal, because the
2341 # main exception channel may be occupied with a user traceback.
2348 # main exception channel may be occupied with a user traceback.
2342 # FIXME: we need to think this mechanism a little more carefully.
2349 # FIXME: we need to think this mechanism a little more carefully.
2343 if post_execute:
2350 if post_execute:
2344 for func in self._post_execute:
2351 for func in self._post_execute:
2345 try:
2352 try:
2346 func()
2353 func()
2347 except:
2354 except:
2348 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2355 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2349 func
2356 func
2350 print >> io.Term.cout, head
2357 print >> io.Term.cout, head
2351 print >> io.Term.cout, self._simple_error()
2358 print >> io.Term.cout, self._simple_error()
2352 print >> io.Term.cout, 'Removing from post_execute'
2359 print >> io.Term.cout, 'Removing from post_execute'
2353 self._post_execute.remove(func)
2360 self._post_execute.remove(func)
2354
2361
2355 # Flush out code object which has been run (and source)
2362 # Flush out code object which has been run (and source)
2356 self.code_to_run = None
2363 self.code_to_run = None
2357 return outflag
2364 return outflag
2358
2365
2359 # For backwards compatibility
2366 # For backwards compatibility
2360 runcode = run_code
2367 runcode = run_code
2361
2368
2362 # PENDING REMOVAL: this method is slated for deletion, once our new
2369 # PENDING REMOVAL: this method is slated for deletion, once our new
2363 # input logic has been 100% moved to frontends and is stable.
2370 # input logic has been 100% moved to frontends and is stable.
2364 def push_line(self, line):
2371 def push_line(self, line):
2365 """Push a line to the interpreter.
2372 """Push a line to the interpreter.
2366
2373
2367 The line should not have a trailing newline; it may have
2374 The line should not have a trailing newline; it may have
2368 internal newlines. The line is appended to a buffer and the
2375 internal newlines. The line is appended to a buffer and the
2369 interpreter's run_source() method is called with the
2376 interpreter's run_source() method is called with the
2370 concatenated contents of the buffer as source. If this
2377 concatenated contents of the buffer as source. If this
2371 indicates that the command was executed or invalid, the buffer
2378 indicates that the command was executed or invalid, the buffer
2372 is reset; otherwise, the command is incomplete, and the buffer
2379 is reset; otherwise, the command is incomplete, and the buffer
2373 is left as it was after the line was appended. The return
2380 is left as it was after the line was appended. The return
2374 value is 1 if more input is required, 0 if the line was dealt
2381 value is 1 if more input is required, 0 if the line was dealt
2375 with in some way (this is the same as run_source()).
2382 with in some way (this is the same as run_source()).
2376 """
2383 """
2377
2384
2378 # autoindent management should be done here, and not in the
2385 # autoindent management should be done here, and not in the
2379 # interactive loop, since that one is only seen by keyboard input. We
2386 # interactive loop, since that one is only seen by keyboard input. We
2380 # need this done correctly even for code run via runlines (which uses
2387 # need this done correctly even for code run via runlines (which uses
2381 # push).
2388 # push).
2382
2389
2383 #print 'push line: <%s>' % line # dbg
2390 #print 'push line: <%s>' % line # dbg
2384 self.buffer.append(line)
2391 self.buffer.append(line)
2385 full_source = '\n'.join(self.buffer)
2392 full_source = '\n'.join(self.buffer)
2386 more = self.run_source(full_source, self.filename)
2393 more = self.run_source(full_source, self.filename)
2387 if not more:
2394 if not more:
2388 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2395 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2389 full_source)
2396 full_source)
2390 self.reset_buffer()
2397 self.reset_buffer()
2391 self.execution_count += 1
2398 self.execution_count += 1
2392 return more
2399 return more
2393
2400
2394 def reset_buffer(self):
2401 def reset_buffer(self):
2395 """Reset the input buffer."""
2402 """Reset the input buffer."""
2396 self.buffer[:] = []
2403 self.buffer[:] = []
2397 self.buffer_raw[:] = []
2404 self.buffer_raw[:] = []
2398 self.input_splitter.reset()
2405 self.input_splitter.reset()
2399
2406
2400 # For backwards compatibility
2407 # For backwards compatibility
2401 resetbuffer = reset_buffer
2408 resetbuffer = reset_buffer
2402
2409
2403 def _is_secondary_block_start(self, s):
2410 def _is_secondary_block_start(self, s):
2404 if not s.endswith(':'):
2411 if not s.endswith(':'):
2405 return False
2412 return False
2406 if (s.startswith('elif') or
2413 if (s.startswith('elif') or
2407 s.startswith('else') or
2414 s.startswith('else') or
2408 s.startswith('except') or
2415 s.startswith('except') or
2409 s.startswith('finally')):
2416 s.startswith('finally')):
2410 return True
2417 return True
2411
2418
2412 def _cleanup_ipy_script(self, script):
2419 def _cleanup_ipy_script(self, script):
2413 """Make a script safe for self.runlines()
2420 """Make a script safe for self.runlines()
2414
2421
2415 Currently, IPython is lines based, with blocks being detected by
2422 Currently, IPython is lines based, with blocks being detected by
2416 empty lines. This is a problem for block based scripts that may
2423 empty lines. This is a problem for block based scripts that may
2417 not have empty lines after blocks. This script adds those empty
2424 not have empty lines after blocks. This script adds those empty
2418 lines to make scripts safe for running in the current line based
2425 lines to make scripts safe for running in the current line based
2419 IPython.
2426 IPython.
2420 """
2427 """
2421 res = []
2428 res = []
2422 lines = script.splitlines()
2429 lines = script.splitlines()
2423 level = 0
2430 level = 0
2424
2431
2425 for l in lines:
2432 for l in lines:
2426 lstripped = l.lstrip()
2433 lstripped = l.lstrip()
2427 stripped = l.strip()
2434 stripped = l.strip()
2428 if not stripped:
2435 if not stripped:
2429 continue
2436 continue
2430 newlevel = len(l) - len(lstripped)
2437 newlevel = len(l) - len(lstripped)
2431 if level > 0 and newlevel == 0 and \
2438 if level > 0 and newlevel == 0 and \
2432 not self._is_secondary_block_start(stripped):
2439 not self._is_secondary_block_start(stripped):
2433 # add empty line
2440 # add empty line
2434 res.append('')
2441 res.append('')
2435 res.append(l)
2442 res.append(l)
2436 level = newlevel
2443 level = newlevel
2437
2444
2438 return '\n'.join(res) + '\n'
2445 return '\n'.join(res) + '\n'
2439
2446
2440 #-------------------------------------------------------------------------
2447 #-------------------------------------------------------------------------
2441 # Things related to GUI support and pylab
2448 # Things related to GUI support and pylab
2442 #-------------------------------------------------------------------------
2449 #-------------------------------------------------------------------------
2443
2450
2444 def enable_pylab(self, gui=None):
2451 def enable_pylab(self, gui=None):
2445 raise NotImplementedError('Implement enable_pylab in a subclass')
2452 raise NotImplementedError('Implement enable_pylab in a subclass')
2446
2453
2447 #-------------------------------------------------------------------------
2454 #-------------------------------------------------------------------------
2448 # Utilities
2455 # Utilities
2449 #-------------------------------------------------------------------------
2456 #-------------------------------------------------------------------------
2450
2457
2451 def var_expand(self,cmd,depth=0):
2458 def var_expand(self,cmd,depth=0):
2452 """Expand python variables in a string.
2459 """Expand python variables in a string.
2453
2460
2454 The depth argument indicates how many frames above the caller should
2461 The depth argument indicates how many frames above the caller should
2455 be walked to look for the local namespace where to expand variables.
2462 be walked to look for the local namespace where to expand variables.
2456
2463
2457 The global namespace for expansion is always the user's interactive
2464 The global namespace for expansion is always the user's interactive
2458 namespace.
2465 namespace.
2459 """
2466 """
2460
2467
2461 return str(ItplNS(cmd,
2468 return str(ItplNS(cmd,
2462 self.user_ns, # globals
2469 self.user_ns, # globals
2463 # Skip our own frame in searching for locals:
2470 # Skip our own frame in searching for locals:
2464 sys._getframe(depth+1).f_locals # locals
2471 sys._getframe(depth+1).f_locals # locals
2465 ))
2472 ))
2466
2473
2467 def mktempfile(self, data=None, prefix='ipython_edit_'):
2474 def mktempfile(self, data=None, prefix='ipython_edit_'):
2468 """Make a new tempfile and return its filename.
2475 """Make a new tempfile and return its filename.
2469
2476
2470 This makes a call to tempfile.mktemp, but it registers the created
2477 This makes a call to tempfile.mktemp, but it registers the created
2471 filename internally so ipython cleans it up at exit time.
2478 filename internally so ipython cleans it up at exit time.
2472
2479
2473 Optional inputs:
2480 Optional inputs:
2474
2481
2475 - data(None): if data is given, it gets written out to the temp file
2482 - data(None): if data is given, it gets written out to the temp file
2476 immediately, and the file is closed again."""
2483 immediately, and the file is closed again."""
2477
2484
2478 filename = tempfile.mktemp('.py', prefix)
2485 filename = tempfile.mktemp('.py', prefix)
2479 self.tempfiles.append(filename)
2486 self.tempfiles.append(filename)
2480
2487
2481 if data:
2488 if data:
2482 tmp_file = open(filename,'w')
2489 tmp_file = open(filename,'w')
2483 tmp_file.write(data)
2490 tmp_file.write(data)
2484 tmp_file.close()
2491 tmp_file.close()
2485 return filename
2492 return filename
2486
2493
2487 # TODO: This should be removed when Term is refactored.
2494 # TODO: This should be removed when Term is refactored.
2488 def write(self,data):
2495 def write(self,data):
2489 """Write a string to the default output"""
2496 """Write a string to the default output"""
2490 io.Term.cout.write(data)
2497 io.Term.cout.write(data)
2491
2498
2492 # TODO: This should be removed when Term is refactored.
2499 # TODO: This should be removed when Term is refactored.
2493 def write_err(self,data):
2500 def write_err(self,data):
2494 """Write a string to the default error output"""
2501 """Write a string to the default error output"""
2495 io.Term.cerr.write(data)
2502 io.Term.cerr.write(data)
2496
2503
2497 def ask_yes_no(self,prompt,default=True):
2504 def ask_yes_no(self,prompt,default=True):
2498 if self.quiet:
2505 if self.quiet:
2499 return True
2506 return True
2500 return ask_yes_no(prompt,default)
2507 return ask_yes_no(prompt,default)
2501
2508
2502 def show_usage(self):
2509 def show_usage(self):
2503 """Show a usage message"""
2510 """Show a usage message"""
2504 page.page(IPython.core.usage.interactive_usage)
2511 page.page(IPython.core.usage.interactive_usage)
2505
2512
2506 #-------------------------------------------------------------------------
2513 #-------------------------------------------------------------------------
2507 # Things related to IPython exiting
2514 # Things related to IPython exiting
2508 #-------------------------------------------------------------------------
2515 #-------------------------------------------------------------------------
2509 def atexit_operations(self):
2516 def atexit_operations(self):
2510 """This will be executed at the time of exit.
2517 """This will be executed at the time of exit.
2511
2518
2512 Cleanup operations and saving of persistent data that is done
2519 Cleanup operations and saving of persistent data that is done
2513 unconditionally by IPython should be performed here.
2520 unconditionally by IPython should be performed here.
2514
2521
2515 For things that may depend on startup flags or platform specifics (such
2522 For things that may depend on startup flags or platform specifics (such
2516 as having readline or not), register a separate atexit function in the
2523 as having readline or not), register a separate atexit function in the
2517 code that has the appropriate information, rather than trying to
2524 code that has the appropriate information, rather than trying to
2518 clutter
2525 clutter
2519 """
2526 """
2520 # Cleanup all tempfiles left around
2527 # Cleanup all tempfiles left around
2521 for tfile in self.tempfiles:
2528 for tfile in self.tempfiles:
2522 try:
2529 try:
2523 os.unlink(tfile)
2530 os.unlink(tfile)
2524 except OSError:
2531 except OSError:
2525 pass
2532 pass
2526
2533
2527 self.save_history()
2534 self.save_history()
2528
2535
2529 # Clear all user namespaces to release all references cleanly.
2536 # Clear all user namespaces to release all references cleanly.
2530 self.reset()
2537 self.reset()
2531
2538
2532 # Run user hooks
2539 # Run user hooks
2533 self.hooks.shutdown_hook()
2540 self.hooks.shutdown_hook()
2534
2541
2535 def cleanup(self):
2542 def cleanup(self):
2536 self.restore_sys_module_state()
2543 self.restore_sys_module_state()
2537
2544
2538
2545
2539 class InteractiveShellABC(object):
2546 class InteractiveShellABC(object):
2540 """An abstract base class for InteractiveShell."""
2547 """An abstract base class for InteractiveShell."""
2541 __metaclass__ = abc.ABCMeta
2548 __metaclass__ = abc.ABCMeta
2542
2549
2543 InteractiveShellABC.register(InteractiveShell)
2550 InteractiveShellABC.register(InteractiveShell)
@@ -1,467 +1,482 b''
1 """ A FrontendWidget that emulates the interface of the console IPython and
1 """ A FrontendWidget that emulates the interface of the console IPython and
2 supports the additional functionality provided by the IPython kernel.
2 supports the additional functionality provided by the IPython kernel.
3
3
4 TODO: Add support for retrieving the system default editor. Requires code
4 TODO: Add support for retrieving the system default editor. Requires code
5 paths for Windows (use the registry), Mac OS (use LaunchServices), and
5 paths for Windows (use the registry), Mac OS (use LaunchServices), and
6 Linux (use the xdg system).
6 Linux (use the xdg system).
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Imports
10 # Imports
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 # Standard library imports
13 # Standard library imports
14 from collections import namedtuple
14 from collections import namedtuple
15 import re
15 import re
16 from subprocess import Popen
16 from subprocess import Popen
17 from textwrap import dedent
17 from textwrap import dedent
18
18
19 # System library imports
19 # System library imports
20 from PyQt4 import QtCore, QtGui
20 from PyQt4 import QtCore, QtGui
21
21
22 # Local imports
22 # Local imports
23 from IPython.core.inputsplitter import IPythonInputSplitter, \
23 from IPython.core.inputsplitter import IPythonInputSplitter, \
24 transform_ipy_prompt
24 transform_ipy_prompt
25 from IPython.core.usage import default_gui_banner
25 from IPython.core.usage import default_gui_banner
26 from IPython.utils.traitlets import Bool, Str
26 from IPython.utils.traitlets import Bool, Str
27 from frontend_widget import FrontendWidget
27 from frontend_widget import FrontendWidget
28 from styles import (default_light_style_sheet, default_light_syntax_style,
28 from styles import (default_light_style_sheet, default_light_syntax_style,
29 default_dark_style_sheet, default_dark_syntax_style,
29 default_dark_style_sheet, default_dark_syntax_style,
30 default_bw_style_sheet, default_bw_syntax_style)
30 default_bw_style_sheet, default_bw_syntax_style)
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Constants
33 # Constants
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 # Default strings to build and display input and output prompts (and separators
36 # Default strings to build and display input and output prompts (and separators
37 # in between)
37 # in between)
38 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
38 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
39 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
39 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
40 default_input_sep = '\n'
40 default_input_sep = '\n'
41 default_output_sep = ''
41 default_output_sep = ''
42 default_output_sep2 = ''
42 default_output_sep2 = ''
43
43
44 # Base path for most payload sources.
44 # Base path for most payload sources.
45 zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell'
45 zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell'
46
46
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48 # IPythonWidget class
48 # IPythonWidget class
49 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
50
50
51 class IPythonWidget(FrontendWidget):
51 class IPythonWidget(FrontendWidget):
52 """ A FrontendWidget for an IPython kernel.
52 """ A FrontendWidget for an IPython kernel.
53 """
53 """
54
54
55 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
55 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
56 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
56 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
57 # settings.
57 # settings.
58 custom_edit = Bool(False)
58 custom_edit = Bool(False)
59 custom_edit_requested = QtCore.pyqtSignal(object, object)
59 custom_edit_requested = QtCore.pyqtSignal(object, object)
60
60
61 # A command for invoking a system text editor. If the string contains a
61 # A command for invoking a system text editor. If the string contains a
62 # {filename} format specifier, it will be used. Otherwise, the filename will
62 # {filename} format specifier, it will be used. Otherwise, the filename will
63 # be appended to the end the command.
63 # be appended to the end the command.
64 editor = Str('default', config=True)
64 editor = Str('default', config=True)
65
65
66 # The editor command to use when a specific line number is requested. The
66 # The editor command to use when a specific line number is requested. The
67 # string should contain two format specifiers: {line} and {filename}. If
67 # string should contain two format specifiers: {line} and {filename}. If
68 # this parameter is not specified, the line number option to the %edit magic
68 # this parameter is not specified, the line number option to the %edit magic
69 # will be ignored.
69 # will be ignored.
70 editor_line = Str(config=True)
70 editor_line = Str(config=True)
71
71
72 # A CSS stylesheet. The stylesheet can contain classes for:
72 # A CSS stylesheet. The stylesheet can contain classes for:
73 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
73 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
74 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
74 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
75 # 3. IPython: .error, .in-prompt, .out-prompt, etc
75 # 3. IPython: .error, .in-prompt, .out-prompt, etc
76 style_sheet = Str(config=True)
76 style_sheet = Str(config=True)
77
77
78 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
78 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
79 # the style sheet is queried for Pygments style information.
79 # the style sheet is queried for Pygments style information.
80 syntax_style = Str(config=True)
80 syntax_style = Str(config=True)
81
81
82 # Prompts.
82 # Prompts.
83 in_prompt = Str(default_in_prompt, config=True)
83 in_prompt = Str(default_in_prompt, config=True)
84 out_prompt = Str(default_out_prompt, config=True)
84 out_prompt = Str(default_out_prompt, config=True)
85 input_sep = Str(default_input_sep, config=True)
85 input_sep = Str(default_input_sep, config=True)
86 output_sep = Str(default_output_sep, config=True)
86 output_sep = Str(default_output_sep, config=True)
87 output_sep2 = Str(default_output_sep2, config=True)
87 output_sep2 = Str(default_output_sep2, config=True)
88
88
89 # FrontendWidget protected class variables.
89 # FrontendWidget protected class variables.
90 _input_splitter_class = IPythonInputSplitter
90 _input_splitter_class = IPythonInputSplitter
91
91
92 # IPythonWidget protected class variables.
92 # IPythonWidget protected class variables.
93 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
93 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
94 _payload_source_edit = zmq_shell_source + '.edit_magic'
94 _payload_source_edit = zmq_shell_source + '.edit_magic'
95 _payload_source_exit = zmq_shell_source + '.ask_exit'
95 _payload_source_exit = zmq_shell_source + '.ask_exit'
96 _payload_source_loadpy = zmq_shell_source + '.magic_loadpy'
96 _payload_source_loadpy = zmq_shell_source + '.magic_loadpy'
97 _payload_source_page = 'IPython.zmq.page.page'
97 _payload_source_page = 'IPython.zmq.page.page'
98
98
99 #---------------------------------------------------------------------------
99 #---------------------------------------------------------------------------
100 # 'object' interface
100 # 'object' interface
101 #---------------------------------------------------------------------------
101 #---------------------------------------------------------------------------
102
102
103 def __init__(self, *args, **kw):
103 def __init__(self, *args, **kw):
104 super(IPythonWidget, self).__init__(*args, **kw)
104 super(IPythonWidget, self).__init__(*args, **kw)
105
105
106 # IPythonWidget protected variables.
106 # IPythonWidget protected variables.
107 self._code_to_load = None
107 self._code_to_load = None
108 self._payload_handlers = {
108 self._payload_handlers = {
109 self._payload_source_edit : self._handle_payload_edit,
109 self._payload_source_edit : self._handle_payload_edit,
110 self._payload_source_exit : self._handle_payload_exit,
110 self._payload_source_exit : self._handle_payload_exit,
111 self._payload_source_page : self._handle_payload_page,
111 self._payload_source_page : self._handle_payload_page,
112 self._payload_source_loadpy : self._handle_payload_loadpy }
112 self._payload_source_loadpy : self._handle_payload_loadpy }
113 self._previous_prompt_obj = None
113 self._previous_prompt_obj = None
114 self._keep_kernel_on_exit = None
114 self._keep_kernel_on_exit = None
115
115
116 # Initialize widget styling.
116 # Initialize widget styling.
117 if self.style_sheet:
117 if self.style_sheet:
118 self._style_sheet_changed()
118 self._style_sheet_changed()
119 self._syntax_style_changed()
119 self._syntax_style_changed()
120 else:
120 else:
121 self.set_default_style()
121 self.set_default_style()
122
122
123 #---------------------------------------------------------------------------
123 #---------------------------------------------------------------------------
124 # 'BaseFrontendMixin' abstract interface
124 # 'BaseFrontendMixin' abstract interface
125 #---------------------------------------------------------------------------
125 #---------------------------------------------------------------------------
126
126
127 def _handle_complete_reply(self, rep):
127 def _handle_complete_reply(self, rep):
128 """ Reimplemented to support IPython's improved completion machinery.
128 """ Reimplemented to support IPython's improved completion machinery.
129 """
129 """
130 cursor = self._get_cursor()
130 cursor = self._get_cursor()
131 info = self._request_info.get('complete')
131 info = self._request_info.get('complete')
132 if info and info.id == rep['parent_header']['msg_id'] and \
132 if info and info.id == rep['parent_header']['msg_id'] and \
133 info.pos == cursor.position():
133 info.pos == cursor.position():
134 matches = rep['content']['matches']
134 matches = rep['content']['matches']
135 text = rep['content']['matched_text']
135 text = rep['content']['matched_text']
136 offset = len(text)
136 offset = len(text)
137
137
138 # Clean up matches with period and path separators if the matched
138 # Clean up matches with period and path separators if the matched
139 # text has not been transformed. This is done by truncating all
139 # text has not been transformed. This is done by truncating all
140 # but the last component and then suitably decreasing the offset
140 # but the last component and then suitably decreasing the offset
141 # between the current cursor position and the start of completion.
141 # between the current cursor position and the start of completion.
142 if len(matches) > 1 and matches[0][:offset] == text:
142 if len(matches) > 1 and matches[0][:offset] == text:
143 parts = re.split(r'[./\\]', text)
143 parts = re.split(r'[./\\]', text)
144 sep_count = len(parts) - 1
144 sep_count = len(parts) - 1
145 if sep_count:
145 if sep_count:
146 chop_length = sum(map(len, parts[:sep_count])) + sep_count
146 chop_length = sum(map(len, parts[:sep_count])) + sep_count
147 matches = [ match[chop_length:] for match in matches ]
147 matches = [ match[chop_length:] for match in matches ]
148 offset -= chop_length
148 offset -= chop_length
149
149
150 # Move the cursor to the start of the match and complete.
150 # Move the cursor to the start of the match and complete.
151 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
151 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
152 self._complete_with_items(cursor, matches)
152 self._complete_with_items(cursor, matches)
153
153
154 def _handle_execute_reply(self, msg):
154 def _handle_execute_reply(self, msg):
155 """ Reimplemented to support prompt requests.
155 """ Reimplemented to support prompt requests.
156 """
156 """
157 info = self._request_info.get('execute')
157 info = self._request_info.get('execute')
158 if info and info.id == msg['parent_header']['msg_id']:
158 if info and info.id == msg['parent_header']['msg_id']:
159 if info.kind == 'prompt':
159 if info.kind == 'prompt':
160 number = msg['content']['execution_count'] + 1
160 number = msg['content']['execution_count'] + 1
161 self._show_interpreter_prompt(number)
161 self._show_interpreter_prompt(number)
162 else:
162 else:
163 super(IPythonWidget, self)._handle_execute_reply(msg)
163 super(IPythonWidget, self)._handle_execute_reply(msg)
164
164
165 def _handle_history_reply(self, msg):
165 def _handle_history_reply(self, msg):
166 """ Implemented to handle history replies, which are only supported by
166 """ Implemented to handle history replies, which are only supported by
167 the IPython kernel.
167 the IPython kernel.
168 """
168 """
169 history_dict = msg['content']['history']
169 history_dict = msg['content']['history']
170 input_history_dict = {}
170 input_history_dict = {}
171 for key,val in history_dict.items():
171 for key,val in history_dict.items():
172 input_history_dict[int(key)] = val
172 input_history_dict[int(key)] = val
173 items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ]
173 items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ]
174 self._set_history(items)
174 self._set_history(items)
175
175
176 def _handle_pyout(self, msg):
176 def _handle_pyout(self, msg):
177 """ Reimplemented for IPython-style "display hook".
177 """ Reimplemented for IPython-style "display hook".
178 """
178 """
179 if not self._hidden and self._is_from_this_session(msg):
179 if not self._hidden and self._is_from_this_session(msg):
180 content = msg['content']
180 content = msg['content']
181 prompt_number = content['execution_count']
181 prompt_number = content['execution_count']
182 self._append_plain_text(self.output_sep)
182 self._append_plain_text(self.output_sep)
183 self._append_html(self._make_out_prompt(prompt_number))
183 self._append_html(self._make_out_prompt(prompt_number))
184 self._append_plain_text(content['data']+self.output_sep2)
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 def _started_channels(self):
201 def _started_channels(self):
187 """ Reimplemented to make a history request.
202 """ Reimplemented to make a history request.
188 """
203 """
189 super(IPythonWidget, self)._started_channels()
204 super(IPythonWidget, self)._started_channels()
190 self.kernel_manager.xreq_channel.history(raw=True, output=False)
205 self.kernel_manager.xreq_channel.history(raw=True, output=False)
191
206
192 #---------------------------------------------------------------------------
207 #---------------------------------------------------------------------------
193 # 'ConsoleWidget' public interface
208 # 'ConsoleWidget' public interface
194 #---------------------------------------------------------------------------
209 #---------------------------------------------------------------------------
195
210
196 def copy(self):
211 def copy(self):
197 """ Copy the currently selected text to the clipboard, removing prompts
212 """ Copy the currently selected text to the clipboard, removing prompts
198 if possible.
213 if possible.
199 """
214 """
200 text = unicode(self._control.textCursor().selection().toPlainText())
215 text = unicode(self._control.textCursor().selection().toPlainText())
201 if text:
216 if text:
202 lines = map(transform_ipy_prompt, text.splitlines())
217 lines = map(transform_ipy_prompt, text.splitlines())
203 text = '\n'.join(lines)
218 text = '\n'.join(lines)
204 QtGui.QApplication.clipboard().setText(text)
219 QtGui.QApplication.clipboard().setText(text)
205
220
206 #---------------------------------------------------------------------------
221 #---------------------------------------------------------------------------
207 # 'FrontendWidget' public interface
222 # 'FrontendWidget' public interface
208 #---------------------------------------------------------------------------
223 #---------------------------------------------------------------------------
209
224
210 def execute_file(self, path, hidden=False):
225 def execute_file(self, path, hidden=False):
211 """ Reimplemented to use the 'run' magic.
226 """ Reimplemented to use the 'run' magic.
212 """
227 """
213 self.execute('%%run %s' % path, hidden=hidden)
228 self.execute('%%run %s' % path, hidden=hidden)
214
229
215 #---------------------------------------------------------------------------
230 #---------------------------------------------------------------------------
216 # 'FrontendWidget' protected interface
231 # 'FrontendWidget' protected interface
217 #---------------------------------------------------------------------------
232 #---------------------------------------------------------------------------
218
233
219 def _complete(self):
234 def _complete(self):
220 """ Reimplemented to support IPython's improved completion machinery.
235 """ Reimplemented to support IPython's improved completion machinery.
221 """
236 """
222 # We let the kernel split the input line, so we *always* send an empty
237 # We let the kernel split the input line, so we *always* send an empty
223 # text field. Readline-based frontends do get a real text field which
238 # text field. Readline-based frontends do get a real text field which
224 # they can use.
239 # they can use.
225 text = ''
240 text = ''
226
241
227 # Send the completion request to the kernel
242 # Send the completion request to the kernel
228 msg_id = self.kernel_manager.xreq_channel.complete(
243 msg_id = self.kernel_manager.xreq_channel.complete(
229 text, # text
244 text, # text
230 self._get_input_buffer_cursor_line(), # line
245 self._get_input_buffer_cursor_line(), # line
231 self._get_input_buffer_cursor_column(), # cursor_pos
246 self._get_input_buffer_cursor_column(), # cursor_pos
232 self.input_buffer) # block
247 self.input_buffer) # block
233 pos = self._get_cursor().position()
248 pos = self._get_cursor().position()
234 info = self._CompletionRequest(msg_id, pos)
249 info = self._CompletionRequest(msg_id, pos)
235 self._request_info['complete'] = info
250 self._request_info['complete'] = info
236
251
237 def _get_banner(self):
252 def _get_banner(self):
238 """ Reimplemented to return IPython's default banner.
253 """ Reimplemented to return IPython's default banner.
239 """
254 """
240 return default_gui_banner
255 return default_gui_banner
241
256
242 def _process_execute_error(self, msg):
257 def _process_execute_error(self, msg):
243 """ Reimplemented for IPython-style traceback formatting.
258 """ Reimplemented for IPython-style traceback formatting.
244 """
259 """
245 content = msg['content']
260 content = msg['content']
246 traceback = '\n'.join(content['traceback']) + '\n'
261 traceback = '\n'.join(content['traceback']) + '\n'
247 if False:
262 if False:
248 # FIXME: For now, tracebacks come as plain text, so we can't use
263 # FIXME: For now, tracebacks come as plain text, so we can't use
249 # the html renderer yet. Once we refactor ultratb to produce
264 # the html renderer yet. Once we refactor ultratb to produce
250 # properly styled tracebacks, this branch should be the default
265 # properly styled tracebacks, this branch should be the default
251 traceback = traceback.replace(' ', '&nbsp;')
266 traceback = traceback.replace(' ', '&nbsp;')
252 traceback = traceback.replace('\n', '<br/>')
267 traceback = traceback.replace('\n', '<br/>')
253
268
254 ename = content['ename']
269 ename = content['ename']
255 ename_styled = '<span class="error">%s</span>' % ename
270 ename_styled = '<span class="error">%s</span>' % ename
256 traceback = traceback.replace(ename, ename_styled)
271 traceback = traceback.replace(ename, ename_styled)
257
272
258 self._append_html(traceback)
273 self._append_html(traceback)
259 else:
274 else:
260 # This is the fallback for now, using plain text with ansi escapes
275 # This is the fallback for now, using plain text with ansi escapes
261 self._append_plain_text(traceback)
276 self._append_plain_text(traceback)
262
277
263 def _process_execute_payload(self, item):
278 def _process_execute_payload(self, item):
264 """ Reimplemented to dispatch payloads to handler methods.
279 """ Reimplemented to dispatch payloads to handler methods.
265 """
280 """
266 handler = self._payload_handlers.get(item['source'])
281 handler = self._payload_handlers.get(item['source'])
267 if handler is None:
282 if handler is None:
268 # We have no handler for this type of payload, simply ignore it
283 # We have no handler for this type of payload, simply ignore it
269 return False
284 return False
270 else:
285 else:
271 handler(item)
286 handler(item)
272 return True
287 return True
273
288
274 def _show_interpreter_prompt(self, number=None):
289 def _show_interpreter_prompt(self, number=None):
275 """ Reimplemented for IPython-style prompts.
290 """ Reimplemented for IPython-style prompts.
276 """
291 """
277 # If a number was not specified, make a prompt number request.
292 # If a number was not specified, make a prompt number request.
278 if number is None:
293 if number is None:
279 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
294 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
280 info = self._ExecutionRequest(msg_id, 'prompt')
295 info = self._ExecutionRequest(msg_id, 'prompt')
281 self._request_info['execute'] = info
296 self._request_info['execute'] = info
282 return
297 return
283
298
284 # Show a new prompt and save information about it so that it can be
299 # Show a new prompt and save information about it so that it can be
285 # updated later if the prompt number turns out to be wrong.
300 # updated later if the prompt number turns out to be wrong.
286 self._prompt_sep = self.input_sep
301 self._prompt_sep = self.input_sep
287 self._show_prompt(self._make_in_prompt(number), html=True)
302 self._show_prompt(self._make_in_prompt(number), html=True)
288 block = self._control.document().lastBlock()
303 block = self._control.document().lastBlock()
289 length = len(self._prompt)
304 length = len(self._prompt)
290 self._previous_prompt_obj = self._PromptBlock(block, length, number)
305 self._previous_prompt_obj = self._PromptBlock(block, length, number)
291
306
292 # Update continuation prompt to reflect (possibly) new prompt length.
307 # Update continuation prompt to reflect (possibly) new prompt length.
293 self._set_continuation_prompt(
308 self._set_continuation_prompt(
294 self._make_continuation_prompt(self._prompt), html=True)
309 self._make_continuation_prompt(self._prompt), html=True)
295
310
296 # Load code from the %loadpy magic, if necessary.
311 # Load code from the %loadpy magic, if necessary.
297 if self._code_to_load is not None:
312 if self._code_to_load is not None:
298 self.input_buffer = dedent(unicode(self._code_to_load).rstrip())
313 self.input_buffer = dedent(unicode(self._code_to_load).rstrip())
299 self._code_to_load = None
314 self._code_to_load = None
300
315
301 def _show_interpreter_prompt_for_reply(self, msg):
316 def _show_interpreter_prompt_for_reply(self, msg):
302 """ Reimplemented for IPython-style prompts.
317 """ Reimplemented for IPython-style prompts.
303 """
318 """
304 # Update the old prompt number if necessary.
319 # Update the old prompt number if necessary.
305 content = msg['content']
320 content = msg['content']
306 previous_prompt_number = content['execution_count']
321 previous_prompt_number = content['execution_count']
307 if self._previous_prompt_obj and \
322 if self._previous_prompt_obj and \
308 self._previous_prompt_obj.number != previous_prompt_number:
323 self._previous_prompt_obj.number != previous_prompt_number:
309 block = self._previous_prompt_obj.block
324 block = self._previous_prompt_obj.block
310
325
311 # Make sure the prompt block has not been erased.
326 # Make sure the prompt block has not been erased.
312 if block.isValid() and not block.text().isEmpty():
327 if block.isValid() and not block.text().isEmpty():
313
328
314 # Remove the old prompt and insert a new prompt.
329 # Remove the old prompt and insert a new prompt.
315 cursor = QtGui.QTextCursor(block)
330 cursor = QtGui.QTextCursor(block)
316 cursor.movePosition(QtGui.QTextCursor.Right,
331 cursor.movePosition(QtGui.QTextCursor.Right,
317 QtGui.QTextCursor.KeepAnchor,
332 QtGui.QTextCursor.KeepAnchor,
318 self._previous_prompt_obj.length)
333 self._previous_prompt_obj.length)
319 prompt = self._make_in_prompt(previous_prompt_number)
334 prompt = self._make_in_prompt(previous_prompt_number)
320 self._prompt = self._insert_html_fetching_plain_text(
335 self._prompt = self._insert_html_fetching_plain_text(
321 cursor, prompt)
336 cursor, prompt)
322
337
323 # When the HTML is inserted, Qt blows away the syntax
338 # When the HTML is inserted, Qt blows away the syntax
324 # highlighting for the line, so we need to rehighlight it.
339 # highlighting for the line, so we need to rehighlight it.
325 self._highlighter.rehighlightBlock(cursor.block())
340 self._highlighter.rehighlightBlock(cursor.block())
326
341
327 self._previous_prompt_obj = None
342 self._previous_prompt_obj = None
328
343
329 # Show a new prompt with the kernel's estimated prompt number.
344 # Show a new prompt with the kernel's estimated prompt number.
330 self._show_interpreter_prompt(previous_prompt_number + 1)
345 self._show_interpreter_prompt(previous_prompt_number + 1)
331
346
332 #---------------------------------------------------------------------------
347 #---------------------------------------------------------------------------
333 # 'IPythonWidget' interface
348 # 'IPythonWidget' interface
334 #---------------------------------------------------------------------------
349 #---------------------------------------------------------------------------
335
350
336 def set_default_style(self, colors='lightbg'):
351 def set_default_style(self, colors='lightbg'):
337 """ Sets the widget style to the class defaults.
352 """ Sets the widget style to the class defaults.
338
353
339 Parameters:
354 Parameters:
340 -----------
355 -----------
341 colors : str, optional (default lightbg)
356 colors : str, optional (default lightbg)
342 Whether to use the default IPython light background or dark
357 Whether to use the default IPython light background or dark
343 background or B&W style.
358 background or B&W style.
344 """
359 """
345 colors = colors.lower()
360 colors = colors.lower()
346 if colors=='lightbg':
361 if colors=='lightbg':
347 self.style_sheet = default_light_style_sheet
362 self.style_sheet = default_light_style_sheet
348 self.syntax_style = default_light_syntax_style
363 self.syntax_style = default_light_syntax_style
349 elif colors=='linux':
364 elif colors=='linux':
350 self.style_sheet = default_dark_style_sheet
365 self.style_sheet = default_dark_style_sheet
351 self.syntax_style = default_dark_syntax_style
366 self.syntax_style = default_dark_syntax_style
352 elif colors=='nocolor':
367 elif colors=='nocolor':
353 self.style_sheet = default_bw_style_sheet
368 self.style_sheet = default_bw_style_sheet
354 self.syntax_style = default_bw_syntax_style
369 self.syntax_style = default_bw_syntax_style
355 else:
370 else:
356 raise KeyError("No such color scheme: %s"%colors)
371 raise KeyError("No such color scheme: %s"%colors)
357
372
358 #---------------------------------------------------------------------------
373 #---------------------------------------------------------------------------
359 # 'IPythonWidget' protected interface
374 # 'IPythonWidget' protected interface
360 #---------------------------------------------------------------------------
375 #---------------------------------------------------------------------------
361
376
362 def _edit(self, filename, line=None):
377 def _edit(self, filename, line=None):
363 """ Opens a Python script for editing.
378 """ Opens a Python script for editing.
364
379
365 Parameters:
380 Parameters:
366 -----------
381 -----------
367 filename : str
382 filename : str
368 A path to a local system file.
383 A path to a local system file.
369
384
370 line : int, optional
385 line : int, optional
371 A line of interest in the file.
386 A line of interest in the file.
372 """
387 """
373 if self.custom_edit:
388 if self.custom_edit:
374 self.custom_edit_requested.emit(filename, line)
389 self.custom_edit_requested.emit(filename, line)
375 elif self.editor == 'default':
390 elif self.editor == 'default':
376 self._append_plain_text('No default editor available.\n')
391 self._append_plain_text('No default editor available.\n')
377 else:
392 else:
378 try:
393 try:
379 filename = '"%s"' % filename
394 filename = '"%s"' % filename
380 if line and self.editor_line:
395 if line and self.editor_line:
381 command = self.editor_line.format(filename=filename,
396 command = self.editor_line.format(filename=filename,
382 line=line)
397 line=line)
383 else:
398 else:
384 try:
399 try:
385 command = self.editor.format()
400 command = self.editor.format()
386 except KeyError:
401 except KeyError:
387 command = self.editor.format(filename=filename)
402 command = self.editor.format(filename=filename)
388 else:
403 else:
389 command += ' ' + filename
404 command += ' ' + filename
390 except KeyError:
405 except KeyError:
391 self._append_plain_text('Invalid editor command.\n')
406 self._append_plain_text('Invalid editor command.\n')
392 else:
407 else:
393 try:
408 try:
394 Popen(command, shell=True)
409 Popen(command, shell=True)
395 except OSError:
410 except OSError:
396 msg = 'Opening editor with command "%s" failed.\n'
411 msg = 'Opening editor with command "%s" failed.\n'
397 self._append_plain_text(msg % command)
412 self._append_plain_text(msg % command)
398
413
399 def _make_in_prompt(self, number):
414 def _make_in_prompt(self, number):
400 """ Given a prompt number, returns an HTML In prompt.
415 """ Given a prompt number, returns an HTML In prompt.
401 """
416 """
402 body = self.in_prompt % number
417 body = self.in_prompt % number
403 return '<span class="in-prompt">%s</span>' % body
418 return '<span class="in-prompt">%s</span>' % body
404
419
405 def _make_continuation_prompt(self, prompt):
420 def _make_continuation_prompt(self, prompt):
406 """ Given a plain text version of an In prompt, returns an HTML
421 """ Given a plain text version of an In prompt, returns an HTML
407 continuation prompt.
422 continuation prompt.
408 """
423 """
409 end_chars = '...: '
424 end_chars = '...: '
410 space_count = len(prompt.lstrip('\n')) - len(end_chars)
425 space_count = len(prompt.lstrip('\n')) - len(end_chars)
411 body = '&nbsp;' * space_count + end_chars
426 body = '&nbsp;' * space_count + end_chars
412 return '<span class="in-prompt">%s</span>' % body
427 return '<span class="in-prompt">%s</span>' % body
413
428
414 def _make_out_prompt(self, number):
429 def _make_out_prompt(self, number):
415 """ Given a prompt number, returns an HTML Out prompt.
430 """ Given a prompt number, returns an HTML Out prompt.
416 """
431 """
417 body = self.out_prompt % number
432 body = self.out_prompt % number
418 return '<span class="out-prompt">%s</span>' % body
433 return '<span class="out-prompt">%s</span>' % body
419
434
420 #------ Payload handlers --------------------------------------------------
435 #------ Payload handlers --------------------------------------------------
421
436
422 # Payload handlers with a generic interface: each takes the opaque payload
437 # Payload handlers with a generic interface: each takes the opaque payload
423 # dict, unpacks it and calls the underlying functions with the necessary
438 # dict, unpacks it and calls the underlying functions with the necessary
424 # arguments.
439 # arguments.
425
440
426 def _handle_payload_edit(self, item):
441 def _handle_payload_edit(self, item):
427 self._edit(item['filename'], item['line_number'])
442 self._edit(item['filename'], item['line_number'])
428
443
429 def _handle_payload_exit(self, item):
444 def _handle_payload_exit(self, item):
430 self._keep_kernel_on_exit = item['keepkernel']
445 self._keep_kernel_on_exit = item['keepkernel']
431 self.exit_requested.emit()
446 self.exit_requested.emit()
432
447
433 def _handle_payload_loadpy(self, item):
448 def _handle_payload_loadpy(self, item):
434 # Simple save the text of the .py file for later. The text is written
449 # Simple save the text of the .py file for later. The text is written
435 # to the buffer when _prompt_started_hook is called.
450 # to the buffer when _prompt_started_hook is called.
436 self._code_to_load = item['text']
451 self._code_to_load = item['text']
437
452
438 def _handle_payload_page(self, item):
453 def _handle_payload_page(self, item):
439 # Since the plain text widget supports only a very small subset of HTML
454 # Since the plain text widget supports only a very small subset of HTML
440 # and we have no control over the HTML source, we only page HTML
455 # and we have no control over the HTML source, we only page HTML
441 # payloads in the rich text widget.
456 # payloads in the rich text widget.
442 if item['html'] and self.kind == 'rich':
457 if item['html'] and self.kind == 'rich':
443 self._page(item['html'], html=True)
458 self._page(item['html'], html=True)
444 else:
459 else:
445 self._page(item['text'], html=False)
460 self._page(item['text'], html=False)
446
461
447 #------ Trait change handlers ---------------------------------------------
462 #------ Trait change handlers --------------------------------------------
448
463
449 def _style_sheet_changed(self):
464 def _style_sheet_changed(self):
450 """ Set the style sheets of the underlying widgets.
465 """ Set the style sheets of the underlying widgets.
451 """
466 """
452 self.setStyleSheet(self.style_sheet)
467 self.setStyleSheet(self.style_sheet)
453 self._control.document().setDefaultStyleSheet(self.style_sheet)
468 self._control.document().setDefaultStyleSheet(self.style_sheet)
454 if self._page_control:
469 if self._page_control:
455 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
470 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
456
471
457 bg_color = self._control.palette().background().color()
472 bg_color = self._control.palette().background().color()
458 self._ansi_processor.set_background_color(bg_color)
473 self._ansi_processor.set_background_color(bg_color)
459
474
460 def _syntax_style_changed(self):
475 def _syntax_style_changed(self):
461 """ Set the style for the syntax highlighter.
476 """ Set the style for the syntax highlighter.
462 """
477 """
463 if self.syntax_style:
478 if self.syntax_style:
464 self._highlighter.set_style(self.syntax_style)
479 self._highlighter.set_style(self.syntax_style)
465 else:
480 else:
466 self._highlighter.set_style_sheet(self.style_sheet)
481 self._highlighter.set_style_sheet(self.style_sheet)
467
482
@@ -1,195 +1,226 b''
1 # System library imports
1 # System library imports
2 import os
2 import os
3 import re
3 import re
4 from PyQt4 import QtCore, QtGui
4 from PyQt4 import QtCore, QtGui
5
5
6 # Local imports
6 # Local imports
7 from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image
7 from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image
8 from ipython_widget import IPythonWidget
8 from ipython_widget import IPythonWidget
9
9
10
10
11 class RichIPythonWidget(IPythonWidget):
11 class RichIPythonWidget(IPythonWidget):
12 """ An IPythonWidget that supports rich text, including lists, images, and
12 """ An IPythonWidget that supports rich text, including lists, images, and
13 tables. Note that raw performance will be reduced compared to the plain
13 tables. Note that raw performance will be reduced compared to the plain
14 text version.
14 text version.
15 """
15 """
16
16
17 # RichIPythonWidget protected class variables.
17 # RichIPythonWidget protected class variables.
18 _payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload'
18 _payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload'
19 _svg_text_format_property = 1
19 _svg_text_format_property = 1
20
20
21 #---------------------------------------------------------------------------
21 #---------------------------------------------------------------------------
22 # 'object' interface
22 # 'object' interface
23 #---------------------------------------------------------------------------
23 #---------------------------------------------------------------------------
24
24
25 def __init__(self, *args, **kw):
25 def __init__(self, *args, **kw):
26 """ Create a RichIPythonWidget.
26 """ Create a RichIPythonWidget.
27 """
27 """
28 kw['kind'] = 'rich'
28 kw['kind'] = 'rich'
29 super(RichIPythonWidget, self).__init__(*args, **kw)
29 super(RichIPythonWidget, self).__init__(*args, **kw)
30 # Dictionary for resolving Qt names to images when
30 # Dictionary for resolving Qt names to images when
31 # generating XHTML output
31 # generating XHTML output
32 self._name_to_svg = {}
32 self._name_to_svg = {}
33
33
34 #---------------------------------------------------------------------------
34 #---------------------------------------------------------------------------
35 # 'ConsoleWidget' protected interface
35 # 'ConsoleWidget' protected interface
36 #---------------------------------------------------------------------------
36 #---------------------------------------------------------------------------
37
37
38 def _context_menu_make(self, pos):
38 def _context_menu_make(self, pos):
39 """ Reimplemented to return a custom context menu for images.
39 """ Reimplemented to return a custom context menu for images.
40 """
40 """
41 format = self._control.cursorForPosition(pos).charFormat()
41 format = self._control.cursorForPosition(pos).charFormat()
42 name = format.stringProperty(QtGui.QTextFormat.ImageName)
42 name = format.stringProperty(QtGui.QTextFormat.ImageName)
43 if name.isEmpty():
43 if name.isEmpty():
44 menu = super(RichIPythonWidget, self)._context_menu_make(pos)
44 menu = super(RichIPythonWidget, self)._context_menu_make(pos)
45 else:
45 else:
46 menu = QtGui.QMenu()
46 menu = QtGui.QMenu()
47
47
48 menu.addAction('Copy Image', lambda: self._copy_image(name))
48 menu.addAction('Copy Image', lambda: self._copy_image(name))
49 menu.addAction('Save Image As...', lambda: self._save_image(name))
49 menu.addAction('Save Image As...', lambda: self._save_image(name))
50 menu.addSeparator()
50 menu.addSeparator()
51
51
52 svg = format.stringProperty(self._svg_text_format_property)
52 svg = format.stringProperty(self._svg_text_format_property)
53 if not svg.isEmpty():
53 if not svg.isEmpty():
54 menu.addSeparator()
54 menu.addSeparator()
55 menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg))
55 menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg))
56 menu.addAction('Save SVG As...',
56 menu.addAction('Save SVG As...',
57 lambda: save_svg(svg, self._control))
57 lambda: save_svg(svg, self._control))
58 return menu
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 # 'FrontendWidget' protected interface
85 # 'FrontendWidget' protected interface
62 #---------------------------------------------------------------------------
86 #---------------------------------------------------------------------------
63
87
64 def _process_execute_payload(self, item):
88 def _process_execute_payload(self, item):
65 """ Reimplemented to handle matplotlib plot payloads.
89 """ Reimplemented to handle matplotlib plot payloads.
66 """
90 """
67 if item['source'] == self._payload_source_plot:
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 if item['format'] == 'svg':
94 if item['format'] == 'svg':
69 svg = item['data']
95 svg = item['data']
70 try:
96 self._append_svg(svg)
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()
82 return True
97 return True
83 else:
98 else:
84 # Add other plot formats here!
99 # Add other plot formats here!
85 return False
100 return False
86 else:
101 else:
87 return super(RichIPythonWidget, self)._process_execute_payload(item)
102 return super(RichIPythonWidget, self)._process_execute_payload(item)
88
103
89 #---------------------------------------------------------------------------
104 #---------------------------------------------------------------------------
90 # 'RichIPythonWidget' protected interface
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 def _add_image(self, image):
124 def _add_image(self, image):
94 """ Adds the specified QImage to the document and returns a
125 """ Adds the specified QImage to the document and returns a
95 QTextImageFormat that references it.
126 QTextImageFormat that references it.
96 """
127 """
97 document = self._control.document()
128 document = self._control.document()
98 name = QtCore.QString.number(image.cacheKey())
129 name = QtCore.QString.number(image.cacheKey())
99 document.addResource(QtGui.QTextDocument.ImageResource,
130 document.addResource(QtGui.QTextDocument.ImageResource,
100 QtCore.QUrl(name), image)
131 QtCore.QUrl(name), image)
101 format = QtGui.QTextImageFormat()
132 format = QtGui.QTextImageFormat()
102 format.setName(name)
133 format.setName(name)
103 return format
134 return format
104
135
105 def _copy_image(self, name):
136 def _copy_image(self, name):
106 """ Copies the ImageResource with 'name' to the clipboard.
137 """ Copies the ImageResource with 'name' to the clipboard.
107 """
138 """
108 image = self._get_image(name)
139 image = self._get_image(name)
109 QtGui.QApplication.clipboard().setImage(image)
140 QtGui.QApplication.clipboard().setImage(image)
110
141
111 def _get_image(self, name):
142 def _get_image(self, name):
112 """ Returns the QImage stored as the ImageResource with 'name'.
143 """ Returns the QImage stored as the ImageResource with 'name'.
113 """
144 """
114 document = self._control.document()
145 document = self._control.document()
115 variant = document.resource(QtGui.QTextDocument.ImageResource,
146 variant = document.resource(QtGui.QTextDocument.ImageResource,
116 QtCore.QUrl(name))
147 QtCore.QUrl(name))
117 return variant.toPyObject()
148 return variant.toPyObject()
118
149
119 def _save_image(self, name, format='PNG'):
150 def _save_image(self, name, format='PNG'):
120 """ Shows a save dialog for the ImageResource with 'name'.
151 """ Shows a save dialog for the ImageResource with 'name'.
121 """
152 """
122 dialog = QtGui.QFileDialog(self._control, 'Save Image')
153 dialog = QtGui.QFileDialog(self._control, 'Save Image')
123 dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
154 dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
124 dialog.setDefaultSuffix(format.lower())
155 dialog.setDefaultSuffix(format.lower())
125 dialog.setNameFilter('%s file (*.%s)' % (format, format.lower()))
156 dialog.setNameFilter('%s file (*.%s)' % (format, format.lower()))
126 if dialog.exec_():
157 if dialog.exec_():
127 filename = dialog.selectedFiles()[0]
158 filename = dialog.selectedFiles()[0]
128 image = self._get_image(name)
159 image = self._get_image(name)
129 image.save(filename, format)
160 image.save(filename, format)
130
161
131 def image_tag(self, match, path = None, format = "png"):
162 def image_tag(self, match, path = None, format = "png"):
132 """ Return (X)HTML mark-up for the image-tag given by match.
163 """ Return (X)HTML mark-up for the image-tag given by match.
133
164
134 Parameters
165 Parameters
135 ----------
166 ----------
136 match : re.SRE_Match
167 match : re.SRE_Match
137 A match to an HTML image tag as exported by Qt, with
168 A match to an HTML image tag as exported by Qt, with
138 match.group("Name") containing the matched image ID.
169 match.group("Name") containing the matched image ID.
139
170
140 path : string|None, optional [default None]
171 path : string|None, optional [default None]
141 If not None, specifies a path to which supporting files
172 If not None, specifies a path to which supporting files
142 may be written (e.g., for linked images).
173 may be written (e.g., for linked images).
143 If None, all images are to be included inline.
174 If None, all images are to be included inline.
144
175
145 format : "png"|"svg", optional [default "png"]
176 format : "png"|"svg", optional [default "png"]
146 Format for returned or referenced images.
177 Format for returned or referenced images.
147
178
148 Subclasses supporting image display should override this
179 Subclasses supporting image display should override this
149 method.
180 method.
150 """
181 """
151
182
152 if(format == "png"):
183 if(format == "png"):
153 try:
184 try:
154 image = self._get_image(match.group("name"))
185 image = self._get_image(match.group("name"))
155 except KeyError:
186 except KeyError:
156 return "<b>Couldn't find image %s</b>" % match.group("name")
187 return "<b>Couldn't find image %s</b>" % match.group("name")
157
188
158 if(path is not None):
189 if(path is not None):
159 if not os.path.exists(path):
190 if not os.path.exists(path):
160 os.mkdir(path)
191 os.mkdir(path)
161 relpath = os.path.basename(path)
192 relpath = os.path.basename(path)
162 if(image.save("%s/qt_img%s.png" % (path,match.group("name")),
193 if(image.save("%s/qt_img%s.png" % (path,match.group("name")),
163 "PNG")):
194 "PNG")):
164 return '<img src="%s/qt_img%s.png">' % (relpath,
195 return '<img src="%s/qt_img%s.png">' % (relpath,
165 match.group("name"))
196 match.group("name"))
166 else:
197 else:
167 return "<b>Couldn't save image!</b>"
198 return "<b>Couldn't save image!</b>"
168 else:
199 else:
169 ba = QtCore.QByteArray()
200 ba = QtCore.QByteArray()
170 buffer_ = QtCore.QBuffer(ba)
201 buffer_ = QtCore.QBuffer(ba)
171 buffer_.open(QtCore.QIODevice.WriteOnly)
202 buffer_.open(QtCore.QIODevice.WriteOnly)
172 image.save(buffer_, "PNG")
203 image.save(buffer_, "PNG")
173 buffer_.close()
204 buffer_.close()
174 return '<img src="data:image/png;base64,\n%s\n" />' % (
205 return '<img src="data:image/png;base64,\n%s\n" />' % (
175 re.sub(r'(.{60})',r'\1\n',str(ba.toBase64())))
206 re.sub(r'(.{60})',r'\1\n',str(ba.toBase64())))
176
207
177 elif(format == "svg"):
208 elif(format == "svg"):
178 try:
209 try:
179 svg = str(self._name_to_svg[match.group("name")])
210 svg = str(self._name_to_svg[match.group("name")])
180 except KeyError:
211 except KeyError:
181 return "<b>Couldn't find image %s</b>" % match.group("name")
212 return "<b>Couldn't find image %s</b>" % match.group("name")
182
213
183 # Not currently checking path, because it's tricky to find a
214 # Not currently checking path, because it's tricky to find a
184 # cross-browser way to embed external SVG images (e.g., via
215 # cross-browser way to embed external SVG images (e.g., via
185 # object or embed tags).
216 # object or embed tags).
186
217
187 # Chop stand-alone header from matplotlib SVG
218 # Chop stand-alone header from matplotlib SVG
188 offset = svg.find("<svg")
219 offset = svg.find("<svg")
189 assert(offset > -1)
220 assert(offset > -1)
190
221
191 return svg[offset:]
222 return svg[offset:]
192
223
193 else:
224 else:
194 return '<b>Unrecognized image format</b>'
225 return '<b>Unrecognized image format</b>'
195
226
@@ -1,240 +1,242 b''
1 """ Defines a KernelManager that provides signals and slots.
1 """ Defines a KernelManager that provides signals and slots.
2 """
2 """
3
3
4 # System library imports.
4 # System library imports.
5 from PyQt4 import QtCore
5 from PyQt4 import QtCore
6
6
7 # IPython imports.
7 # IPython imports.
8 from IPython.utils.traitlets import Type
8 from IPython.utils.traitlets import Type
9 from IPython.zmq.kernelmanager import KernelManager, SubSocketChannel, \
9 from IPython.zmq.kernelmanager import KernelManager, SubSocketChannel, \
10 XReqSocketChannel, RepSocketChannel, HBSocketChannel
10 XReqSocketChannel, RepSocketChannel, HBSocketChannel
11 from util import MetaQObjectHasTraits, SuperQObject
11 from util import MetaQObjectHasTraits, SuperQObject
12
12
13
13
14 class SocketChannelQObject(SuperQObject):
14 class SocketChannelQObject(SuperQObject):
15
15
16 # Emitted when the channel is started.
16 # Emitted when the channel is started.
17 started = QtCore.pyqtSignal()
17 started = QtCore.pyqtSignal()
18
18
19 # Emitted when the channel is stopped.
19 # Emitted when the channel is stopped.
20 stopped = QtCore.pyqtSignal()
20 stopped = QtCore.pyqtSignal()
21
21
22 #---------------------------------------------------------------------------
22 #---------------------------------------------------------------------------
23 # 'ZmqSocketChannel' interface
23 # 'ZmqSocketChannel' interface
24 #---------------------------------------------------------------------------
24 #---------------------------------------------------------------------------
25
25
26 def start(self):
26 def start(self):
27 """ Reimplemented to emit signal.
27 """ Reimplemented to emit signal.
28 """
28 """
29 super(SocketChannelQObject, self).start()
29 super(SocketChannelQObject, self).start()
30 self.started.emit()
30 self.started.emit()
31
31
32 def stop(self):
32 def stop(self):
33 """ Reimplemented to emit signal.
33 """ Reimplemented to emit signal.
34 """
34 """
35 super(SocketChannelQObject, self).stop()
35 super(SocketChannelQObject, self).stop()
36 self.stopped.emit()
36 self.stopped.emit()
37
37
38
38
39 class QtXReqSocketChannel(SocketChannelQObject, XReqSocketChannel):
39 class QtXReqSocketChannel(SocketChannelQObject, XReqSocketChannel):
40
40
41 # Emitted when any message is received.
41 # Emitted when any message is received.
42 message_received = QtCore.pyqtSignal(object)
42 message_received = QtCore.pyqtSignal(object)
43
43
44 # Emitted when a reply has been received for the corresponding request
44 # Emitted when a reply has been received for the corresponding request
45 # type.
45 # type.
46 execute_reply = QtCore.pyqtSignal(object)
46 execute_reply = QtCore.pyqtSignal(object)
47 complete_reply = QtCore.pyqtSignal(object)
47 complete_reply = QtCore.pyqtSignal(object)
48 object_info_reply = QtCore.pyqtSignal(object)
48 object_info_reply = QtCore.pyqtSignal(object)
49
49
50 # Emitted when the first reply comes back.
50 # Emitted when the first reply comes back.
51 first_reply = QtCore.pyqtSignal()
51 first_reply = QtCore.pyqtSignal()
52
52
53 # Used by the first_reply signal logic to determine if a reply is the
53 # Used by the first_reply signal logic to determine if a reply is the
54 # first.
54 # first.
55 _handlers_called = False
55 _handlers_called = False
56
56
57 #---------------------------------------------------------------------------
57 #---------------------------------------------------------------------------
58 # 'XReqSocketChannel' interface
58 # 'XReqSocketChannel' interface
59 #---------------------------------------------------------------------------
59 #---------------------------------------------------------------------------
60
60
61 def call_handlers(self, msg):
61 def call_handlers(self, msg):
62 """ Reimplemented to emit signals instead of making callbacks.
62 """ Reimplemented to emit signals instead of making callbacks.
63 """
63 """
64 # Emit the generic signal.
64 # Emit the generic signal.
65 self.message_received.emit(msg)
65 self.message_received.emit(msg)
66
66
67 # Emit signals for specialized message types.
67 # Emit signals for specialized message types.
68 msg_type = msg['msg_type']
68 msg_type = msg['msg_type']
69 signal = getattr(self, msg_type, None)
69 signal = getattr(self, msg_type, None)
70 if signal:
70 if signal:
71 signal.emit(msg)
71 signal.emit(msg)
72
72
73 if not self._handlers_called:
73 if not self._handlers_called:
74 self.first_reply.emit()
74 self.first_reply.emit()
75 self._handlers_called = True
75 self._handlers_called = True
76
76
77 #---------------------------------------------------------------------------
77 #---------------------------------------------------------------------------
78 # 'QtXReqSocketChannel' interface
78 # 'QtXReqSocketChannel' interface
79 #---------------------------------------------------------------------------
79 #---------------------------------------------------------------------------
80
80
81 def reset_first_reply(self):
81 def reset_first_reply(self):
82 """ Reset the first_reply signal to fire again on the next reply.
82 """ Reset the first_reply signal to fire again on the next reply.
83 """
83 """
84 self._handlers_called = False
84 self._handlers_called = False
85
85
86
86
87 class QtSubSocketChannel(SocketChannelQObject, SubSocketChannel):
87 class QtSubSocketChannel(SocketChannelQObject, SubSocketChannel):
88
88
89 # Emitted when any message is received.
89 # Emitted when any message is received.
90 message_received = QtCore.pyqtSignal(object)
90 message_received = QtCore.pyqtSignal(object)
91
91
92 # Emitted when a message of type 'stream' is received.
92 # Emitted when a message of type 'stream' is received.
93 stream_received = QtCore.pyqtSignal(object)
93 stream_received = QtCore.pyqtSignal(object)
94
94
95 # Emitted when a message of type 'pyin' is received.
95 # Emitted when a message of type 'pyin' is received.
96 pyin_received = QtCore.pyqtSignal(object)
96 pyin_received = QtCore.pyqtSignal(object)
97
97
98 # Emitted when a message of type 'pyout' is received.
98 # Emitted when a message of type 'pyout' is received.
99 pyout_received = QtCore.pyqtSignal(object)
99 pyout_received = QtCore.pyqtSignal(object)
100
100
101 # Emitted when a message of type 'pyerr' is received.
101 # Emitted when a message of type 'pyerr' is received.
102 pyerr_received = QtCore.pyqtSignal(object)
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 # Emitted when a crash report message is received from the kernel's
107 # Emitted when a crash report message is received from the kernel's
105 # last-resort sys.excepthook.
108 # last-resort sys.excepthook.
106 crash_received = QtCore.pyqtSignal(object)
109 crash_received = QtCore.pyqtSignal(object)
107
110
108 # Emitted when a shutdown is noticed.
111 # Emitted when a shutdown is noticed.
109 shutdown_reply_received = QtCore.pyqtSignal(object)
112 shutdown_reply_received = QtCore.pyqtSignal(object)
110
113
111 #---------------------------------------------------------------------------
114 #---------------------------------------------------------------------------
112 # 'SubSocketChannel' interface
115 # 'SubSocketChannel' interface
113 #---------------------------------------------------------------------------
116 #---------------------------------------------------------------------------
114
117
115 def call_handlers(self, msg):
118 def call_handlers(self, msg):
116 """ Reimplemented to emit signals instead of making callbacks.
119 """ Reimplemented to emit signals instead of making callbacks.
117 """
120 """
118 # Emit the generic signal.
121 # Emit the generic signal.
119 self.message_received.emit(msg)
122 self.message_received.emit(msg)
120
121 # Emit signals for specialized message types.
123 # Emit signals for specialized message types.
122 msg_type = msg['msg_type']
124 msg_type = msg['msg_type']
123 signal = getattr(self, msg_type + '_received', None)
125 signal = getattr(self, msg_type + '_received', None)
124 if signal:
126 if signal:
125 signal.emit(msg)
127 signal.emit(msg)
126 elif msg_type in ('stdout', 'stderr'):
128 elif msg_type in ('stdout', 'stderr'):
127 self.stream_received.emit(msg)
129 self.stream_received.emit(msg)
128
130
129 def flush(self):
131 def flush(self):
130 """ Reimplemented to ensure that signals are dispatched immediately.
132 """ Reimplemented to ensure that signals are dispatched immediately.
131 """
133 """
132 super(QtSubSocketChannel, self).flush()
134 super(QtSubSocketChannel, self).flush()
133 QtCore.QCoreApplication.instance().processEvents()
135 QtCore.QCoreApplication.instance().processEvents()
134
136
135
137
136 class QtRepSocketChannel(SocketChannelQObject, RepSocketChannel):
138 class QtRepSocketChannel(SocketChannelQObject, RepSocketChannel):
137
139
138 # Emitted when any message is received.
140 # Emitted when any message is received.
139 message_received = QtCore.pyqtSignal(object)
141 message_received = QtCore.pyqtSignal(object)
140
142
141 # Emitted when an input request is received.
143 # Emitted when an input request is received.
142 input_requested = QtCore.pyqtSignal(object)
144 input_requested = QtCore.pyqtSignal(object)
143
145
144 #---------------------------------------------------------------------------
146 #---------------------------------------------------------------------------
145 # 'RepSocketChannel' interface
147 # 'RepSocketChannel' interface
146 #---------------------------------------------------------------------------
148 #---------------------------------------------------------------------------
147
149
148 def call_handlers(self, msg):
150 def call_handlers(self, msg):
149 """ Reimplemented to emit signals instead of making callbacks.
151 """ Reimplemented to emit signals instead of making callbacks.
150 """
152 """
151 # Emit the generic signal.
153 # Emit the generic signal.
152 self.message_received.emit(msg)
154 self.message_received.emit(msg)
153
155
154 # Emit signals for specialized message types.
156 # Emit signals for specialized message types.
155 msg_type = msg['msg_type']
157 msg_type = msg['msg_type']
156 if msg_type == 'input_request':
158 if msg_type == 'input_request':
157 self.input_requested.emit(msg)
159 self.input_requested.emit(msg)
158
160
159
161
160 class QtHBSocketChannel(SocketChannelQObject, HBSocketChannel):
162 class QtHBSocketChannel(SocketChannelQObject, HBSocketChannel):
161
163
162 # Emitted when the kernel has died.
164 # Emitted when the kernel has died.
163 kernel_died = QtCore.pyqtSignal(object)
165 kernel_died = QtCore.pyqtSignal(object)
164
166
165 #---------------------------------------------------------------------------
167 #---------------------------------------------------------------------------
166 # 'HBSocketChannel' interface
168 # 'HBSocketChannel' interface
167 #---------------------------------------------------------------------------
169 #---------------------------------------------------------------------------
168
170
169 def call_handlers(self, since_last_heartbeat):
171 def call_handlers(self, since_last_heartbeat):
170 """ Reimplemented to emit signals instead of making callbacks.
172 """ Reimplemented to emit signals instead of making callbacks.
171 """
173 """
172 # Emit the generic signal.
174 # Emit the generic signal.
173 self.kernel_died.emit(since_last_heartbeat)
175 self.kernel_died.emit(since_last_heartbeat)
174
176
175
177
176 class QtKernelManager(KernelManager, SuperQObject):
178 class QtKernelManager(KernelManager, SuperQObject):
177 """ A KernelManager that provides signals and slots.
179 """ A KernelManager that provides signals and slots.
178 """
180 """
179
181
180 __metaclass__ = MetaQObjectHasTraits
182 __metaclass__ = MetaQObjectHasTraits
181
183
182 # Emitted when the kernel manager has started listening.
184 # Emitted when the kernel manager has started listening.
183 started_channels = QtCore.pyqtSignal()
185 started_channels = QtCore.pyqtSignal()
184
186
185 # Emitted when the kernel manager has stopped listening.
187 # Emitted when the kernel manager has stopped listening.
186 stopped_channels = QtCore.pyqtSignal()
188 stopped_channels = QtCore.pyqtSignal()
187
189
188 # Use Qt-specific channel classes that emit signals.
190 # Use Qt-specific channel classes that emit signals.
189 sub_channel_class = Type(QtSubSocketChannel)
191 sub_channel_class = Type(QtSubSocketChannel)
190 xreq_channel_class = Type(QtXReqSocketChannel)
192 xreq_channel_class = Type(QtXReqSocketChannel)
191 rep_channel_class = Type(QtRepSocketChannel)
193 rep_channel_class = Type(QtRepSocketChannel)
192 hb_channel_class = Type(QtHBSocketChannel)
194 hb_channel_class = Type(QtHBSocketChannel)
193
195
194 #---------------------------------------------------------------------------
196 #---------------------------------------------------------------------------
195 # 'KernelManager' interface
197 # 'KernelManager' interface
196 #---------------------------------------------------------------------------
198 #---------------------------------------------------------------------------
197
199
198 #------ Kernel process management ------------------------------------------
200 #------ Kernel process management ------------------------------------------
199
201
200 def start_kernel(self, *args, **kw):
202 def start_kernel(self, *args, **kw):
201 """ Reimplemented for proper heartbeat management.
203 """ Reimplemented for proper heartbeat management.
202 """
204 """
203 if self._xreq_channel is not None:
205 if self._xreq_channel is not None:
204 self._xreq_channel.reset_first_reply()
206 self._xreq_channel.reset_first_reply()
205 super(QtKernelManager, self).start_kernel(*args, **kw)
207 super(QtKernelManager, self).start_kernel(*args, **kw)
206
208
207 #------ Channel management -------------------------------------------------
209 #------ Channel management -------------------------------------------------
208
210
209 def start_channels(self, *args, **kw):
211 def start_channels(self, *args, **kw):
210 """ Reimplemented to emit signal.
212 """ Reimplemented to emit signal.
211 """
213 """
212 super(QtKernelManager, self).start_channels(*args, **kw)
214 super(QtKernelManager, self).start_channels(*args, **kw)
213 self.started_channels.emit()
215 self.started_channels.emit()
214
216
215 def stop_channels(self):
217 def stop_channels(self):
216 """ Reimplemented to emit signal.
218 """ Reimplemented to emit signal.
217 """
219 """
218 super(QtKernelManager, self).stop_channels()
220 super(QtKernelManager, self).stop_channels()
219 self.stopped_channels.emit()
221 self.stopped_channels.emit()
220
222
221 @property
223 @property
222 def xreq_channel(self):
224 def xreq_channel(self):
223 """ Reimplemented for proper heartbeat management.
225 """ Reimplemented for proper heartbeat management.
224 """
226 """
225 if self._xreq_channel is None:
227 if self._xreq_channel is None:
226 self._xreq_channel = super(QtKernelManager, self).xreq_channel
228 self._xreq_channel = super(QtKernelManager, self).xreq_channel
227 self._xreq_channel.first_reply.connect(self._first_reply)
229 self._xreq_channel.first_reply.connect(self._first_reply)
228 return self._xreq_channel
230 return self._xreq_channel
229
231
230 #---------------------------------------------------------------------------
232 #---------------------------------------------------------------------------
231 # Protected interface
233 # Protected interface
232 #---------------------------------------------------------------------------
234 #---------------------------------------------------------------------------
233
235
234 def _first_reply(self):
236 def _first_reply(self):
235 """ Unpauses the heartbeat channel when the first reply is received on
237 """ Unpauses the heartbeat channel when the first reply is received on
236 the execute channel. Note that this will *not* start the heartbeat
238 the execute channel. Note that this will *not* start the heartbeat
237 channel if it is not already running!
239 channel if it is not already running!
238 """
240 """
239 if self._hb_channel is not None:
241 if self._hb_channel is not None:
240 self._hb_channel.unpause()
242 self._hb_channel.unpause()
@@ -1,629 +1,632 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """A simple interactive kernel that talks to a frontend over 0MQ.
2 """A simple interactive kernel that talks to a frontend over 0MQ.
3
3
4 Things to do:
4 Things to do:
5
5
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 call set_parent on all the PUB objects with the message about to be executed.
7 call set_parent on all the PUB objects with the message about to be executed.
8 * Implement random port and security key logic.
8 * Implement random port and security key logic.
9 * Implement control messages.
9 * Implement control messages.
10 * Implement event loop and poll version.
10 * Implement event loop and poll version.
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Standard library imports.
18 # Standard library imports.
19 import __builtin__
19 import __builtin__
20 import atexit
20 import atexit
21 import sys
21 import sys
22 import time
22 import time
23 import traceback
23 import traceback
24
24
25 # System library imports.
25 # System library imports.
26 import zmq
26 import zmq
27
27
28 # Local imports.
28 # Local imports.
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.utils import io
30 from IPython.utils import io
31 from IPython.utils.jsonutil import json_clean
31 from IPython.utils.jsonutil import json_clean
32 from IPython.lib import pylabtools
32 from IPython.lib import pylabtools
33 from IPython.utils.traitlets import Instance, Float
33 from IPython.utils.traitlets import Instance, Float
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
35 start_kernel)
35 start_kernel)
36 from iostream import OutStream
36 from iostream import OutStream
37 from session import Session, Message
37 from session import Session, Message
38 from zmqshell import ZMQInteractiveShell
38 from zmqshell import ZMQInteractiveShell
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Main kernel class
41 # Main kernel class
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 class Kernel(Configurable):
44 class Kernel(Configurable):
45
45
46 #---------------------------------------------------------------------------
46 #---------------------------------------------------------------------------
47 # Kernel interface
47 # Kernel interface
48 #---------------------------------------------------------------------------
48 #---------------------------------------------------------------------------
49
49
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 session = Instance(Session)
51 session = Instance(Session)
52 reply_socket = Instance('zmq.Socket')
52 reply_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
55
55
56 # Private interface
56 # Private interface
57
57
58 # Time to sleep after flushing the stdout/err buffers in each execute
58 # Time to sleep after flushing the stdout/err buffers in each execute
59 # cycle. While this introduces a hard limit on the minimal latency of the
59 # cycle. While this introduces a hard limit on the minimal latency of the
60 # execute cycle, it helps prevent output synchronization problems for
60 # execute cycle, it helps prevent output synchronization problems for
61 # clients.
61 # clients.
62 # Units are in seconds. The minimum zmq latency on local host is probably
62 # Units are in seconds. The minimum zmq latency on local host is probably
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 # a little if it's not enough after more interactive testing.
64 # a little if it's not enough after more interactive testing.
65 _execute_sleep = Float(0.0005, config=True)
65 _execute_sleep = Float(0.0005, config=True)
66
66
67 # Frequency of the kernel's event loop.
67 # Frequency of the kernel's event loop.
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 # adapt to milliseconds.
69 # adapt to milliseconds.
70 _poll_interval = Float(0.05, config=True)
70 _poll_interval = Float(0.05, config=True)
71
71
72 # If the shutdown was requested over the network, we leave here the
72 # If the shutdown was requested over the network, we leave here the
73 # necessary reply message so it can be sent by our registered atexit
73 # necessary reply message so it can be sent by our registered atexit
74 # handler. This ensures that the reply is only sent to clients truly at
74 # handler. This ensures that the reply is only sent to clients truly at
75 # the end of our shutdown process (which happens after the underlying
75 # the end of our shutdown process (which happens after the underlying
76 # IPython shell's own shutdown).
76 # IPython shell's own shutdown).
77 _shutdown_message = None
77 _shutdown_message = None
78
78
79 # This is a dict of port number that the kernel is listening on. It is set
79 # This is a dict of port number that the kernel is listening on. It is set
80 # by record_ports and used by connect_request.
80 # by record_ports and used by connect_request.
81 _recorded_ports = None
81 _recorded_ports = None
82
82
83 def __init__(self, **kwargs):
83 def __init__(self, **kwargs):
84 super(Kernel, self).__init__(**kwargs)
84 super(Kernel, self).__init__(**kwargs)
85
85
86 # Before we even start up the shell, register *first* our exit handlers
86 # Before we even start up the shell, register *first* our exit handlers
87 # so they come before the shell's
87 # so they come before the shell's
88 atexit.register(self._at_shutdown)
88 atexit.register(self._at_shutdown)
89
89
90 # Initialize the InteractiveShell subclass
90 # Initialize the InteractiveShell subclass
91 self.shell = ZMQInteractiveShell.instance()
91 self.shell = ZMQInteractiveShell.instance()
92 self.shell.displayhook.session = self.session
92 self.shell.displayhook.session = self.session
93 self.shell.displayhook.pub_socket = self.pub_socket
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 # TMP - hack while developing
97 # TMP - hack while developing
96 self.shell._reply_content = None
98 self.shell._reply_content = None
97
99
98 # Build dict of handlers for message types
100 # Build dict of handlers for message types
99 msg_types = [ 'execute_request', 'complete_request',
101 msg_types = [ 'execute_request', 'complete_request',
100 'object_info_request', 'history_request',
102 'object_info_request', 'history_request',
101 'connect_request', 'shutdown_request']
103 'connect_request', 'shutdown_request']
102 self.handlers = {}
104 self.handlers = {}
103 for msg_type in msg_types:
105 for msg_type in msg_types:
104 self.handlers[msg_type] = getattr(self, msg_type)
106 self.handlers[msg_type] = getattr(self, msg_type)
105
107
106 def do_one_iteration(self):
108 def do_one_iteration(self):
107 """Do one iteration of the kernel's evaluation loop.
109 """Do one iteration of the kernel's evaluation loop.
108 """
110 """
109 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
111 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
110 if msg is None:
112 if msg is None:
111 return
113 return
112
114
113 # This assert will raise in versions of zeromq 2.0.7 and lesser.
115 # This assert will raise in versions of zeromq 2.0.7 and lesser.
114 # We now require 2.0.8 or above, so we can uncomment for safety.
116 # We now require 2.0.8 or above, so we can uncomment for safety.
115 # print(ident,msg, file=sys.__stdout__)
117 # print(ident,msg, file=sys.__stdout__)
116 assert ident is not None, "Missing message part."
118 assert ident is not None, "Missing message part."
117
119
118 # Print some info about this message and leave a '--->' marker, so it's
120 # Print some info about this message and leave a '--->' marker, so it's
119 # easier to trace visually the message chain when debugging. Each
121 # easier to trace visually the message chain when debugging. Each
120 # handler prints its message at the end.
122 # handler prints its message at the end.
121 # Eventually we'll move these from stdout to a logger.
123 # Eventually we'll move these from stdout to a logger.
122 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
124 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
123 io.raw_print(' Content: ', msg['content'],
125 io.raw_print(' Content: ', msg['content'],
124 '\n --->\n ', sep='', end='')
126 '\n --->\n ', sep='', end='')
125
127
126 # Find and call actual handler for message
128 # Find and call actual handler for message
127 handler = self.handlers.get(msg['msg_type'], None)
129 handler = self.handlers.get(msg['msg_type'], None)
128 if handler is None:
130 if handler is None:
129 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
131 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
130 else:
132 else:
131 handler(ident, msg)
133 handler(ident, msg)
132
134
133 # Check whether we should exit, in case the incoming message set the
135 # Check whether we should exit, in case the incoming message set the
134 # exit flag on
136 # exit flag on
135 if self.shell.exit_now:
137 if self.shell.exit_now:
136 io.raw_print('\nExiting IPython kernel...')
138 io.raw_print('\nExiting IPython kernel...')
137 # We do a normal, clean exit, which allows any actions registered
139 # We do a normal, clean exit, which allows any actions registered
138 # via atexit (such as history saving) to take place.
140 # via atexit (such as history saving) to take place.
139 sys.exit(0)
141 sys.exit(0)
140
142
141
143
142 def start(self):
144 def start(self):
143 """ Start the kernel main loop.
145 """ Start the kernel main loop.
144 """
146 """
145 while True:
147 while True:
146 time.sleep(self._poll_interval)
148 time.sleep(self._poll_interval)
147 self.do_one_iteration()
149 self.do_one_iteration()
148
150
149 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
151 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
150 """Record the ports that this kernel is using.
152 """Record the ports that this kernel is using.
151
153
152 The creator of the Kernel instance must call this methods if they
154 The creator of the Kernel instance must call this methods if they
153 want the :meth:`connect_request` method to return the port numbers.
155 want the :meth:`connect_request` method to return the port numbers.
154 """
156 """
155 self._recorded_ports = {
157 self._recorded_ports = {
156 'xrep_port' : xrep_port,
158 'xrep_port' : xrep_port,
157 'pub_port' : pub_port,
159 'pub_port' : pub_port,
158 'req_port' : req_port,
160 'req_port' : req_port,
159 'hb_port' : hb_port
161 'hb_port' : hb_port
160 }
162 }
161
163
162 #---------------------------------------------------------------------------
164 #---------------------------------------------------------------------------
163 # Kernel request handlers
165 # Kernel request handlers
164 #---------------------------------------------------------------------------
166 #---------------------------------------------------------------------------
165
167
166 def _publish_pyin(self, code, parent):
168 def _publish_pyin(self, code, parent):
167 """Publish the code request on the pyin stream."""
169 """Publish the code request on the pyin stream."""
168
170
169 pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent)
171 pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent)
170
172
171 def execute_request(self, ident, parent):
173 def execute_request(self, ident, parent):
172
174
173 status_msg = self.session.send(self.pub_socket,
175 status_msg = self.session.send(self.pub_socket,
174 u'status',
176 u'status',
175 {u'execution_state':u'busy'},
177 {u'execution_state':u'busy'},
176 parent=parent
178 parent=parent
177 )
179 )
178
180
179 try:
181 try:
180 content = parent[u'content']
182 content = parent[u'content']
181 code = content[u'code']
183 code = content[u'code']
182 silent = content[u'silent']
184 silent = content[u'silent']
183 except:
185 except:
184 io.raw_print_err("Got bad msg: ")
186 io.raw_print_err("Got bad msg: ")
185 io.raw_print_err(Message(parent))
187 io.raw_print_err(Message(parent))
186 return
188 return
187
189
188 shell = self.shell # we'll need this a lot here
190 shell = self.shell # we'll need this a lot here
189
191
190 # Replace raw_input. Note that is not sufficient to replace
192 # Replace raw_input. Note that is not sufficient to replace
191 # raw_input in the user namespace.
193 # raw_input in the user namespace.
192 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
194 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
193 __builtin__.raw_input = raw_input
195 __builtin__.raw_input = raw_input
194
196
195 # Set the parent message of the display hook and out streams.
197 # Set the parent message of the display hook and out streams.
196 shell.displayhook.set_parent(parent)
198 shell.displayhook.set_parent(parent)
199 shell.display_pub.set_parent(parent)
197 sys.stdout.set_parent(parent)
200 sys.stdout.set_parent(parent)
198 sys.stderr.set_parent(parent)
201 sys.stderr.set_parent(parent)
199
202
200 # Re-broadcast our input for the benefit of listening clients, and
203 # Re-broadcast our input for the benefit of listening clients, and
201 # start computing output
204 # start computing output
202 if not silent:
205 if not silent:
203 self._publish_pyin(code, parent)
206 self._publish_pyin(code, parent)
204
207
205 reply_content = {}
208 reply_content = {}
206 try:
209 try:
207 if silent:
210 if silent:
208 # run_code uses 'exec' mode, so no displayhook will fire, and it
211 # run_code uses 'exec' mode, so no displayhook will fire, and it
209 # doesn't call logging or history manipulations. Print
212 # doesn't call logging or history manipulations. Print
210 # statements in that code will obviously still execute.
213 # statements in that code will obviously still execute.
211 shell.run_code(code)
214 shell.run_code(code)
212 else:
215 else:
213 # FIXME: the shell calls the exception handler itself.
216 # FIXME: the shell calls the exception handler itself.
214 shell._reply_content = None
217 shell._reply_content = None
215 shell.run_cell(code)
218 shell.run_cell(code)
216 except:
219 except:
217 status = u'error'
220 status = u'error'
218 # FIXME: this code right now isn't being used yet by default,
221 # FIXME: this code right now isn't being used yet by default,
219 # because the runlines() call above directly fires off exception
222 # because the runlines() call above directly fires off exception
220 # reporting. This code, therefore, is only active in the scenario
223 # reporting. This code, therefore, is only active in the scenario
221 # where runlines itself has an unhandled exception. We need to
224 # where runlines itself has an unhandled exception. We need to
222 # uniformize this, for all exception construction to come from a
225 # uniformize this, for all exception construction to come from a
223 # single location in the codbase.
226 # single location in the codbase.
224 etype, evalue, tb = sys.exc_info()
227 etype, evalue, tb = sys.exc_info()
225 tb_list = traceback.format_exception(etype, evalue, tb)
228 tb_list = traceback.format_exception(etype, evalue, tb)
226 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
229 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
227 else:
230 else:
228 status = u'ok'
231 status = u'ok'
229
232
230 reply_content[u'status'] = status
233 reply_content[u'status'] = status
231
234
232 # Return the execution counter so clients can display prompts
235 # Return the execution counter so clients can display prompts
233 reply_content['execution_count'] = shell.execution_count -1
236 reply_content['execution_count'] = shell.execution_count -1
234
237
235 # FIXME - fish exception info out of shell, possibly left there by
238 # FIXME - fish exception info out of shell, possibly left there by
236 # runlines. We'll need to clean up this logic later.
239 # runlines. We'll need to clean up this logic later.
237 if shell._reply_content is not None:
240 if shell._reply_content is not None:
238 reply_content.update(shell._reply_content)
241 reply_content.update(shell._reply_content)
239
242
240 # At this point, we can tell whether the main code execution succeeded
243 # At this point, we can tell whether the main code execution succeeded
241 # or not. If it did, we proceed to evaluate user_variables/expressions
244 # or not. If it did, we proceed to evaluate user_variables/expressions
242 if reply_content['status'] == 'ok':
245 if reply_content['status'] == 'ok':
243 reply_content[u'user_variables'] = \
246 reply_content[u'user_variables'] = \
244 shell.user_variables(content[u'user_variables'])
247 shell.user_variables(content[u'user_variables'])
245 reply_content[u'user_expressions'] = \
248 reply_content[u'user_expressions'] = \
246 shell.user_expressions(content[u'user_expressions'])
249 shell.user_expressions(content[u'user_expressions'])
247 else:
250 else:
248 # If there was an error, don't even try to compute variables or
251 # If there was an error, don't even try to compute variables or
249 # expressions
252 # expressions
250 reply_content[u'user_variables'] = {}
253 reply_content[u'user_variables'] = {}
251 reply_content[u'user_expressions'] = {}
254 reply_content[u'user_expressions'] = {}
252
255
253 # Payloads should be retrieved regardless of outcome, so we can both
256 # Payloads should be retrieved regardless of outcome, so we can both
254 # recover partial output (that could have been generated early in a
257 # recover partial output (that could have been generated early in a
255 # block, before an error) and clear the payload system always.
258 # block, before an error) and clear the payload system always.
256 reply_content[u'payload'] = shell.payload_manager.read_payload()
259 reply_content[u'payload'] = shell.payload_manager.read_payload()
257 # Be agressive about clearing the payload because we don't want
260 # Be agressive about clearing the payload because we don't want
258 # it to sit in memory until the next execute_request comes in.
261 # it to sit in memory until the next execute_request comes in.
259 shell.payload_manager.clear_payload()
262 shell.payload_manager.clear_payload()
260
263
261 # Send the reply.
264 # Send the reply.
262 reply_msg = self.session.send(self.reply_socket, u'execute_reply', reply_content, parent, ident=ident)
265 reply_msg = self.session.send(self.reply_socket, u'execute_reply', reply_content, parent, ident=ident)
263 io.raw_print(reply_msg)
266 io.raw_print(reply_msg)
264
267
265 # Flush output before sending the reply.
268 # Flush output before sending the reply.
266 sys.stdout.flush()
269 sys.stdout.flush()
267 sys.stderr.flush()
270 sys.stderr.flush()
268 # FIXME: on rare occasions, the flush doesn't seem to make it to the
271 # FIXME: on rare occasions, the flush doesn't seem to make it to the
269 # clients... This seems to mitigate the problem, but we definitely need
272 # clients... This seems to mitigate the problem, but we definitely need
270 # to better understand what's going on.
273 # to better understand what's going on.
271 if self._execute_sleep:
274 if self._execute_sleep:
272 time.sleep(self._execute_sleep)
275 time.sleep(self._execute_sleep)
273
276
274 if reply_msg['content']['status'] == u'error':
277 if reply_msg['content']['status'] == u'error':
275 self._abort_queue()
278 self._abort_queue()
276
279
277 status_msg = self.session.send(self.pub_socket,
280 status_msg = self.session.send(self.pub_socket,
278 u'status',
281 u'status',
279 {u'execution_state':u'idle'},
282 {u'execution_state':u'idle'},
280 parent=parent
283 parent=parent
281 )
284 )
282
285
283 def complete_request(self, ident, parent):
286 def complete_request(self, ident, parent):
284 txt, matches = self._complete(parent)
287 txt, matches = self._complete(parent)
285 matches = {'matches' : matches,
288 matches = {'matches' : matches,
286 'matched_text' : txt,
289 'matched_text' : txt,
287 'status' : 'ok'}
290 'status' : 'ok'}
288 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
291 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
289 matches, parent, ident)
292 matches, parent, ident)
290 io.raw_print(completion_msg)
293 io.raw_print(completion_msg)
291
294
292 def object_info_request(self, ident, parent):
295 def object_info_request(self, ident, parent):
293 object_info = self.shell.object_inspect(parent['content']['oname'])
296 object_info = self.shell.object_inspect(parent['content']['oname'])
294 # Before we send this object over, we scrub it for JSON usage
297 # Before we send this object over, we scrub it for JSON usage
295 oinfo = json_clean(object_info)
298 oinfo = json_clean(object_info)
296 msg = self.session.send(self.reply_socket, 'object_info_reply',
299 msg = self.session.send(self.reply_socket, 'object_info_reply',
297 oinfo, parent, ident)
300 oinfo, parent, ident)
298 io.raw_print(msg)
301 io.raw_print(msg)
299
302
300 def history_request(self, ident, parent):
303 def history_request(self, ident, parent):
301 output = parent['content']['output']
304 output = parent['content']['output']
302 index = parent['content']['index']
305 index = parent['content']['index']
303 raw = parent['content']['raw']
306 raw = parent['content']['raw']
304 hist = self.shell.get_history(index=index, raw=raw, output=output)
307 hist = self.shell.get_history(index=index, raw=raw, output=output)
305 content = {'history' : hist}
308 content = {'history' : hist}
306 msg = self.session.send(self.reply_socket, 'history_reply',
309 msg = self.session.send(self.reply_socket, 'history_reply',
307 content, parent, ident)
310 content, parent, ident)
308 io.raw_print(msg)
311 io.raw_print(msg)
309
312
310 def connect_request(self, ident, parent):
313 def connect_request(self, ident, parent):
311 if self._recorded_ports is not None:
314 if self._recorded_ports is not None:
312 content = self._recorded_ports.copy()
315 content = self._recorded_ports.copy()
313 else:
316 else:
314 content = {}
317 content = {}
315 msg = self.session.send(self.reply_socket, 'connect_reply',
318 msg = self.session.send(self.reply_socket, 'connect_reply',
316 content, parent, ident)
319 content, parent, ident)
317 io.raw_print(msg)
320 io.raw_print(msg)
318
321
319 def shutdown_request(self, ident, parent):
322 def shutdown_request(self, ident, parent):
320 self.shell.exit_now = True
323 self.shell.exit_now = True
321 self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent)
324 self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent)
322 sys.exit(0)
325 sys.exit(0)
323
326
324 #---------------------------------------------------------------------------
327 #---------------------------------------------------------------------------
325 # Protected interface
328 # Protected interface
326 #---------------------------------------------------------------------------
329 #---------------------------------------------------------------------------
327
330
328 def _abort_queue(self):
331 def _abort_queue(self):
329 while True:
332 while True:
330 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
333 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
331 if msg is None:
334 if msg is None:
332 break
335 break
333 else:
336 else:
334 assert ident is not None, \
337 assert ident is not None, \
335 "Unexpected missing message part."
338 "Unexpected missing message part."
336 io.raw_print("Aborting:\n", Message(msg))
339 io.raw_print("Aborting:\n", Message(msg))
337 msg_type = msg['msg_type']
340 msg_type = msg['msg_type']
338 reply_type = msg_type.split('_')[0] + '_reply'
341 reply_type = msg_type.split('_')[0] + '_reply'
339 reply_msg = self.session.send(self.reply_socket, reply_type,
342 reply_msg = self.session.send(self.reply_socket, reply_type,
340 {'status' : 'aborted'}, msg, ident=ident)
343 {'status' : 'aborted'}, msg, ident=ident)
341 io.raw_print(reply_msg)
344 io.raw_print(reply_msg)
342 # We need to wait a bit for requests to come in. This can probably
345 # We need to wait a bit for requests to come in. This can probably
343 # be set shorter for true asynchronous clients.
346 # be set shorter for true asynchronous clients.
344 time.sleep(0.1)
347 time.sleep(0.1)
345
348
346 def _raw_input(self, prompt, ident, parent):
349 def _raw_input(self, prompt, ident, parent):
347 # Flush output before making the request.
350 # Flush output before making the request.
348 sys.stderr.flush()
351 sys.stderr.flush()
349 sys.stdout.flush()
352 sys.stdout.flush()
350
353
351 # Send the input request.
354 # Send the input request.
352 content = dict(prompt=prompt)
355 content = dict(prompt=prompt)
353 msg = self.session.send(self.req_socket, u'input_request', content, parent)
356 msg = self.session.send(self.req_socket, u'input_request', content, parent)
354
357
355 # Await a response.
358 # Await a response.
356 ident, reply = self.session.recv(self.req_socket, 0)
359 ident, reply = self.session.recv(self.req_socket, 0)
357 try:
360 try:
358 value = reply['content']['value']
361 value = reply['content']['value']
359 except:
362 except:
360 io.raw_print_err("Got bad raw_input reply: ")
363 io.raw_print_err("Got bad raw_input reply: ")
361 io.raw_print_err(Message(parent))
364 io.raw_print_err(Message(parent))
362 value = ''
365 value = ''
363 return value
366 return value
364
367
365 def _complete(self, msg):
368 def _complete(self, msg):
366 c = msg['content']
369 c = msg['content']
367 try:
370 try:
368 cpos = int(c['cursor_pos'])
371 cpos = int(c['cursor_pos'])
369 except:
372 except:
370 # If we don't get something that we can convert to an integer, at
373 # If we don't get something that we can convert to an integer, at
371 # least attempt the completion guessing the cursor is at the end of
374 # least attempt the completion guessing the cursor is at the end of
372 # the text, if there's any, and otherwise of the line
375 # the text, if there's any, and otherwise of the line
373 cpos = len(c['text'])
376 cpos = len(c['text'])
374 if cpos==0:
377 if cpos==0:
375 cpos = len(c['line'])
378 cpos = len(c['line'])
376 return self.shell.complete(c['text'], c['line'], cpos)
379 return self.shell.complete(c['text'], c['line'], cpos)
377
380
378 def _object_info(self, context):
381 def _object_info(self, context):
379 symbol, leftover = self._symbol_from_context(context)
382 symbol, leftover = self._symbol_from_context(context)
380 if symbol is not None and not leftover:
383 if symbol is not None and not leftover:
381 doc = getattr(symbol, '__doc__', '')
384 doc = getattr(symbol, '__doc__', '')
382 else:
385 else:
383 doc = ''
386 doc = ''
384 object_info = dict(docstring = doc)
387 object_info = dict(docstring = doc)
385 return object_info
388 return object_info
386
389
387 def _symbol_from_context(self, context):
390 def _symbol_from_context(self, context):
388 if not context:
391 if not context:
389 return None, context
392 return None, context
390
393
391 base_symbol_string = context[0]
394 base_symbol_string = context[0]
392 symbol = self.shell.user_ns.get(base_symbol_string, None)
395 symbol = self.shell.user_ns.get(base_symbol_string, None)
393 if symbol is None:
396 if symbol is None:
394 symbol = __builtin__.__dict__.get(base_symbol_string, None)
397 symbol = __builtin__.__dict__.get(base_symbol_string, None)
395 if symbol is None:
398 if symbol is None:
396 return None, context
399 return None, context
397
400
398 context = context[1:]
401 context = context[1:]
399 for i, name in enumerate(context):
402 for i, name in enumerate(context):
400 new_symbol = getattr(symbol, name, None)
403 new_symbol = getattr(symbol, name, None)
401 if new_symbol is None:
404 if new_symbol is None:
402 return symbol, context[i:]
405 return symbol, context[i:]
403 else:
406 else:
404 symbol = new_symbol
407 symbol = new_symbol
405
408
406 return symbol, []
409 return symbol, []
407
410
408 def _at_shutdown(self):
411 def _at_shutdown(self):
409 """Actions taken at shutdown by the kernel, called by python's atexit.
412 """Actions taken at shutdown by the kernel, called by python's atexit.
410 """
413 """
411 # io.rprint("Kernel at_shutdown") # dbg
414 # io.rprint("Kernel at_shutdown") # dbg
412 if self._shutdown_message is not None:
415 if self._shutdown_message is not None:
413 self.session.send(self.reply_socket, self._shutdown_message)
416 self.session.send(self.reply_socket, self._shutdown_message)
414 self.session.send(self.pub_socket, self._shutdown_message)
417 self.session.send(self.pub_socket, self._shutdown_message)
415 io.raw_print(self._shutdown_message)
418 io.raw_print(self._shutdown_message)
416 # A very short sleep to give zmq time to flush its message buffers
419 # A very short sleep to give zmq time to flush its message buffers
417 # before Python truly shuts down.
420 # before Python truly shuts down.
418 time.sleep(0.01)
421 time.sleep(0.01)
419
422
420
423
421 class QtKernel(Kernel):
424 class QtKernel(Kernel):
422 """A Kernel subclass with Qt support."""
425 """A Kernel subclass with Qt support."""
423
426
424 def start(self):
427 def start(self):
425 """Start a kernel with QtPy4 event loop integration."""
428 """Start a kernel with QtPy4 event loop integration."""
426
429
427 from PyQt4 import QtCore
430 from PyQt4 import QtCore
428 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
431 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
429
432
430 self.app = get_app_qt4([" "])
433 self.app = get_app_qt4([" "])
431 self.app.setQuitOnLastWindowClosed(False)
434 self.app.setQuitOnLastWindowClosed(False)
432 self.timer = QtCore.QTimer()
435 self.timer = QtCore.QTimer()
433 self.timer.timeout.connect(self.do_one_iteration)
436 self.timer.timeout.connect(self.do_one_iteration)
434 # Units for the timer are in milliseconds
437 # Units for the timer are in milliseconds
435 self.timer.start(1000*self._poll_interval)
438 self.timer.start(1000*self._poll_interval)
436 start_event_loop_qt4(self.app)
439 start_event_loop_qt4(self.app)
437
440
438
441
439 class WxKernel(Kernel):
442 class WxKernel(Kernel):
440 """A Kernel subclass with Wx support."""
443 """A Kernel subclass with Wx support."""
441
444
442 def start(self):
445 def start(self):
443 """Start a kernel with wx event loop support."""
446 """Start a kernel with wx event loop support."""
444
447
445 import wx
448 import wx
446 from IPython.lib.guisupport import start_event_loop_wx
449 from IPython.lib.guisupport import start_event_loop_wx
447
450
448 doi = self.do_one_iteration
451 doi = self.do_one_iteration
449 # Wx uses milliseconds
452 # Wx uses milliseconds
450 poll_interval = int(1000*self._poll_interval)
453 poll_interval = int(1000*self._poll_interval)
451
454
452 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
455 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
453 # We make the Frame hidden when we create it in the main app below.
456 # We make the Frame hidden when we create it in the main app below.
454 class TimerFrame(wx.Frame):
457 class TimerFrame(wx.Frame):
455 def __init__(self, func):
458 def __init__(self, func):
456 wx.Frame.__init__(self, None, -1)
459 wx.Frame.__init__(self, None, -1)
457 self.timer = wx.Timer(self)
460 self.timer = wx.Timer(self)
458 # Units for the timer are in milliseconds
461 # Units for the timer are in milliseconds
459 self.timer.Start(poll_interval)
462 self.timer.Start(poll_interval)
460 self.Bind(wx.EVT_TIMER, self.on_timer)
463 self.Bind(wx.EVT_TIMER, self.on_timer)
461 self.func = func
464 self.func = func
462
465
463 def on_timer(self, event):
466 def on_timer(self, event):
464 self.func()
467 self.func()
465
468
466 # We need a custom wx.App to create our Frame subclass that has the
469 # We need a custom wx.App to create our Frame subclass that has the
467 # wx.Timer to drive the ZMQ event loop.
470 # wx.Timer to drive the ZMQ event loop.
468 class IPWxApp(wx.App):
471 class IPWxApp(wx.App):
469 def OnInit(self):
472 def OnInit(self):
470 self.frame = TimerFrame(doi)
473 self.frame = TimerFrame(doi)
471 self.frame.Show(False)
474 self.frame.Show(False)
472 return True
475 return True
473
476
474 # The redirect=False here makes sure that wx doesn't replace
477 # The redirect=False here makes sure that wx doesn't replace
475 # sys.stdout/stderr with its own classes.
478 # sys.stdout/stderr with its own classes.
476 self.app = IPWxApp(redirect=False)
479 self.app = IPWxApp(redirect=False)
477 start_event_loop_wx(self.app)
480 start_event_loop_wx(self.app)
478
481
479
482
480 class TkKernel(Kernel):
483 class TkKernel(Kernel):
481 """A Kernel subclass with Tk support."""
484 """A Kernel subclass with Tk support."""
482
485
483 def start(self):
486 def start(self):
484 """Start a Tk enabled event loop."""
487 """Start a Tk enabled event loop."""
485
488
486 import Tkinter
489 import Tkinter
487 doi = self.do_one_iteration
490 doi = self.do_one_iteration
488 # Tk uses milliseconds
491 # Tk uses milliseconds
489 poll_interval = int(1000*self._poll_interval)
492 poll_interval = int(1000*self._poll_interval)
490 # For Tkinter, we create a Tk object and call its withdraw method.
493 # For Tkinter, we create a Tk object and call its withdraw method.
491 class Timer(object):
494 class Timer(object):
492 def __init__(self, func):
495 def __init__(self, func):
493 self.app = Tkinter.Tk()
496 self.app = Tkinter.Tk()
494 self.app.withdraw()
497 self.app.withdraw()
495 self.func = func
498 self.func = func
496
499
497 def on_timer(self):
500 def on_timer(self):
498 self.func()
501 self.func()
499 self.app.after(poll_interval, self.on_timer)
502 self.app.after(poll_interval, self.on_timer)
500
503
501 def start(self):
504 def start(self):
502 self.on_timer() # Call it once to get things going.
505 self.on_timer() # Call it once to get things going.
503 self.app.mainloop()
506 self.app.mainloop()
504
507
505 self.timer = Timer(doi)
508 self.timer = Timer(doi)
506 self.timer.start()
509 self.timer.start()
507
510
508
511
509 class GTKKernel(Kernel):
512 class GTKKernel(Kernel):
510 """A Kernel subclass with GTK support."""
513 """A Kernel subclass with GTK support."""
511
514
512 def start(self):
515 def start(self):
513 """Start the kernel, coordinating with the GTK event loop"""
516 """Start the kernel, coordinating with the GTK event loop"""
514 from .gui.gtkembed import GTKEmbed
517 from .gui.gtkembed import GTKEmbed
515
518
516 gtk_kernel = GTKEmbed(self)
519 gtk_kernel = GTKEmbed(self)
517 gtk_kernel.start()
520 gtk_kernel.start()
518
521
519
522
520 #-----------------------------------------------------------------------------
523 #-----------------------------------------------------------------------------
521 # Kernel main and launch functions
524 # Kernel main and launch functions
522 #-----------------------------------------------------------------------------
525 #-----------------------------------------------------------------------------
523
526
524 def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0,
527 def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0,
525 independent=False, pylab=False, colors=None):
528 independent=False, pylab=False, colors=None):
526 """Launches a localhost kernel, binding to the specified ports.
529 """Launches a localhost kernel, binding to the specified ports.
527
530
528 Parameters
531 Parameters
529 ----------
532 ----------
530 ip : str, optional
533 ip : str, optional
531 The ip address the kernel will bind to.
534 The ip address the kernel will bind to.
532
535
533 xrep_port : int, optional
536 xrep_port : int, optional
534 The port to use for XREP channel.
537 The port to use for XREP channel.
535
538
536 pub_port : int, optional
539 pub_port : int, optional
537 The port to use for the SUB channel.
540 The port to use for the SUB channel.
538
541
539 req_port : int, optional
542 req_port : int, optional
540 The port to use for the REQ (raw input) channel.
543 The port to use for the REQ (raw input) channel.
541
544
542 hb_port : int, optional
545 hb_port : int, optional
543 The port to use for the hearbeat REP channel.
546 The port to use for the hearbeat REP channel.
544
547
545 independent : bool, optional (default False)
548 independent : bool, optional (default False)
546 If set, the kernel process is guaranteed to survive if this process
549 If set, the kernel process is guaranteed to survive if this process
547 dies. If not set, an effort is made to ensure that the kernel is killed
550 dies. If not set, an effort is made to ensure that the kernel is killed
548 when this process dies. Note that in this case it is still good practice
551 when this process dies. Note that in this case it is still good practice
549 to kill kernels manually before exiting.
552 to kill kernels manually before exiting.
550
553
551 pylab : bool or string, optional (default False)
554 pylab : bool or string, optional (default False)
552 If not False, the kernel will be launched with pylab enabled. If a
555 If not False, the kernel will be launched with pylab enabled. If a
553 string is passed, matplotlib will use the specified backend. Otherwise,
556 string is passed, matplotlib will use the specified backend. Otherwise,
554 matplotlib's default backend will be used.
557 matplotlib's default backend will be used.
555
558
556 colors : None or string, optional (default None)
559 colors : None or string, optional (default None)
557 If not None, specify the color scheme. One of (NoColor, LightBG, Linux)
560 If not None, specify the color scheme. One of (NoColor, LightBG, Linux)
558
561
559 Returns
562 Returns
560 -------
563 -------
561 A tuple of form:
564 A tuple of form:
562 (kernel_process, xrep_port, pub_port, req_port)
565 (kernel_process, xrep_port, pub_port, req_port)
563 where kernel_process is a Popen object and the ports are integers.
566 where kernel_process is a Popen object and the ports are integers.
564 """
567 """
565 extra_arguments = []
568 extra_arguments = []
566 if pylab:
569 if pylab:
567 extra_arguments.append('--pylab')
570 extra_arguments.append('--pylab')
568 if isinstance(pylab, basestring):
571 if isinstance(pylab, basestring):
569 extra_arguments.append(pylab)
572 extra_arguments.append(pylab)
570 if ip is not None:
573 if ip is not None:
571 extra_arguments.append('--ip')
574 extra_arguments.append('--ip')
572 if isinstance(ip, basestring):
575 if isinstance(ip, basestring):
573 extra_arguments.append(ip)
576 extra_arguments.append(ip)
574 if colors is not None:
577 if colors is not None:
575 extra_arguments.append('--colors')
578 extra_arguments.append('--colors')
576 extra_arguments.append(colors)
579 extra_arguments.append(colors)
577 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
580 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
578 xrep_port, pub_port, req_port, hb_port,
581 xrep_port, pub_port, req_port, hb_port,
579 independent, extra_arguments)
582 independent, extra_arguments)
580
583
581
584
582 def main():
585 def main():
583 """ The IPython kernel main entry point.
586 """ The IPython kernel main entry point.
584 """
587 """
585 parser = make_argument_parser()
588 parser = make_argument_parser()
586 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
589 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
587 const='auto', help = \
590 const='auto', help = \
588 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
591 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
589 given, the GUI backend is matplotlib's, otherwise use one of: \
592 given, the GUI backend is matplotlib's, otherwise use one of: \
590 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
593 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
591 parser.add_argument('--colors',
594 parser.add_argument('--colors',
592 type=str, dest='colors',
595 type=str, dest='colors',
593 help="Set the color scheme (NoColor, Linux, and LightBG).",
596 help="Set the color scheme (NoColor, Linux, and LightBG).",
594 metavar='ZMQInteractiveShell.colors')
597 metavar='ZMQInteractiveShell.colors')
595 namespace = parser.parse_args()
598 namespace = parser.parse_args()
596
599
597 kernel_class = Kernel
600 kernel_class = Kernel
598
601
599 kernel_classes = {
602 kernel_classes = {
600 'qt' : QtKernel,
603 'qt' : QtKernel,
601 'qt4': QtKernel,
604 'qt4': QtKernel,
602 'inline': Kernel,
605 'inline': Kernel,
603 'wx' : WxKernel,
606 'wx' : WxKernel,
604 'tk' : TkKernel,
607 'tk' : TkKernel,
605 'gtk': GTKKernel,
608 'gtk': GTKKernel,
606 }
609 }
607 if namespace.pylab:
610 if namespace.pylab:
608 if namespace.pylab == 'auto':
611 if namespace.pylab == 'auto':
609 gui, backend = pylabtools.find_gui_and_backend()
612 gui, backend = pylabtools.find_gui_and_backend()
610 else:
613 else:
611 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
614 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
612 kernel_class = kernel_classes.get(gui)
615 kernel_class = kernel_classes.get(gui)
613 if kernel_class is None:
616 if kernel_class is None:
614 raise ValueError('GUI is not supported: %r' % gui)
617 raise ValueError('GUI is not supported: %r' % gui)
615 pylabtools.activate_matplotlib(backend)
618 pylabtools.activate_matplotlib(backend)
616 if namespace.colors:
619 if namespace.colors:
617 ZMQInteractiveShell.colors=namespace.colors
620 ZMQInteractiveShell.colors=namespace.colors
618
621
619 kernel = make_kernel(namespace, kernel_class, OutStream)
622 kernel = make_kernel(namespace, kernel_class, OutStream)
620
623
621 if namespace.pylab:
624 if namespace.pylab:
622 pylabtools.import_pylab(kernel.shell.user_ns, backend,
625 pylabtools.import_pylab(kernel.shell.user_ns, backend,
623 shell=kernel.shell)
626 shell=kernel.shell)
624
627
625 start_kernel(namespace, kernel)
628 start_kernel(namespace, kernel)
626
629
627
630
628 if __name__ == '__main__':
631 if __name__ == '__main__':
629 main()
632 main()
@@ -1,119 +1,123 b''
1 """Produce SVG versions of active plots for display by the rich Qt frontend.
1 """Produce SVG versions of active plots for display by the rich Qt frontend.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Imports
4 # Imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 from __future__ import print_function
6 from __future__ import print_function
7
7
8 # Standard library imports
8 # Standard library imports
9 from cStringIO import StringIO
9 from cStringIO import StringIO
10
10
11 # System library imports.
11 # System library imports.
12 import matplotlib
12 import matplotlib
13 from matplotlib.backends.backend_svg import new_figure_manager
13 from matplotlib.backends.backend_svg import new_figure_manager
14 from matplotlib._pylab_helpers import Gcf
14 from matplotlib._pylab_helpers import Gcf
15
15
16 # Local imports.
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 # Functions
20 # Functions
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 def show(close=True):
23 def show(close=True):
24 """Show all figures as SVG payloads sent to the IPython clients.
24 """Show all figures as SVG payloads sent to the IPython clients.
25
25
26 Parameters
26 Parameters
27 ----------
27 ----------
28 close : bool, optional
28 close : bool, optional
29 If true, a ``plt.close('all')`` call is automatically issued after
29 If true, a ``plt.close('all')`` call is automatically issued after
30 sending all the SVG figures.
30 sending all the SVG figures.
31 """
31 """
32 for figure_manager in Gcf.get_all_fig_managers():
32 for figure_manager in Gcf.get_all_fig_managers():
33 send_svg_canvas(figure_manager.canvas)
33 send_svg_canvas(figure_manager.canvas)
34 if close:
34 if close:
35 matplotlib.pyplot.close('all')
35 matplotlib.pyplot.close('all')
36
36
37 # This flag will be reset by draw_if_interactive when called
37 # This flag will be reset by draw_if_interactive when called
38 show._draw_called = False
38 show._draw_called = False
39
39
40
40
41 def figsize(sizex, sizey):
41 def figsize(sizex, sizey):
42 """Set the default figure size to be [sizex, sizey].
42 """Set the default figure size to be [sizex, sizey].
43
43
44 This is just an easy to remember, convenience wrapper that sets::
44 This is just an easy to remember, convenience wrapper that sets::
45
45
46 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
46 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
47 """
47 """
48 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
48 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
49
49
50
50
51 def pastefig(*figs):
51 def pastefig(*figs):
52 """Paste one or more figures into the console workspace.
52 """Paste one or more figures into the console workspace.
53
53
54 If no arguments are given, all available figures are pasted. If the
54 If no arguments are given, all available figures are pasted. If the
55 argument list contains references to invalid figures, a warning is printed
55 argument list contains references to invalid figures, a warning is printed
56 but the function continues pasting further figures.
56 but the function continues pasting further figures.
57
57
58 Parameters
58 Parameters
59 ----------
59 ----------
60 figs : tuple
60 figs : tuple
61 A tuple that can contain any mixture of integers and figure objects.
61 A tuple that can contain any mixture of integers and figure objects.
62 """
62 """
63 if not figs:
63 if not figs:
64 show(close=False)
64 show(close=False)
65 else:
65 else:
66 fig_managers = Gcf.get_all_fig_managers()
66 fig_managers = Gcf.get_all_fig_managers()
67 fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers]
67 fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers]
68 + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] )
68 + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] )
69
69
70 for fig in figs:
70 for fig in figs:
71 canvas = fig_index.get(fig)
71 canvas = fig_index.get(fig)
72 if canvas is None:
72 if canvas is None:
73 print('Warning: figure %s not available.' % fig)
73 print('Warning: figure %s not available.' % fig)
74 else:
74 else:
75 send_svg_canvas(canvas)
75 send_svg_canvas(canvas)
76
76
77
77
78 def send_svg_canvas(canvas):
78 def send_svg_canvas(canvas):
79 """Draw the current canvas and send it as an SVG payload.
79 """Draw the current canvas and send it as an SVG payload.
80 """
80 """
81 # Set the background to white instead so it looks good on black. We store
81 # Set the background to white instead so it looks good on black. We store
82 # the current values to restore them at the end.
82 # the current values to restore them at the end.
83 fc = canvas.figure.get_facecolor()
83 fc = canvas.figure.get_facecolor()
84 ec = canvas.figure.get_edgecolor()
84 ec = canvas.figure.get_edgecolor()
85 canvas.figure.set_facecolor('white')
85 canvas.figure.set_facecolor('white')
86 canvas.figure.set_edgecolor('white')
86 canvas.figure.set_edgecolor('white')
87 try:
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 finally:
93 finally:
90 canvas.figure.set_facecolor(fc)
94 canvas.figure.set_facecolor(fc)
91 canvas.figure.set_edgecolor(ec)
95 canvas.figure.set_edgecolor(ec)
92
96
93
97
94 def svg_from_canvas(canvas):
98 def svg_from_canvas(canvas):
95 """ Return a string containing the SVG representation of a FigureCanvasSvg.
99 """ Return a string containing the SVG representation of a FigureCanvasSvg.
96 """
100 """
97 string_io = StringIO()
101 string_io = StringIO()
98 canvas.print_figure(string_io, format='svg')
102 canvas.print_figure(string_io, format='svg')
99 return string_io.getvalue()
103 return string_io.getvalue()
100
104
101
105
102 def draw_if_interactive():
106 def draw_if_interactive():
103 """
107 """
104 Is called after every pylab drawing command
108 Is called after every pylab drawing command
105 """
109 """
106 # We simply flag we were called and otherwise do nothing. At the end of
110 # We simply flag we were called and otherwise do nothing. At the end of
107 # the code execution, a separate call to show_close() will act upon this.
111 # the code execution, a separate call to show_close() will act upon this.
108 show._draw_called = True
112 show._draw_called = True
109
113
110
114
111 def flush_svg():
115 def flush_svg():
112 """Call show, close all open figures, sending all SVG images.
116 """Call show, close all open figures, sending all SVG images.
113
117
114 This is meant to be called automatically and will call show() if, during
118 This is meant to be called automatically and will call show() if, during
115 prior code execution, there had been any calls to draw_if_interactive.
119 prior code execution, there had been any calls to draw_if_interactive.
116 """
120 """
117 if show._draw_called:
121 if show._draw_called:
118 show(close=True)
122 show(close=True)
119 show._draw_called = False
123 show._draw_called = False
@@ -1,580 +1,605 b''
1 """A ZMQ-based subclass of InteractiveShell.
1 """A ZMQ-based subclass of InteractiveShell.
2
2
3 This code is meant to ease the refactoring of the base InteractiveShell into
3 This code is meant to ease the refactoring of the base InteractiveShell into
4 something with a cleaner architecture for 2-process use, without actually
4 something with a cleaner architecture for 2-process use, without actually
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 we subclass and override what we want to fix. Once this is working well, we
6 we subclass and override what we want to fix. Once this is working well, we
7 can go back to the base class and refactor the code for a cleaner inheritance
7 can go back to the base class and refactor the code for a cleaner inheritance
8 implementation that doesn't rely on so much monkeypatching.
8 implementation that doesn't rely on so much monkeypatching.
9
9
10 But this lets us maintain a fully working IPython as we develop the new
10 But this lets us maintain a fully working IPython as we develop the new
11 machinery. This should thus be thought of as scaffolding.
11 machinery. This should thus be thought of as scaffolding.
12 """
12 """
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Stdlib
18 # Stdlib
19 import inspect
19 import inspect
20 import os
20 import os
21 import re
21 import re
22
22
23 # Our own
23 # Our own
24 from IPython.core.interactiveshell import (
24 from IPython.core.interactiveshell import (
25 InteractiveShell, InteractiveShellABC
25 InteractiveShell, InteractiveShellABC
26 )
26 )
27 from IPython.core import page
27 from IPython.core import page
28 from IPython.core.displayhook import DisplayHook
28 from IPython.core.displayhook import DisplayHook
29 from IPython.core.displaypub import DisplayPublisher
29 from IPython.core.macro import Macro
30 from IPython.core.macro import Macro
30 from IPython.core.payloadpage import install_payload_page
31 from IPython.core.payloadpage import install_payload_page
31 from IPython.utils import io
32 from IPython.utils import io
32 from IPython.utils.path import get_py_filename
33 from IPython.utils.path import get_py_filename
33 from IPython.utils.text import StringTypes
34 from IPython.utils.text import StringTypes
34 from IPython.utils.traitlets import Instance, Type, Dict
35 from IPython.utils.traitlets import Instance, Type, Dict
35 from IPython.utils.warn import warn
36 from IPython.utils.warn import warn
36 from IPython.zmq.session import extract_header
37 from IPython.zmq.session import extract_header
37 from session import Session
38 from session import Session
38
39
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40 # Globals and side-effects
41 # Globals and side-effects
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42
43
43 # Install the payload version of page.
44 # Install the payload version of page.
44 install_payload_page()
45 install_payload_page()
45
46
46 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
47 # Functions and classes
48 # Functions and classes
48 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
49
50
50 class ZMQDisplayHook(DisplayHook):
51 class ZMQDisplayHook(DisplayHook):
51
52
52 session = Instance(Session)
53 session = Instance(Session)
53 pub_socket = Instance('zmq.Socket')
54 pub_socket = Instance('zmq.Socket')
54 parent_header = Dict({})
55 parent_header = Dict({})
55
56
56 def set_parent(self, parent):
57 def set_parent(self, parent):
57 """Set the parent for outbound messages."""
58 """Set the parent for outbound messages."""
58 self.parent_header = extract_header(parent)
59 self.parent_header = extract_header(parent)
59
60
60 def start_displayhook(self):
61 def start_displayhook(self):
61 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
62 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
62
63
63 def write_output_prompt(self):
64 def write_output_prompt(self):
64 """Write the output prompt."""
65 """Write the output prompt."""
65 if self.do_full_cache:
66 if self.do_full_cache:
66 self.msg['content']['execution_count'] = self.prompt_count
67 self.msg['content']['execution_count'] = self.prompt_count
67
68
68 def write_result_repr(self, result_repr, extra_formats):
69 def write_result_repr(self, result_repr, extra_formats):
69 self.msg['content']['data'] = result_repr
70 self.msg['content']['data'] = result_repr
70 self.msg['content']['extra_formats'] = extra_formats
71 self.msg['content']['extra_formats'] = extra_formats
71
72
72 def finish_displayhook(self):
73 def finish_displayhook(self):
73 """Finish up all displayhook activities."""
74 """Finish up all displayhook activities."""
74 self.session.send(self.pub_socket, self.msg)
75 self.session.send(self.pub_socket, self.msg)
75 self.msg = None
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 class ZMQInteractiveShell(InteractiveShell):
101 class ZMQInteractiveShell(InteractiveShell):
79 """A subclass of InteractiveShell for ZMQ."""
102 """A subclass of InteractiveShell for ZMQ."""
80
103
81 displayhook_class = Type(ZMQDisplayHook)
104 displayhook_class = Type(ZMQDisplayHook)
105 display_pub_class = Type(ZMQDisplayPublisher)
106
82 keepkernel_on_exit = None
107 keepkernel_on_exit = None
83
108
84 def init_environment(self):
109 def init_environment(self):
85 """Configure the user's environment.
110 """Configure the user's environment.
86
111
87 """
112 """
88 env = os.environ
113 env = os.environ
89 # These two ensure 'ls' produces nice coloring on BSD-derived systems
114 # These two ensure 'ls' produces nice coloring on BSD-derived systems
90 env['TERM'] = 'xterm-color'
115 env['TERM'] = 'xterm-color'
91 env['CLICOLOR'] = '1'
116 env['CLICOLOR'] = '1'
92 # Since normal pagers don't work at all (over pexpect we don't have
117 # Since normal pagers don't work at all (over pexpect we don't have
93 # single-key control of the subprocess), try to disable paging in
118 # single-key control of the subprocess), try to disable paging in
94 # subprocesses as much as possible.
119 # subprocesses as much as possible.
95 env['PAGER'] = 'cat'
120 env['PAGER'] = 'cat'
96 env['GIT_PAGER'] = 'cat'
121 env['GIT_PAGER'] = 'cat'
97
122
98 def auto_rewrite_input(self, cmd):
123 def auto_rewrite_input(self, cmd):
99 """Called to show the auto-rewritten input for autocall and friends.
124 """Called to show the auto-rewritten input for autocall and friends.
100
125
101 FIXME: this payload is currently not correctly processed by the
126 FIXME: this payload is currently not correctly processed by the
102 frontend.
127 frontend.
103 """
128 """
104 new = self.displayhook.prompt1.auto_rewrite() + cmd
129 new = self.displayhook.prompt1.auto_rewrite() + cmd
105 payload = dict(
130 payload = dict(
106 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
131 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
107 transformed_input=new,
132 transformed_input=new,
108 )
133 )
109 self.payload_manager.write_payload(payload)
134 self.payload_manager.write_payload(payload)
110
135
111 def ask_exit(self):
136 def ask_exit(self):
112 """Engage the exit actions."""
137 """Engage the exit actions."""
113 payload = dict(
138 payload = dict(
114 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
139 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
115 exit=True,
140 exit=True,
116 keepkernel=self.keepkernel_on_exit,
141 keepkernel=self.keepkernel_on_exit,
117 )
142 )
118 self.payload_manager.write_payload(payload)
143 self.payload_manager.write_payload(payload)
119
144
120 def _showtraceback(self, etype, evalue, stb):
145 def _showtraceback(self, etype, evalue, stb):
121
146
122 exc_content = {
147 exc_content = {
123 u'traceback' : stb,
148 u'traceback' : stb,
124 u'ename' : unicode(etype.__name__),
149 u'ename' : unicode(etype.__name__),
125 u'evalue' : unicode(evalue)
150 u'evalue' : unicode(evalue)
126 }
151 }
127
152
128 dh = self.displayhook
153 dh = self.displayhook
129 # Send exception info over pub socket for other clients than the caller
154 # Send exception info over pub socket for other clients than the caller
130 # to pick up
155 # to pick up
131 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header)
156 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header)
132
157
133 # FIXME - Hack: store exception info in shell object. Right now, the
158 # FIXME - Hack: store exception info in shell object. Right now, the
134 # caller is reading this info after the fact, we need to fix this logic
159 # caller is reading this info after the fact, we need to fix this logic
135 # to remove this hack. Even uglier, we need to store the error status
160 # to remove this hack. Even uglier, we need to store the error status
136 # here, because in the main loop, the logic that sets it is being
161 # here, because in the main loop, the logic that sets it is being
137 # skipped because runlines swallows the exceptions.
162 # skipped because runlines swallows the exceptions.
138 exc_content[u'status'] = u'error'
163 exc_content[u'status'] = u'error'
139 self._reply_content = exc_content
164 self._reply_content = exc_content
140 # /FIXME
165 # /FIXME
141
166
142 return exc_content
167 return exc_content
143
168
144 #------------------------------------------------------------------------
169 #------------------------------------------------------------------------
145 # Magic overrides
170 # Magic overrides
146 #------------------------------------------------------------------------
171 #------------------------------------------------------------------------
147 # Once the base class stops inheriting from magic, this code needs to be
172 # Once the base class stops inheriting from magic, this code needs to be
148 # moved into a separate machinery as well. For now, at least isolate here
173 # moved into a separate machinery as well. For now, at least isolate here
149 # the magics which this class needs to implement differently from the base
174 # the magics which this class needs to implement differently from the base
150 # class, or that are unique to it.
175 # class, or that are unique to it.
151
176
152 def magic_doctest_mode(self,parameter_s=''):
177 def magic_doctest_mode(self,parameter_s=''):
153 """Toggle doctest mode on and off.
178 """Toggle doctest mode on and off.
154
179
155 This mode is intended to make IPython behave as much as possible like a
180 This mode is intended to make IPython behave as much as possible like a
156 plain Python shell, from the perspective of how its prompts, exceptions
181 plain Python shell, from the perspective of how its prompts, exceptions
157 and output look. This makes it easy to copy and paste parts of a
182 and output look. This makes it easy to copy and paste parts of a
158 session into doctests. It does so by:
183 session into doctests. It does so by:
159
184
160 - Changing the prompts to the classic ``>>>`` ones.
185 - Changing the prompts to the classic ``>>>`` ones.
161 - Changing the exception reporting mode to 'Plain'.
186 - Changing the exception reporting mode to 'Plain'.
162 - Disabling pretty-printing of output.
187 - Disabling pretty-printing of output.
163
188
164 Note that IPython also supports the pasting of code snippets that have
189 Note that IPython also supports the pasting of code snippets that have
165 leading '>>>' and '...' prompts in them. This means that you can paste
190 leading '>>>' and '...' prompts in them. This means that you can paste
166 doctests from files or docstrings (even if they have leading
191 doctests from files or docstrings (even if they have leading
167 whitespace), and the code will execute correctly. You can then use
192 whitespace), and the code will execute correctly. You can then use
168 '%history -t' to see the translated history; this will give you the
193 '%history -t' to see the translated history; this will give you the
169 input after removal of all the leading prompts and whitespace, which
194 input after removal of all the leading prompts and whitespace, which
170 can be pasted back into an editor.
195 can be pasted back into an editor.
171
196
172 With these features, you can switch into this mode easily whenever you
197 With these features, you can switch into this mode easily whenever you
173 need to do testing and changes to doctests, without having to leave
198 need to do testing and changes to doctests, without having to leave
174 your existing IPython session.
199 your existing IPython session.
175 """
200 """
176
201
177 from IPython.utils.ipstruct import Struct
202 from IPython.utils.ipstruct import Struct
178
203
179 # Shorthands
204 # Shorthands
180 shell = self.shell
205 shell = self.shell
181 # dstore is a data store kept in the instance metadata bag to track any
206 # dstore is a data store kept in the instance metadata bag to track any
182 # changes we make, so we can undo them later.
207 # changes we make, so we can undo them later.
183 dstore = shell.meta.setdefault('doctest_mode', Struct())
208 dstore = shell.meta.setdefault('doctest_mode', Struct())
184 save_dstore = dstore.setdefault
209 save_dstore = dstore.setdefault
185
210
186 # save a few values we'll need to recover later
211 # save a few values we'll need to recover later
187 mode = save_dstore('mode', False)
212 mode = save_dstore('mode', False)
188 save_dstore('rc_pprint', shell.pprint)
213 save_dstore('rc_pprint', shell.pprint)
189 save_dstore('xmode', shell.InteractiveTB.mode)
214 save_dstore('xmode', shell.InteractiveTB.mode)
190
215
191 if mode == False:
216 if mode == False:
192 # turn on
217 # turn on
193 shell.pprint = False
218 shell.pprint = False
194 shell.magic_xmode('Plain')
219 shell.magic_xmode('Plain')
195 else:
220 else:
196 # turn off
221 # turn off
197 shell.pprint = dstore.rc_pprint
222 shell.pprint = dstore.rc_pprint
198 shell.magic_xmode(dstore.xmode)
223 shell.magic_xmode(dstore.xmode)
199
224
200 # Store new mode and inform on console
225 # Store new mode and inform on console
201 dstore.mode = bool(1-int(mode))
226 dstore.mode = bool(1-int(mode))
202 mode_label = ['OFF','ON'][dstore.mode]
227 mode_label = ['OFF','ON'][dstore.mode]
203 print('Doctest mode is:', mode_label)
228 print('Doctest mode is:', mode_label)
204
229
205 # Send the payload back so that clients can modify their prompt display
230 # Send the payload back so that clients can modify their prompt display
206 payload = dict(
231 payload = dict(
207 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
232 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
208 mode=dstore.mode)
233 mode=dstore.mode)
209 self.payload_manager.write_payload(payload)
234 self.payload_manager.write_payload(payload)
210
235
211 def magic_edit(self,parameter_s='',last_call=['','']):
236 def magic_edit(self,parameter_s='',last_call=['','']):
212 """Bring up an editor and execute the resulting code.
237 """Bring up an editor and execute the resulting code.
213
238
214 Usage:
239 Usage:
215 %edit [options] [args]
240 %edit [options] [args]
216
241
217 %edit runs IPython's editor hook. The default version of this hook is
242 %edit runs IPython's editor hook. The default version of this hook is
218 set to call the __IPYTHON__.rc.editor command. This is read from your
243 set to call the __IPYTHON__.rc.editor command. This is read from your
219 environment variable $EDITOR. If this isn't found, it will default to
244 environment variable $EDITOR. If this isn't found, it will default to
220 vi under Linux/Unix and to notepad under Windows. See the end of this
245 vi under Linux/Unix and to notepad under Windows. See the end of this
221 docstring for how to change the editor hook.
246 docstring for how to change the editor hook.
222
247
223 You can also set the value of this editor via the command line option
248 You can also set the value of this editor via the command line option
224 '-editor' or in your ipythonrc file. This is useful if you wish to use
249 '-editor' or in your ipythonrc file. This is useful if you wish to use
225 specifically for IPython an editor different from your typical default
250 specifically for IPython an editor different from your typical default
226 (and for Windows users who typically don't set environment variables).
251 (and for Windows users who typically don't set environment variables).
227
252
228 This command allows you to conveniently edit multi-line code right in
253 This command allows you to conveniently edit multi-line code right in
229 your IPython session.
254 your IPython session.
230
255
231 If called without arguments, %edit opens up an empty editor with a
256 If called without arguments, %edit opens up an empty editor with a
232 temporary file and will execute the contents of this file when you
257 temporary file and will execute the contents of this file when you
233 close it (don't forget to save it!).
258 close it (don't forget to save it!).
234
259
235
260
236 Options:
261 Options:
237
262
238 -n <number>: open the editor at a specified line number. By default,
263 -n <number>: open the editor at a specified line number. By default,
239 the IPython editor hook uses the unix syntax 'editor +N filename', but
264 the IPython editor hook uses the unix syntax 'editor +N filename', but
240 you can configure this by providing your own modified hook if your
265 you can configure this by providing your own modified hook if your
241 favorite editor supports line-number specifications with a different
266 favorite editor supports line-number specifications with a different
242 syntax.
267 syntax.
243
268
244 -p: this will call the editor with the same data as the previous time
269 -p: this will call the editor with the same data as the previous time
245 it was used, regardless of how long ago (in your current session) it
270 it was used, regardless of how long ago (in your current session) it
246 was.
271 was.
247
272
248 -r: use 'raw' input. This option only applies to input taken from the
273 -r: use 'raw' input. This option only applies to input taken from the
249 user's history. By default, the 'processed' history is used, so that
274 user's history. By default, the 'processed' history is used, so that
250 magics are loaded in their transformed version to valid Python. If
275 magics are loaded in their transformed version to valid Python. If
251 this option is given, the raw input as typed as the command line is
276 this option is given, the raw input as typed as the command line is
252 used instead. When you exit the editor, it will be executed by
277 used instead. When you exit the editor, it will be executed by
253 IPython's own processor.
278 IPython's own processor.
254
279
255 -x: do not execute the edited code immediately upon exit. This is
280 -x: do not execute the edited code immediately upon exit. This is
256 mainly useful if you are editing programs which need to be called with
281 mainly useful if you are editing programs which need to be called with
257 command line arguments, which you can then do using %run.
282 command line arguments, which you can then do using %run.
258
283
259
284
260 Arguments:
285 Arguments:
261
286
262 If arguments are given, the following possibilites exist:
287 If arguments are given, the following possibilites exist:
263
288
264 - The arguments are numbers or pairs of colon-separated numbers (like
289 - The arguments are numbers or pairs of colon-separated numbers (like
265 1 4:8 9). These are interpreted as lines of previous input to be
290 1 4:8 9). These are interpreted as lines of previous input to be
266 loaded into the editor. The syntax is the same of the %macro command.
291 loaded into the editor. The syntax is the same of the %macro command.
267
292
268 - If the argument doesn't start with a number, it is evaluated as a
293 - If the argument doesn't start with a number, it is evaluated as a
269 variable and its contents loaded into the editor. You can thus edit
294 variable and its contents loaded into the editor. You can thus edit
270 any string which contains python code (including the result of
295 any string which contains python code (including the result of
271 previous edits).
296 previous edits).
272
297
273 - If the argument is the name of an object (other than a string),
298 - If the argument is the name of an object (other than a string),
274 IPython will try to locate the file where it was defined and open the
299 IPython will try to locate the file where it was defined and open the
275 editor at the point where it is defined. You can use `%edit function`
300 editor at the point where it is defined. You can use `%edit function`
276 to load an editor exactly at the point where 'function' is defined,
301 to load an editor exactly at the point where 'function' is defined,
277 edit it and have the file be executed automatically.
302 edit it and have the file be executed automatically.
278
303
279 If the object is a macro (see %macro for details), this opens up your
304 If the object is a macro (see %macro for details), this opens up your
280 specified editor with a temporary file containing the macro's data.
305 specified editor with a temporary file containing the macro's data.
281 Upon exit, the macro is reloaded with the contents of the file.
306 Upon exit, the macro is reloaded with the contents of the file.
282
307
283 Note: opening at an exact line is only supported under Unix, and some
308 Note: opening at an exact line is only supported under Unix, and some
284 editors (like kedit and gedit up to Gnome 2.8) do not understand the
309 editors (like kedit and gedit up to Gnome 2.8) do not understand the
285 '+NUMBER' parameter necessary for this feature. Good editors like
310 '+NUMBER' parameter necessary for this feature. Good editors like
286 (X)Emacs, vi, jed, pico and joe all do.
311 (X)Emacs, vi, jed, pico and joe all do.
287
312
288 - If the argument is not found as a variable, IPython will look for a
313 - If the argument is not found as a variable, IPython will look for a
289 file with that name (adding .py if necessary) and load it into the
314 file with that name (adding .py if necessary) and load it into the
290 editor. It will execute its contents with execfile() when you exit,
315 editor. It will execute its contents with execfile() when you exit,
291 loading any code in the file into your interactive namespace.
316 loading any code in the file into your interactive namespace.
292
317
293 After executing your code, %edit will return as output the code you
318 After executing your code, %edit will return as output the code you
294 typed in the editor (except when it was an existing file). This way
319 typed in the editor (except when it was an existing file). This way
295 you can reload the code in further invocations of %edit as a variable,
320 you can reload the code in further invocations of %edit as a variable,
296 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
321 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
297 the output.
322 the output.
298
323
299 Note that %edit is also available through the alias %ed.
324 Note that %edit is also available through the alias %ed.
300
325
301 This is an example of creating a simple function inside the editor and
326 This is an example of creating a simple function inside the editor and
302 then modifying it. First, start up the editor:
327 then modifying it. First, start up the editor:
303
328
304 In [1]: ed
329 In [1]: ed
305 Editing... done. Executing edited code...
330 Editing... done. Executing edited code...
306 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
331 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
307
332
308 We can then call the function foo():
333 We can then call the function foo():
309
334
310 In [2]: foo()
335 In [2]: foo()
311 foo() was defined in an editing session
336 foo() was defined in an editing session
312
337
313 Now we edit foo. IPython automatically loads the editor with the
338 Now we edit foo. IPython automatically loads the editor with the
314 (temporary) file where foo() was previously defined:
339 (temporary) file where foo() was previously defined:
315
340
316 In [3]: ed foo
341 In [3]: ed foo
317 Editing... done. Executing edited code...
342 Editing... done. Executing edited code...
318
343
319 And if we call foo() again we get the modified version:
344 And if we call foo() again we get the modified version:
320
345
321 In [4]: foo()
346 In [4]: foo()
322 foo() has now been changed!
347 foo() has now been changed!
323
348
324 Here is an example of how to edit a code snippet successive
349 Here is an example of how to edit a code snippet successive
325 times. First we call the editor:
350 times. First we call the editor:
326
351
327 In [5]: ed
352 In [5]: ed
328 Editing... done. Executing edited code...
353 Editing... done. Executing edited code...
329 hello
354 hello
330 Out[5]: "print 'hello'n"
355 Out[5]: "print 'hello'n"
331
356
332 Now we call it again with the previous output (stored in _):
357 Now we call it again with the previous output (stored in _):
333
358
334 In [6]: ed _
359 In [6]: ed _
335 Editing... done. Executing edited code...
360 Editing... done. Executing edited code...
336 hello world
361 hello world
337 Out[6]: "print 'hello world'n"
362 Out[6]: "print 'hello world'n"
338
363
339 Now we call it with the output #8 (stored in _8, also as Out[8]):
364 Now we call it with the output #8 (stored in _8, also as Out[8]):
340
365
341 In [7]: ed _8
366 In [7]: ed _8
342 Editing... done. Executing edited code...
367 Editing... done. Executing edited code...
343 hello again
368 hello again
344 Out[7]: "print 'hello again'n"
369 Out[7]: "print 'hello again'n"
345
370
346
371
347 Changing the default editor hook:
372 Changing the default editor hook:
348
373
349 If you wish to write your own editor hook, you can put it in a
374 If you wish to write your own editor hook, you can put it in a
350 configuration file which you load at startup time. The default hook
375 configuration file which you load at startup time. The default hook
351 is defined in the IPython.core.hooks module, and you can use that as a
376 is defined in the IPython.core.hooks module, and you can use that as a
352 starting example for further modifications. That file also has
377 starting example for further modifications. That file also has
353 general instructions on how to set a new hook for use once you've
378 general instructions on how to set a new hook for use once you've
354 defined it."""
379 defined it."""
355
380
356 # FIXME: This function has become a convoluted mess. It needs a
381 # FIXME: This function has become a convoluted mess. It needs a
357 # ground-up rewrite with clean, simple logic.
382 # ground-up rewrite with clean, simple logic.
358
383
359 def make_filename(arg):
384 def make_filename(arg):
360 "Make a filename from the given args"
385 "Make a filename from the given args"
361 try:
386 try:
362 filename = get_py_filename(arg)
387 filename = get_py_filename(arg)
363 except IOError:
388 except IOError:
364 if args.endswith('.py'):
389 if args.endswith('.py'):
365 filename = arg
390 filename = arg
366 else:
391 else:
367 filename = None
392 filename = None
368 return filename
393 return filename
369
394
370 # custom exceptions
395 # custom exceptions
371 class DataIsObject(Exception): pass
396 class DataIsObject(Exception): pass
372
397
373 opts,args = self.parse_options(parameter_s,'prn:')
398 opts,args = self.parse_options(parameter_s,'prn:')
374 # Set a few locals from the options for convenience:
399 # Set a few locals from the options for convenience:
375 opts_p = opts.has_key('p')
400 opts_p = opts.has_key('p')
376 opts_r = opts.has_key('r')
401 opts_r = opts.has_key('r')
377
402
378 # Default line number value
403 # Default line number value
379 lineno = opts.get('n',None)
404 lineno = opts.get('n',None)
380 if lineno is not None:
405 if lineno is not None:
381 try:
406 try:
382 lineno = int(lineno)
407 lineno = int(lineno)
383 except:
408 except:
384 warn("The -n argument must be an integer.")
409 warn("The -n argument must be an integer.")
385 return
410 return
386
411
387 if opts_p:
412 if opts_p:
388 args = '_%s' % last_call[0]
413 args = '_%s' % last_call[0]
389 if not self.shell.user_ns.has_key(args):
414 if not self.shell.user_ns.has_key(args):
390 args = last_call[1]
415 args = last_call[1]
391
416
392 # use last_call to remember the state of the previous call, but don't
417 # use last_call to remember the state of the previous call, but don't
393 # let it be clobbered by successive '-p' calls.
418 # let it be clobbered by successive '-p' calls.
394 try:
419 try:
395 last_call[0] = self.shell.displayhook.prompt_count
420 last_call[0] = self.shell.displayhook.prompt_count
396 if not opts_p:
421 if not opts_p:
397 last_call[1] = parameter_s
422 last_call[1] = parameter_s
398 except:
423 except:
399 pass
424 pass
400
425
401 # by default this is done with temp files, except when the given
426 # by default this is done with temp files, except when the given
402 # arg is a filename
427 # arg is a filename
403 use_temp = 1
428 use_temp = 1
404
429
405 if re.match(r'\d',args):
430 if re.match(r'\d',args):
406 # Mode where user specifies ranges of lines, like in %macro.
431 # Mode where user specifies ranges of lines, like in %macro.
407 # This means that you can't edit files whose names begin with
432 # This means that you can't edit files whose names begin with
408 # numbers this way. Tough.
433 # numbers this way. Tough.
409 ranges = args.split()
434 ranges = args.split()
410 data = ''.join(self.extract_input_slices(ranges,opts_r))
435 data = ''.join(self.extract_input_slices(ranges,opts_r))
411 elif args.endswith('.py'):
436 elif args.endswith('.py'):
412 filename = make_filename(args)
437 filename = make_filename(args)
413 data = ''
438 data = ''
414 use_temp = 0
439 use_temp = 0
415 elif args:
440 elif args:
416 try:
441 try:
417 # Load the parameter given as a variable. If not a string,
442 # Load the parameter given as a variable. If not a string,
418 # process it as an object instead (below)
443 # process it as an object instead (below)
419
444
420 #print '*** args',args,'type',type(args) # dbg
445 #print '*** args',args,'type',type(args) # dbg
421 data = eval(args,self.shell.user_ns)
446 data = eval(args,self.shell.user_ns)
422 if not type(data) in StringTypes:
447 if not type(data) in StringTypes:
423 raise DataIsObject
448 raise DataIsObject
424
449
425 except (NameError,SyntaxError):
450 except (NameError,SyntaxError):
426 # given argument is not a variable, try as a filename
451 # given argument is not a variable, try as a filename
427 filename = make_filename(args)
452 filename = make_filename(args)
428 if filename is None:
453 if filename is None:
429 warn("Argument given (%s) can't be found as a variable "
454 warn("Argument given (%s) can't be found as a variable "
430 "or as a filename." % args)
455 "or as a filename." % args)
431 return
456 return
432
457
433 data = ''
458 data = ''
434 use_temp = 0
459 use_temp = 0
435 except DataIsObject:
460 except DataIsObject:
436
461
437 # macros have a special edit function
462 # macros have a special edit function
438 if isinstance(data,Macro):
463 if isinstance(data,Macro):
439 self._edit_macro(args,data)
464 self._edit_macro(args,data)
440 return
465 return
441
466
442 # For objects, try to edit the file where they are defined
467 # For objects, try to edit the file where they are defined
443 try:
468 try:
444 filename = inspect.getabsfile(data)
469 filename = inspect.getabsfile(data)
445 if 'fakemodule' in filename.lower() and inspect.isclass(data):
470 if 'fakemodule' in filename.lower() and inspect.isclass(data):
446 # class created by %edit? Try to find source
471 # class created by %edit? Try to find source
447 # by looking for method definitions instead, the
472 # by looking for method definitions instead, the
448 # __module__ in those classes is FakeModule.
473 # __module__ in those classes is FakeModule.
449 attrs = [getattr(data, aname) for aname in dir(data)]
474 attrs = [getattr(data, aname) for aname in dir(data)]
450 for attr in attrs:
475 for attr in attrs:
451 if not inspect.ismethod(attr):
476 if not inspect.ismethod(attr):
452 continue
477 continue
453 filename = inspect.getabsfile(attr)
478 filename = inspect.getabsfile(attr)
454 if filename and 'fakemodule' not in filename.lower():
479 if filename and 'fakemodule' not in filename.lower():
455 # change the attribute to be the edit target instead
480 # change the attribute to be the edit target instead
456 data = attr
481 data = attr
457 break
482 break
458
483
459 datafile = 1
484 datafile = 1
460 except TypeError:
485 except TypeError:
461 filename = make_filename(args)
486 filename = make_filename(args)
462 datafile = 1
487 datafile = 1
463 warn('Could not find file where `%s` is defined.\n'
488 warn('Could not find file where `%s` is defined.\n'
464 'Opening a file named `%s`' % (args,filename))
489 'Opening a file named `%s`' % (args,filename))
465 # Now, make sure we can actually read the source (if it was in
490 # Now, make sure we can actually read the source (if it was in
466 # a temp file it's gone by now).
491 # a temp file it's gone by now).
467 if datafile:
492 if datafile:
468 try:
493 try:
469 if lineno is None:
494 if lineno is None:
470 lineno = inspect.getsourcelines(data)[1]
495 lineno = inspect.getsourcelines(data)[1]
471 except IOError:
496 except IOError:
472 filename = make_filename(args)
497 filename = make_filename(args)
473 if filename is None:
498 if filename is None:
474 warn('The file `%s` where `%s` was defined cannot '
499 warn('The file `%s` where `%s` was defined cannot '
475 'be read.' % (filename,data))
500 'be read.' % (filename,data))
476 return
501 return
477 use_temp = 0
502 use_temp = 0
478 else:
503 else:
479 data = ''
504 data = ''
480
505
481 if use_temp:
506 if use_temp:
482 filename = self.shell.mktempfile(data)
507 filename = self.shell.mktempfile(data)
483 print('IPython will make a temporary file named:', filename)
508 print('IPython will make a temporary file named:', filename)
484
509
485 # Make sure we send to the client an absolute path, in case the working
510 # Make sure we send to the client an absolute path, in case the working
486 # directory of client and kernel don't match
511 # directory of client and kernel don't match
487 filename = os.path.abspath(filename)
512 filename = os.path.abspath(filename)
488
513
489 payload = {
514 payload = {
490 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
515 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
491 'filename' : filename,
516 'filename' : filename,
492 'line_number' : lineno
517 'line_number' : lineno
493 }
518 }
494 self.payload_manager.write_payload(payload)
519 self.payload_manager.write_payload(payload)
495
520
496 def magic_gui(self, *args, **kwargs):
521 def magic_gui(self, *args, **kwargs):
497 raise NotImplementedError(
522 raise NotImplementedError(
498 'GUI support must be enabled in command line options.')
523 'GUI support must be enabled in command line options.')
499
524
500 def magic_pylab(self, *args, **kwargs):
525 def magic_pylab(self, *args, **kwargs):
501 raise NotImplementedError(
526 raise NotImplementedError(
502 'pylab support must be enabled in command line options.')
527 'pylab support must be enabled in command line options.')
503
528
504 # A few magics that are adapted to the specifics of using pexpect and a
529 # A few magics that are adapted to the specifics of using pexpect and a
505 # remote terminal
530 # remote terminal
506
531
507 def magic_clear(self, arg_s):
532 def magic_clear(self, arg_s):
508 """Clear the terminal."""
533 """Clear the terminal."""
509 if os.name == 'posix':
534 if os.name == 'posix':
510 self.shell.system("clear")
535 self.shell.system("clear")
511 else:
536 else:
512 self.shell.system("cls")
537 self.shell.system("cls")
513
538
514 if os.name == 'nt':
539 if os.name == 'nt':
515 # This is the usual name in windows
540 # This is the usual name in windows
516 magic_cls = magic_clear
541 magic_cls = magic_clear
517
542
518 # Terminal pagers won't work over pexpect, but we do have our own pager
543 # Terminal pagers won't work over pexpect, but we do have our own pager
519
544
520 def magic_less(self, arg_s):
545 def magic_less(self, arg_s):
521 """Show a file through the pager.
546 """Show a file through the pager.
522
547
523 Files ending in .py are syntax-highlighted."""
548 Files ending in .py are syntax-highlighted."""
524 cont = open(arg_s).read()
549 cont = open(arg_s).read()
525 if arg_s.endswith('.py'):
550 if arg_s.endswith('.py'):
526 cont = self.shell.pycolorize(cont)
551 cont = self.shell.pycolorize(cont)
527 page.page(cont)
552 page.page(cont)
528
553
529 magic_more = magic_less
554 magic_more = magic_less
530
555
531 # Man calls a pager, so we also need to redefine it
556 # Man calls a pager, so we also need to redefine it
532 if os.name == 'posix':
557 if os.name == 'posix':
533 def magic_man(self, arg_s):
558 def magic_man(self, arg_s):
534 """Find the man page for the given command and display in pager."""
559 """Find the man page for the given command and display in pager."""
535 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
560 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
536 split=False))
561 split=False))
537
562
538 # FIXME: this is specific to the GUI, so we should let the gui app load
563 # FIXME: this is specific to the GUI, so we should let the gui app load
539 # magics at startup that are only for the gui. Once the gui app has proper
564 # magics at startup that are only for the gui. Once the gui app has proper
540 # profile and configuration management, we can have it initialize a kernel
565 # profile and configuration management, we can have it initialize a kernel
541 # with a special config file that provides these.
566 # with a special config file that provides these.
542 def magic_guiref(self, arg_s):
567 def magic_guiref(self, arg_s):
543 """Show a basic reference about the GUI console."""
568 """Show a basic reference about the GUI console."""
544 from IPython.core.usage import gui_reference
569 from IPython.core.usage import gui_reference
545 page.page(gui_reference, auto_html=True)
570 page.page(gui_reference, auto_html=True)
546
571
547 def magic_loadpy(self, arg_s):
572 def magic_loadpy(self, arg_s):
548 """Load a .py python script into the GUI console.
573 """Load a .py python script into the GUI console.
549
574
550 This magic command can either take a local filename or a url::
575 This magic command can either take a local filename or a url::
551
576
552 %loadpy myscript.py
577 %loadpy myscript.py
553 %loadpy http://www.example.com/myscript.py
578 %loadpy http://www.example.com/myscript.py
554 """
579 """
555 if not arg_s.endswith('.py'):
580 if not arg_s.endswith('.py'):
556 raise ValueError('%%load only works with .py files: %s' % arg_s)
581 raise ValueError('%%load only works with .py files: %s' % arg_s)
557 if arg_s.startswith('http'):
582 if arg_s.startswith('http'):
558 import urllib2
583 import urllib2
559 response = urllib2.urlopen(arg_s)
584 response = urllib2.urlopen(arg_s)
560 content = response.read()
585 content = response.read()
561 else:
586 else:
562 content = open(arg_s).read()
587 content = open(arg_s).read()
563 payload = dict(
588 payload = dict(
564 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy',
589 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy',
565 text=content
590 text=content
566 )
591 )
567 self.payload_manager.write_payload(payload)
592 self.payload_manager.write_payload(payload)
568
593
569 def magic_Exit(self, parameter_s=''):
594 def magic_Exit(self, parameter_s=''):
570 """Exit IPython. If the -k option is provided, the kernel will be left
595 """Exit IPython. If the -k option is provided, the kernel will be left
571 running. Otherwise, it will shutdown without prompting.
596 running. Otherwise, it will shutdown without prompting.
572 """
597 """
573 opts,args = self.parse_options(parameter_s,'k')
598 opts,args = self.parse_options(parameter_s,'k')
574 self.shell.keepkernel_on_exit = opts.has_key('k')
599 self.shell.keepkernel_on_exit = opts.has_key('k')
575 self.shell.ask_exit()
600 self.shell.ask_exit()
576
601
577 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
602 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
578 magic_exit = magic_quit = magic_Quit = magic_Exit
603 magic_exit = magic_quit = magic_Quit = magic_Exit
579
604
580 InteractiveShellABC.register(ZMQInteractiveShell)
605 InteractiveShellABC.register(ZMQInteractiveShell)
@@ -1,934 +1,936 b''
1 .. _messaging:
1 .. _messaging:
2
2
3 ======================
3 ======================
4 Messaging in IPython
4 Messaging in IPython
5 ======================
5 ======================
6
6
7
7
8 Introduction
8 Introduction
9 ============
9 ============
10
10
11 This document explains the basic communications design and messaging
11 This document explains the basic communications design and messaging
12 specification for how the various IPython objects interact over a network
12 specification for how the various IPython objects interact over a network
13 transport. The current implementation uses the ZeroMQ_ library for messaging
13 transport. The current implementation uses the ZeroMQ_ library for messaging
14 within and between hosts.
14 within and between hosts.
15
15
16 .. Note::
16 .. Note::
17
17
18 This document should be considered the authoritative description of the
18 This document should be considered the authoritative description of the
19 IPython messaging protocol, and all developers are strongly encouraged to
19 IPython messaging protocol, and all developers are strongly encouraged to
20 keep it updated as the implementation evolves, so that we have a single
20 keep it updated as the implementation evolves, so that we have a single
21 common reference for all protocol details.
21 common reference for all protocol details.
22
22
23 The basic design is explained in the following diagram:
23 The basic design is explained in the following diagram:
24
24
25 .. image:: frontend-kernel.png
25 .. image:: frontend-kernel.png
26 :width: 450px
26 :width: 450px
27 :alt: IPython kernel/frontend messaging architecture.
27 :alt: IPython kernel/frontend messaging architecture.
28 :align: center
28 :align: center
29 :target: ../_images/frontend-kernel.png
29 :target: ../_images/frontend-kernel.png
30
30
31 A single kernel can be simultaneously connected to one or more frontends. The
31 A single kernel can be simultaneously connected to one or more frontends. The
32 kernel has three sockets that serve the following functions:
32 kernel has three sockets that serve the following functions:
33
33
34 1. REQ: this socket is connected to a *single* frontend at a time, and it allows
34 1. REQ: this socket is connected to a *single* frontend at a time, and it allows
35 the kernel to request input from a frontend when :func:`raw_input` is called.
35 the kernel to request input from a frontend when :func:`raw_input` is called.
36 The frontend holding the matching REP socket acts as a 'virtual keyboard'
36 The frontend holding the matching REP socket acts as a 'virtual keyboard'
37 for the kernel while this communication is happening (illustrated in the
37 for the kernel while this communication is happening (illustrated in the
38 figure by the black outline around the central keyboard). In practice,
38 figure by the black outline around the central keyboard). In practice,
39 frontends may display such kernel requests using a special input widget or
39 frontends may display such kernel requests using a special input widget or
40 otherwise indicating that the user is to type input for the kernel instead
40 otherwise indicating that the user is to type input for the kernel instead
41 of normal commands in the frontend.
41 of normal commands in the frontend.
42
42
43 2. XREP: this single sockets allows multiple incoming connections from
43 2. XREP: this single sockets allows multiple incoming connections from
44 frontends, and this is the socket where requests for code execution, object
44 frontends, and this is the socket where requests for code execution, object
45 information, prompts, etc. are made to the kernel by any frontend. The
45 information, prompts, etc. are made to the kernel by any frontend. The
46 communication on this socket is a sequence of request/reply actions from
46 communication on this socket is a sequence of request/reply actions from
47 each frontend and the kernel.
47 each frontend and the kernel.
48
48
49 3. PUB: this socket is the 'broadcast channel' where the kernel publishes all
49 3. PUB: this socket is the 'broadcast channel' where the kernel publishes all
50 side effects (stdout, stderr, etc.) as well as the requests coming from any
50 side effects (stdout, stderr, etc.) as well as the requests coming from any
51 client over the XREP socket and its own requests on the REP socket. There
51 client over the XREP socket and its own requests on the REP socket. There
52 are a number of actions in Python which generate side effects: :func:`print`
52 are a number of actions in Python which generate side effects: :func:`print`
53 writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in
53 writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in
54 a multi-client scenario, we want all frontends to be able to know what each
54 a multi-client scenario, we want all frontends to be able to know what each
55 other has sent to the kernel (this can be useful in collaborative scenarios,
55 other has sent to the kernel (this can be useful in collaborative scenarios,
56 for example). This socket allows both side effects and the information
56 for example). This socket allows both side effects and the information
57 about communications taking place with one client over the XREQ/XREP channel
57 about communications taking place with one client over the XREQ/XREP channel
58 to be made available to all clients in a uniform manner.
58 to be made available to all clients in a uniform manner.
59
59
60 All messages are tagged with enough information (details below) for clients
60 All messages are tagged with enough information (details below) for clients
61 to know which messages come from their own interaction with the kernel and
61 to know which messages come from their own interaction with the kernel and
62 which ones are from other clients, so they can display each type
62 which ones are from other clients, so they can display each type
63 appropriately.
63 appropriately.
64
64
65 The actual format of the messages allowed on each of these channels is
65 The actual format of the messages allowed on each of these channels is
66 specified below. Messages are dicts of dicts with string keys and values that
66 specified below. Messages are dicts of dicts with string keys and values that
67 are reasonably representable in JSON. Our current implementation uses JSON
67 are reasonably representable in JSON. Our current implementation uses JSON
68 explicitly as its message format, but this shouldn't be considered a permanent
68 explicitly as its message format, but this shouldn't be considered a permanent
69 feature. As we've discovered that JSON has non-trivial performance issues due
69 feature. As we've discovered that JSON has non-trivial performance issues due
70 to excessive copying, we may in the future move to a pure pickle-based raw
70 to excessive copying, we may in the future move to a pure pickle-based raw
71 message format. However, it should be possible to easily convert from the raw
71 message format. However, it should be possible to easily convert from the raw
72 objects to JSON, since we may have non-python clients (e.g. a web frontend).
72 objects to JSON, since we may have non-python clients (e.g. a web frontend).
73 As long as it's easy to make a JSON version of the objects that is a faithful
73 As long as it's easy to make a JSON version of the objects that is a faithful
74 representation of all the data, we can communicate with such clients.
74 representation of all the data, we can communicate with such clients.
75
75
76 .. Note::
76 .. Note::
77
77
78 Not all of these have yet been fully fleshed out, but the key ones are, see
78 Not all of these have yet been fully fleshed out, but the key ones are, see
79 kernel and frontend files for actual implementation details.
79 kernel and frontend files for actual implementation details.
80
80
81
81
82 Python functional API
82 Python functional API
83 =====================
83 =====================
84
84
85 As messages are dicts, they map naturally to a ``func(**kw)`` call form. We
85 As messages are dicts, they map naturally to a ``func(**kw)`` call form. We
86 should develop, at a few key points, functional forms of all the requests that
86 should develop, at a few key points, functional forms of all the requests that
87 take arguments in this manner and automatically construct the necessary dict
87 take arguments in this manner and automatically construct the necessary dict
88 for sending.
88 for sending.
89
89
90
90
91 General Message Format
91 General Message Format
92 ======================
92 ======================
93
93
94 All messages send or received by any IPython process should have the following
94 All messages send or received by any IPython process should have the following
95 generic structure::
95 generic structure::
96
96
97 {
97 {
98 # The message header contains a pair of unique identifiers for the
98 # The message header contains a pair of unique identifiers for the
99 # originating session and the actual message id, in addition to the
99 # originating session and the actual message id, in addition to the
100 # username for the process that generated the message. This is useful in
100 # username for the process that generated the message. This is useful in
101 # collaborative settings where multiple users may be interacting with the
101 # collaborative settings where multiple users may be interacting with the
102 # same kernel simultaneously, so that frontends can label the various
102 # same kernel simultaneously, so that frontends can label the various
103 # messages in a meaningful way.
103 # messages in a meaningful way.
104 'header' : { 'msg_id' : uuid,
104 'header' : { 'msg_id' : uuid,
105 'username' : str,
105 'username' : str,
106 'session' : uuid
106 'session' : uuid
107 },
107 },
108
108
109 # In a chain of messages, the header from the parent is copied so that
109 # In a chain of messages, the header from the parent is copied so that
110 # clients can track where messages come from.
110 # clients can track where messages come from.
111 'parent_header' : dict,
111 'parent_header' : dict,
112
112
113 # All recognized message type strings are listed below.
113 # All recognized message type strings are listed below.
114 'msg_type' : str,
114 'msg_type' : str,
115
115
116 # The actual content of the message must be a dict, whose structure
116 # The actual content of the message must be a dict, whose structure
117 # depends on the message type.x
117 # depends on the message type.x
118 'content' : dict,
118 'content' : dict,
119 }
119 }
120
120
121 For each message type, the actual content will differ and all existing message
121 For each message type, the actual content will differ and all existing message
122 types are specified in what follows of this document.
122 types are specified in what follows of this document.
123
123
124
124
125 Messages on the XREP/XREQ socket
125 Messages on the XREP/XREQ socket
126 ================================
126 ================================
127
127
128 .. _execute:
128 .. _execute:
129
129
130 Execute
130 Execute
131 -------
131 -------
132
132
133 This message type is used by frontends to ask the kernel to execute code on
133 This message type is used by frontends to ask the kernel to execute code on
134 behalf of the user, in a namespace reserved to the user's variables (and thus
134 behalf of the user, in a namespace reserved to the user's variables (and thus
135 separate from the kernel's own internal code and variables).
135 separate from the kernel's own internal code and variables).
136
136
137 Message type: ``execute_request``::
137 Message type: ``execute_request``::
138
138
139 content = {
139 content = {
140 # Source code to be executed by the kernel, one or more lines.
140 # Source code to be executed by the kernel, one or more lines.
141 'code' : str,
141 'code' : str,
142
142
143 # A boolean flag which, if True, signals the kernel to execute this
143 # A boolean flag which, if True, signals the kernel to execute this
144 # code as quietly as possible. This means that the kernel will compile
144 # code as quietly as possible. This means that the kernel will compile
145 # the code witIPython/core/tests/h 'exec' instead of 'single' (so
145 # the code witIPython/core/tests/h 'exec' instead of 'single' (so
146 # sys.displayhook will not fire), and will *not*:
146 # sys.displayhook will not fire), and will *not*:
147 # - broadcast exceptions on the PUB socket
147 # - broadcast exceptions on the PUB socket
148 # - do any logging
148 # - do any logging
149 # - populate any history
149 # - populate any history
150 #
150 #
151 # The default is False.
151 # The default is False.
152 'silent' : bool,
152 'silent' : bool,
153
153
154 # A list of variable names from the user's namespace to be retrieved. What
154 # A list of variable names from the user's namespace to be retrieved. What
155 # returns is a JSON string of the variable's repr(), not a python object.
155 # returns is a JSON string of the variable's repr(), not a python object.
156 'user_variables' : list,
156 'user_variables' : list,
157
157
158 # Similarly, a dict mapping names to expressions to be evaluated in the
158 # Similarly, a dict mapping names to expressions to be evaluated in the
159 # user's dict.
159 # user's dict.
160 'user_expressions' : dict,
160 'user_expressions' : dict,
161 }
161 }
162
162
163 The ``code`` field contains a single string (possibly multiline). The kernel
163 The ``code`` field contains a single string (possibly multiline). The kernel
164 is responsible for splitting this into one or more independent execution blocks
164 is responsible for splitting this into one or more independent execution blocks
165 and deciding whether to compile these in 'single' or 'exec' mode (see below for
165 and deciding whether to compile these in 'single' or 'exec' mode (see below for
166 detailed execution semantics).
166 detailed execution semantics).
167
167
168 The ``user_`` fields deserve a detailed explanation. In the past, IPython had
168 The ``user_`` fields deserve a detailed explanation. In the past, IPython had
169 the notion of a prompt string that allowed arbitrary code to be evaluated, and
169 the notion of a prompt string that allowed arbitrary code to be evaluated, and
170 this was put to good use by many in creating prompts that displayed system
170 this was put to good use by many in creating prompts that displayed system
171 status, path information, and even more esoteric uses like remote instrument
171 status, path information, and even more esoteric uses like remote instrument
172 status aqcuired over the network. But now that IPython has a clean separation
172 status aqcuired over the network. But now that IPython has a clean separation
173 between the kernel and the clients, the kernel has no prompt knowledge; prompts
173 between the kernel and the clients, the kernel has no prompt knowledge; prompts
174 are a frontend-side feature, and it should be even possible for different
174 are a frontend-side feature, and it should be even possible for different
175 frontends to display different prompts while interacting with the same kernel.
175 frontends to display different prompts while interacting with the same kernel.
176
176
177 The kernel now provides the ability to retrieve data from the user's namespace
177 The kernel now provides the ability to retrieve data from the user's namespace
178 after the execution of the main ``code``, thanks to two fields in the
178 after the execution of the main ``code``, thanks to two fields in the
179 ``execute_request`` message:
179 ``execute_request`` message:
180
180
181 - ``user_variables``: If only variables from the user's namespace are needed, a
181 - ``user_variables``: If only variables from the user's namespace are needed, a
182 list of variable names can be passed and a dict with these names as keys and
182 list of variable names can be passed and a dict with these names as keys and
183 their :func:`repr()` as values will be returned.
183 their :func:`repr()` as values will be returned.
184
184
185 - ``user_expressions``: For more complex expressions that require function
185 - ``user_expressions``: For more complex expressions that require function
186 evaluations, a dict can be provided with string keys and arbitrary python
186 evaluations, a dict can be provided with string keys and arbitrary python
187 expressions as values. The return message will contain also a dict with the
187 expressions as values. The return message will contain also a dict with the
188 same keys and the :func:`repr()` of the evaluated expressions as value.
188 same keys and the :func:`repr()` of the evaluated expressions as value.
189
189
190 With this information, frontends can display any status information they wish
190 With this information, frontends can display any status information they wish
191 in the form that best suits each frontend (a status line, a popup, inline for a
191 in the form that best suits each frontend (a status line, a popup, inline for a
192 terminal, etc).
192 terminal, etc).
193
193
194 .. Note::
194 .. Note::
195
195
196 In order to obtain the current execution counter for the purposes of
196 In order to obtain the current execution counter for the purposes of
197 displaying input prompts, frontends simply make an execution request with an
197 displaying input prompts, frontends simply make an execution request with an
198 empty code string and ``silent=True``.
198 empty code string and ``silent=True``.
199
199
200 Execution semantics
200 Execution semantics
201 ~~~~~~~~~~~~~~~~~~~
201 ~~~~~~~~~~~~~~~~~~~
202
202
203 When the silent flag is false, the execution of use code consists of the
203 When the silent flag is false, the execution of use code consists of the
204 following phases (in silent mode, only the ``code`` field is executed):
204 following phases (in silent mode, only the ``code`` field is executed):
205
205
206 1. Run the ``pre_runcode_hook``.
206 1. Run the ``pre_runcode_hook``.
207
207
208 2. Execute the ``code`` field, see below for details.
208 2. Execute the ``code`` field, see below for details.
209
209
210 3. If #2 succeeds, compute ``user_variables`` and ``user_expressions`` are
210 3. If #2 succeeds, compute ``user_variables`` and ``user_expressions`` are
211 computed. This ensures that any error in the latter don't harm the main
211 computed. This ensures that any error in the latter don't harm the main
212 code execution.
212 code execution.
213
213
214 4. Call any method registered with :meth:`register_post_execute`.
214 4. Call any method registered with :meth:`register_post_execute`.
215
215
216 .. warning::
216 .. warning::
217
217
218 The API for running code before/after the main code block is likely to
218 The API for running code before/after the main code block is likely to
219 change soon. Both the ``pre_runcode_hook`` and the
219 change soon. Both the ``pre_runcode_hook`` and the
220 :meth:`register_post_execute` are susceptible to modification, as we find a
220 :meth:`register_post_execute` are susceptible to modification, as we find a
221 consistent model for both.
221 consistent model for both.
222
222
223 To understand how the ``code`` field is executed, one must know that Python
223 To understand how the ``code`` field is executed, one must know that Python
224 code can be compiled in one of three modes (controlled by the ``mode`` argument
224 code can be compiled in one of three modes (controlled by the ``mode`` argument
225 to the :func:`compile` builtin):
225 to the :func:`compile` builtin):
226
226
227 *single*
227 *single*
228 Valid for a single interactive statement (though the source can contain
228 Valid for a single interactive statement (though the source can contain
229 multiple lines, such as a for loop). When compiled in this mode, the
229 multiple lines, such as a for loop). When compiled in this mode, the
230 generated bytecode contains special instructions that trigger the calling of
230 generated bytecode contains special instructions that trigger the calling of
231 :func:`sys.displayhook` for any expression in the block that returns a value.
231 :func:`sys.displayhook` for any expression in the block that returns a value.
232 This means that a single statement can actually produce multiple calls to
232 This means that a single statement can actually produce multiple calls to
233 :func:`sys.displayhook`, if for example it contains a loop where each
233 :func:`sys.displayhook`, if for example it contains a loop where each
234 iteration computes an unassigned expression would generate 10 calls::
234 iteration computes an unassigned expression would generate 10 calls::
235
235
236 for i in range(10):
236 for i in range(10):
237 i**2
237 i**2
238
238
239 *exec*
239 *exec*
240 An arbitrary amount of source code, this is how modules are compiled.
240 An arbitrary amount of source code, this is how modules are compiled.
241 :func:`sys.displayhook` is *never* implicitly called.
241 :func:`sys.displayhook` is *never* implicitly called.
242
242
243 *eval*
243 *eval*
244 A single expression that returns a value. :func:`sys.displayhook` is *never*
244 A single expression that returns a value. :func:`sys.displayhook` is *never*
245 implicitly called.
245 implicitly called.
246
246
247
247
248 The ``code`` field is split into individual blocks each of which is valid for
248 The ``code`` field is split into individual blocks each of which is valid for
249 execution in 'single' mode, and then:
249 execution in 'single' mode, and then:
250
250
251 - If there is only a single block: it is executed in 'single' mode.
251 - If there is only a single block: it is executed in 'single' mode.
252
252
253 - If there is more than one block:
253 - If there is more than one block:
254
254
255 * if the last one is a single line long, run all but the last in 'exec' mode
255 * if the last one is a single line long, run all but the last in 'exec' mode
256 and the very last one in 'single' mode. This makes it easy to type simple
256 and the very last one in 'single' mode. This makes it easy to type simple
257 expressions at the end to see computed values.
257 expressions at the end to see computed values.
258
258
259 * if the last one is no more than two lines long, run all but the last in
259 * if the last one is no more than two lines long, run all but the last in
260 'exec' mode and the very last one in 'single' mode. This makes it easy to
260 'exec' mode and the very last one in 'single' mode. This makes it easy to
261 type simple expressions at the end to see computed values. - otherwise
261 type simple expressions at the end to see computed values. - otherwise
262 (last one is also multiline), run all in 'exec' mode
262 (last one is also multiline), run all in 'exec' mode
263
263
264 * otherwise (last one is also multiline), run all in 'exec' mode as a single
264 * otherwise (last one is also multiline), run all in 'exec' mode as a single
265 unit.
265 unit.
266
266
267 Any error in retrieving the ``user_variables`` or evaluating the
267 Any error in retrieving the ``user_variables`` or evaluating the
268 ``user_expressions`` will result in a simple error message in the return fields
268 ``user_expressions`` will result in a simple error message in the return fields
269 of the form::
269 of the form::
270
270
271 [ERROR] ExceptionType: Exception message
271 [ERROR] ExceptionType: Exception message
272
272
273 The user can simply send the same variable name or expression for evaluation to
273 The user can simply send the same variable name or expression for evaluation to
274 see a regular traceback.
274 see a regular traceback.
275
275
276 Errors in any registered post_execute functions are also reported similarly,
276 Errors in any registered post_execute functions are also reported similarly,
277 and the failing function is removed from the post_execution set so that it does
277 and the failing function is removed from the post_execution set so that it does
278 not continue triggering failures.
278 not continue triggering failures.
279
279
280 Upon completion of the execution request, the kernel *always* sends a reply,
280 Upon completion of the execution request, the kernel *always* sends a reply,
281 with a status code indicating what happened and additional data depending on
281 with a status code indicating what happened and additional data depending on
282 the outcome. See :ref:`below <execution_results>` for the possible return
282 the outcome. See :ref:`below <execution_results>` for the possible return
283 codes and associated data.
283 codes and associated data.
284
284
285
285
286 Execution counter (old prompt number)
286 Execution counter (old prompt number)
287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
288
288
289 The kernel has a single, monotonically increasing counter of all execution
289 The kernel has a single, monotonically increasing counter of all execution
290 requests that are made with ``silent=False``. This counter is used to populate
290 requests that are made with ``silent=False``. This counter is used to populate
291 the ``In[n]``, ``Out[n]`` and ``_n`` variables, so clients will likely want to
291 the ``In[n]``, ``Out[n]`` and ``_n`` variables, so clients will likely want to
292 display it in some form to the user, which will typically (but not necessarily)
292 display it in some form to the user, which will typically (but not necessarily)
293 be done in the prompts. The value of this counter will be returned as the
293 be done in the prompts. The value of this counter will be returned as the
294 ``execution_count`` field of all ``execute_reply`` messages.
294 ``execution_count`` field of all ``execute_reply`` messages.
295
295
296 .. _execution_results:
296 .. _execution_results:
297
297
298 Execution results
298 Execution results
299 ~~~~~~~~~~~~~~~~~
299 ~~~~~~~~~~~~~~~~~
300
300
301 Message type: ``execute_reply``::
301 Message type: ``execute_reply``::
302
302
303 content = {
303 content = {
304 # One of: 'ok' OR 'error' OR 'abort'
304 # One of: 'ok' OR 'error' OR 'abort'
305 'status' : str,
305 'status' : str,
306
306
307 # The global kernel counter that increases by one with each non-silent
307 # The global kernel counter that increases by one with each non-silent
308 # executed request. This will typically be used by clients to display
308 # executed request. This will typically be used by clients to display
309 # prompt numbers to the user. If the request was a silent one, this will
309 # prompt numbers to the user. If the request was a silent one, this will
310 # be the current value of the counter in the kernel.
310 # be the current value of the counter in the kernel.
311 'execution_count' : int,
311 'execution_count' : int,
312 }
312 }
313
313
314 When status is 'ok', the following extra fields are present::
314 When status is 'ok', the following extra fields are present::
315
315
316 {
316 {
317 # The execution payload is a dict with string keys that may have been
317 # The execution payload is a dict with string keys that may have been
318 # produced by the code being executed. It is retrieved by the kernel at
318 # produced by the code being executed. It is retrieved by the kernel at
319 # the end of the execution and sent back to the front end, which can take
319 # the end of the execution and sent back to the front end, which can take
320 # action on it as needed. See main text for further details.
320 # action on it as needed. See main text for further details.
321 'payload' : dict,
321 'payload' : dict,
322
322
323 # Results for the user_variables and user_expressions.
323 # Results for the user_variables and user_expressions.
324 'user_variables' : dict,
324 'user_variables' : dict,
325 'user_expressions' : dict,
325 'user_expressions' : dict,
326
326
327 # The kernel will often transform the input provided to it. If the
327 # The kernel will often transform the input provided to it. If the
328 # '---->' transform had been applied, this is filled, otherwise it's the
328 # '---->' transform had been applied, this is filled, otherwise it's the
329 # empty string. So transformations like magics don't appear here, only
329 # empty string. So transformations like magics don't appear here, only
330 # autocall ones.
330 # autocall ones.
331 'transformed_code' : str,
331 'transformed_code' : str,
332 }
332 }
333
333
334 .. admonition:: Execution payloads
334 .. admonition:: Execution payloads
335
335
336 The notion of an 'execution payload' is different from a return value of a
336 The notion of an 'execution payload' is different from a return value of a
337 given set of code, which normally is just displayed on the pyout stream
337 given set of code, which normally is just displayed on the pyout stream
338 through the PUB socket. The idea of a payload is to allow special types of
338 through the PUB socket. The idea of a payload is to allow special types of
339 code, typically magics, to populate a data container in the IPython kernel
339 code, typically magics, to populate a data container in the IPython kernel
340 that will be shipped back to the caller via this channel. The kernel will
340 that will be shipped back to the caller via this channel. The kernel will
341 have an API for this, probably something along the lines of::
341 have an API for this, probably something along the lines of::
342
342
343 ip.exec_payload_add(key, value)
343 ip.exec_payload_add(key, value)
344
344
345 though this API is still in the design stages. The data returned in this
345 though this API is still in the design stages. The data returned in this
346 payload will allow frontends to present special views of what just happened.
346 payload will allow frontends to present special views of what just happened.
347
347
348
348
349 When status is 'error', the following extra fields are present::
349 When status is 'error', the following extra fields are present::
350
350
351 {
351 {
352 'exc_name' : str, # Exception name, as a string
352 'exc_name' : str, # Exception name, as a string
353 'exc_value' : str, # Exception value, as a string
353 'exc_value' : str, # Exception value, as a string
354
354
355 # The traceback will contain a list of frames, represented each as a
355 # The traceback will contain a list of frames, represented each as a
356 # string. For now we'll stick to the existing design of ultraTB, which
356 # string. For now we'll stick to the existing design of ultraTB, which
357 # controls exception level of detail statefully. But eventually we'll
357 # controls exception level of detail statefully. But eventually we'll
358 # want to grow into a model where more information is collected and
358 # want to grow into a model where more information is collected and
359 # packed into the traceback object, with clients deciding how little or
359 # packed into the traceback object, with clients deciding how little or
360 # how much of it to unpack. But for now, let's start with a simple list
360 # how much of it to unpack. But for now, let's start with a simple list
361 # of strings, since that requires only minimal changes to ultratb as
361 # of strings, since that requires only minimal changes to ultratb as
362 # written.
362 # written.
363 'traceback' : list,
363 'traceback' : list,
364 }
364 }
365
365
366
366
367 When status is 'abort', there are for now no additional data fields. This
367 When status is 'abort', there are for now no additional data fields. This
368 happens when the kernel was interrupted by a signal.
368 happens when the kernel was interrupted by a signal.
369
369
370 Kernel attribute access
370 Kernel attribute access
371 -----------------------
371 -----------------------
372
372
373 .. warning::
373 .. warning::
374
374
375 This part of the messaging spec is not actually implemented in the kernel
375 This part of the messaging spec is not actually implemented in the kernel
376 yet.
376 yet.
377
377
378 While this protocol does not specify full RPC access to arbitrary methods of
378 While this protocol does not specify full RPC access to arbitrary methods of
379 the kernel object, the kernel does allow read (and in some cases write) access
379 the kernel object, the kernel does allow read (and in some cases write) access
380 to certain attributes.
380 to certain attributes.
381
381
382 The policy for which attributes can be read is: any attribute of the kernel, or
382 The policy for which attributes can be read is: any attribute of the kernel, or
383 its sub-objects, that belongs to a :class:`Configurable` object and has been
383 its sub-objects, that belongs to a :class:`Configurable` object and has been
384 declared at the class-level with Traits validation, is in principle accessible
384 declared at the class-level with Traits validation, is in principle accessible
385 as long as its name does not begin with a leading underscore. The attribute
385 as long as its name does not begin with a leading underscore. The attribute
386 itself will have metadata indicating whether it allows remote read and/or write
386 itself will have metadata indicating whether it allows remote read and/or write
387 access. The message spec follows for attribute read and write requests.
387 access. The message spec follows for attribute read and write requests.
388
388
389 Message type: ``getattr_request``::
389 Message type: ``getattr_request``::
390
390
391 content = {
391 content = {
392 # The (possibly dotted) name of the attribute
392 # The (possibly dotted) name of the attribute
393 'name' : str,
393 'name' : str,
394 }
394 }
395
395
396 When a ``getattr_request`` fails, there are two possible error types:
396 When a ``getattr_request`` fails, there are two possible error types:
397
397
398 - AttributeError: this type of error was raised when trying to access the
398 - AttributeError: this type of error was raised when trying to access the
399 given name by the kernel itself. This means that the attribute likely
399 given name by the kernel itself. This means that the attribute likely
400 doesn't exist.
400 doesn't exist.
401
401
402 - AccessError: the attribute exists but its value is not readable remotely.
402 - AccessError: the attribute exists but its value is not readable remotely.
403
403
404
404
405 Message type: ``getattr_reply``::
405 Message type: ``getattr_reply``::
406
406
407 content = {
407 content = {
408 # One of ['ok', 'AttributeError', 'AccessError'].
408 # One of ['ok', 'AttributeError', 'AccessError'].
409 'status' : str,
409 'status' : str,
410 # If status is 'ok', a JSON object.
410 # If status is 'ok', a JSON object.
411 'value' : object,
411 'value' : object,
412 }
412 }
413
413
414 Message type: ``setattr_request``::
414 Message type: ``setattr_request``::
415
415
416 content = {
416 content = {
417 # The (possibly dotted) name of the attribute
417 # The (possibly dotted) name of the attribute
418 'name' : str,
418 'name' : str,
419
419
420 # A JSON-encoded object, that will be validated by the Traits
420 # A JSON-encoded object, that will be validated by the Traits
421 # information in the kernel
421 # information in the kernel
422 'value' : object,
422 'value' : object,
423 }
423 }
424
424
425 When a ``setattr_request`` fails, there are also two possible error types with
425 When a ``setattr_request`` fails, there are also two possible error types with
426 similar meanings as those of the ``getattr_request`` case, but for writing.
426 similar meanings as those of the ``getattr_request`` case, but for writing.
427
427
428 Message type: ``setattr_reply``::
428 Message type: ``setattr_reply``::
429
429
430 content = {
430 content = {
431 # One of ['ok', 'AttributeError', 'AccessError'].
431 # One of ['ok', 'AttributeError', 'AccessError'].
432 'status' : str,
432 'status' : str,
433 }
433 }
434
434
435
435
436
436
437 Object information
437 Object information
438 ------------------
438 ------------------
439
439
440 One of IPython's most used capabilities is the introspection of Python objects
440 One of IPython's most used capabilities is the introspection of Python objects
441 in the user's namespace, typically invoked via the ``?`` and ``??`` characters
441 in the user's namespace, typically invoked via the ``?`` and ``??`` characters
442 (which in reality are shorthands for the ``%pinfo`` magic). This is used often
442 (which in reality are shorthands for the ``%pinfo`` magic). This is used often
443 enough that it warrants an explicit message type, especially because frontends
443 enough that it warrants an explicit message type, especially because frontends
444 may want to get object information in response to user keystrokes (like Tab or
444 may want to get object information in response to user keystrokes (like Tab or
445 F1) besides from the user explicitly typing code like ``x??``.
445 F1) besides from the user explicitly typing code like ``x??``.
446
446
447 Message type: ``object_info_request``::
447 Message type: ``object_info_request``::
448
448
449 content = {
449 content = {
450 # The (possibly dotted) name of the object to be searched in all
450 # The (possibly dotted) name of the object to be searched in all
451 # relevant namespaces
451 # relevant namespaces
452 'name' : str,
452 'name' : str,
453
453
454 # The level of detail desired. The default (0) is equivalent to typing
454 # The level of detail desired. The default (0) is equivalent to typing
455 # 'x?' at the prompt, 1 is equivalent to 'x??'.
455 # 'x?' at the prompt, 1 is equivalent to 'x??'.
456 'detail_level' : int,
456 'detail_level' : int,
457 }
457 }
458
458
459 The returned information will be a dictionary with keys very similar to the
459 The returned information will be a dictionary with keys very similar to the
460 field names that IPython prints at the terminal.
460 field names that IPython prints at the terminal.
461
461
462 Message type: ``object_info_reply``::
462 Message type: ``object_info_reply``::
463
463
464 content = {
464 content = {
465 # The name the object was requested under
465 # The name the object was requested under
466 'name' : str,
466 'name' : str,
467
467
468 # Boolean flag indicating whether the named object was found or not. If
468 # Boolean flag indicating whether the named object was found or not. If
469 # it's false, all other fields will be empty.
469 # it's false, all other fields will be empty.
470 'found' : bool,
470 'found' : bool,
471
471
472 # Flags for magics and system aliases
472 # Flags for magics and system aliases
473 'ismagic' : bool,
473 'ismagic' : bool,
474 'isalias' : bool,
474 'isalias' : bool,
475
475
476 # The name of the namespace where the object was found ('builtin',
476 # The name of the namespace where the object was found ('builtin',
477 # 'magics', 'alias', 'interactive', etc.)
477 # 'magics', 'alias', 'interactive', etc.)
478 'namespace' : str,
478 'namespace' : str,
479
479
480 # The type name will be type.__name__ for normal Python objects, but it
480 # The type name will be type.__name__ for normal Python objects, but it
481 # can also be a string like 'Magic function' or 'System alias'
481 # can also be a string like 'Magic function' or 'System alias'
482 'type_name' : str,
482 'type_name' : str,
483
483
484 'string_form' : str,
484 'string_form' : str,
485
485
486 # For objects with a __class__ attribute this will be set
486 # For objects with a __class__ attribute this will be set
487 'base_class' : str,
487 'base_class' : str,
488
488
489 # For objects with a __len__ attribute this will be set
489 # For objects with a __len__ attribute this will be set
490 'length' : int,
490 'length' : int,
491
491
492 # If the object is a function, class or method whose file we can find,
492 # If the object is a function, class or method whose file we can find,
493 # we give its full path
493 # we give its full path
494 'file' : str,
494 'file' : str,
495
495
496 # For pure Python callable objects, we can reconstruct the object
496 # For pure Python callable objects, we can reconstruct the object
497 # definition line which provides its call signature. For convenience this
497 # definition line which provides its call signature. For convenience this
498 # is returned as a single 'definition' field, but below the raw parts that
498 # is returned as a single 'definition' field, but below the raw parts that
499 # compose it are also returned as the argspec field.
499 # compose it are also returned as the argspec field.
500 'definition' : str,
500 'definition' : str,
501
501
502 # The individual parts that together form the definition string. Clients
502 # The individual parts that together form the definition string. Clients
503 # with rich display capabilities may use this to provide a richer and more
503 # with rich display capabilities may use this to provide a richer and more
504 # precise representation of the definition line (e.g. by highlighting
504 # precise representation of the definition line (e.g. by highlighting
505 # arguments based on the user's cursor position). For non-callable
505 # arguments based on the user's cursor position). For non-callable
506 # objects, this field is empty.
506 # objects, this field is empty.
507 'argspec' : { # The names of all the arguments
507 'argspec' : { # The names of all the arguments
508 args : list,
508 args : list,
509 # The name of the varargs (*args), if any
509 # The name of the varargs (*args), if any
510 varargs : str,
510 varargs : str,
511 # The name of the varkw (**kw), if any
511 # The name of the varkw (**kw), if any
512 varkw : str,
512 varkw : str,
513 # The values (as strings) of all default arguments. Note
513 # The values (as strings) of all default arguments. Note
514 # that these must be matched *in reverse* with the 'args'
514 # that these must be matched *in reverse* with the 'args'
515 # list above, since the first positional args have no default
515 # list above, since the first positional args have no default
516 # value at all.
516 # value at all.
517 defaults : list,
517 defaults : list,
518 },
518 },
519
519
520 # For instances, provide the constructor signature (the definition of
520 # For instances, provide the constructor signature (the definition of
521 # the __init__ method):
521 # the __init__ method):
522 'init_definition' : str,
522 'init_definition' : str,
523
523
524 # Docstrings: for any object (function, method, module, package) with a
524 # Docstrings: for any object (function, method, module, package) with a
525 # docstring, we show it. But in addition, we may provide additional
525 # docstring, we show it. But in addition, we may provide additional
526 # docstrings. For example, for instances we will show the constructor
526 # docstrings. For example, for instances we will show the constructor
527 # and class docstrings as well, if available.
527 # and class docstrings as well, if available.
528 'docstring' : str,
528 'docstring' : str,
529
529
530 # For instances, provide the constructor and class docstrings
530 # For instances, provide the constructor and class docstrings
531 'init_docstring' : str,
531 'init_docstring' : str,
532 'class_docstring' : str,
532 'class_docstring' : str,
533
533
534 # If it's a callable object whose call method has a separate docstring and
534 # If it's a callable object whose call method has a separate docstring and
535 # definition line:
535 # definition line:
536 'call_def' : str,
536 'call_def' : str,
537 'call_docstring' : str,
537 'call_docstring' : str,
538
538
539 # If detail_level was 1, we also try to find the source code that
539 # If detail_level was 1, we also try to find the source code that
540 # defines the object, if possible. The string 'None' will indicate
540 # defines the object, if possible. The string 'None' will indicate
541 # that no source was found.
541 # that no source was found.
542 'source' : str,
542 'source' : str,
543 }
543 }
544 '
544 '
545
545
546 Complete
546 Complete
547 --------
547 --------
548
548
549 Message type: ``complete_request``::
549 Message type: ``complete_request``::
550
550
551 content = {
551 content = {
552 # The text to be completed, such as 'a.is'
552 # The text to be completed, such as 'a.is'
553 'text' : str,
553 'text' : str,
554
554
555 # The full line, such as 'print a.is'. This allows completers to
555 # The full line, such as 'print a.is'. This allows completers to
556 # make decisions that may require information about more than just the
556 # make decisions that may require information about more than just the
557 # current word.
557 # current word.
558 'line' : str,
558 'line' : str,
559
559
560 # The entire block of text where the line is. This may be useful in the
560 # The entire block of text where the line is. This may be useful in the
561 # case of multiline completions where more context may be needed. Note: if
561 # case of multiline completions where more context may be needed. Note: if
562 # in practice this field proves unnecessary, remove it to lighten the
562 # in practice this field proves unnecessary, remove it to lighten the
563 # messages.
563 # messages.
564
564
565 'block' : str,
565 'block' : str,
566
566
567 # The position of the cursor where the user hit 'TAB' on the line.
567 # The position of the cursor where the user hit 'TAB' on the line.
568 'cursor_pos' : int,
568 'cursor_pos' : int,
569 }
569 }
570
570
571 Message type: ``complete_reply``::
571 Message type: ``complete_reply``::
572
572
573 content = {
573 content = {
574 # The list of all matches to the completion request, such as
574 # The list of all matches to the completion request, such as
575 # ['a.isalnum', 'a.isalpha'] for the above example.
575 # ['a.isalnum', 'a.isalpha'] for the above example.
576 'matches' : list
576 'matches' : list
577 }
577 }
578
578
579
579
580 History
580 History
581 -------
581 -------
582
582
583 For clients to explicitly request history from a kernel. The kernel has all
583 For clients to explicitly request history from a kernel. The kernel has all
584 the actual execution history stored in a single location, so clients can
584 the actual execution history stored in a single location, so clients can
585 request it from the kernel when needed.
585 request it from the kernel when needed.
586
586
587 Message type: ``history_request``::
587 Message type: ``history_request``::
588
588
589 content = {
589 content = {
590
590
591 # If True, also return output history in the resulting dict.
591 # If True, also return output history in the resulting dict.
592 'output' : bool,
592 'output' : bool,
593
593
594 # If True, return the raw input history, else the transformed input.
594 # If True, return the raw input history, else the transformed input.
595 'raw' : bool,
595 'raw' : bool,
596
596
597 # This parameter can be one of: A number, a pair of numbers, None
597 # This parameter can be one of: A number, a pair of numbers, None
598 # If not given, last 40 are returned.
598 # If not given, last 40 are returned.
599 # - number n: return the last n entries.
599 # - number n: return the last n entries.
600 # - pair n1, n2: return entries in the range(n1, n2).
600 # - pair n1, n2: return entries in the range(n1, n2).
601 # - None: return all history
601 # - None: return all history
602 'index' : n or (n1, n2) or None,
602 'index' : n or (n1, n2) or None,
603 }
603 }
604
604
605 Message type: ``history_reply``::
605 Message type: ``history_reply``::
606
606
607 content = {
607 content = {
608 # A dict with prompt numbers as keys and either (input, output) or input
608 # A dict with prompt numbers as keys and either (input, output) or input
609 # as the value depending on whether output was True or False,
609 # as the value depending on whether output was True or False,
610 # respectively.
610 # respectively.
611 'history' : dict,
611 'history' : dict,
612 }
612 }
613
613
614
614
615 Connect
615 Connect
616 -------
616 -------
617
617
618 When a client connects to the request/reply socket of the kernel, it can issue
618 When a client connects to the request/reply socket of the kernel, it can issue
619 a connect request to get basic information about the kernel, such as the ports
619 a connect request to get basic information about the kernel, such as the ports
620 the other ZeroMQ sockets are listening on. This allows clients to only have
620 the other ZeroMQ sockets are listening on. This allows clients to only have
621 to know about a single port (the XREQ/XREP channel) to connect to a kernel.
621 to know about a single port (the XREQ/XREP channel) to connect to a kernel.
622
622
623 Message type: ``connect_request``::
623 Message type: ``connect_request``::
624
624
625 content = {
625 content = {
626 }
626 }
627
627
628 Message type: ``connect_reply``::
628 Message type: ``connect_reply``::
629
629
630 content = {
630 content = {
631 'xrep_port' : int # The port the XREP socket is listening on.
631 'xrep_port' : int # The port the XREP socket is listening on.
632 'pub_port' : int # The port the PUB socket is listening on.
632 'pub_port' : int # The port the PUB socket is listening on.
633 'req_port' : int # The port the REQ socket is listening on.
633 'req_port' : int # The port the REQ socket is listening on.
634 'hb_port' : int # The port the heartbeat socket is listening on.
634 'hb_port' : int # The port the heartbeat socket is listening on.
635 }
635 }
636
636
637
637
638
638
639 Kernel shutdown
639 Kernel shutdown
640 ---------------
640 ---------------
641
641
642 The clients can request the kernel to shut itself down; this is used in
642 The clients can request the kernel to shut itself down; this is used in
643 multiple cases:
643 multiple cases:
644
644
645 - when the user chooses to close the client application via a menu or window
645 - when the user chooses to close the client application via a menu or window
646 control.
646 control.
647 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
647 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
648 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
648 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
649 IPythonQt client) to force a kernel restart to get a clean kernel without
649 IPythonQt client) to force a kernel restart to get a clean kernel without
650 losing client-side state like history or inlined figures.
650 losing client-side state like history or inlined figures.
651
651
652 The client sends a shutdown request to the kernel, and once it receives the
652 The client sends a shutdown request to the kernel, and once it receives the
653 reply message (which is otherwise empty), it can assume that the kernel has
653 reply message (which is otherwise empty), it can assume that the kernel has
654 completed shutdown safely.
654 completed shutdown safely.
655
655
656 Upon their own shutdown, client applications will typically execute a last
656 Upon their own shutdown, client applications will typically execute a last
657 minute sanity check and forcefully terminate any kernel that is still alive, to
657 minute sanity check and forcefully terminate any kernel that is still alive, to
658 avoid leaving stray processes in the user's machine.
658 avoid leaving stray processes in the user's machine.
659
659
660 For both shutdown request and reply, there is no actual content that needs to
660 For both shutdown request and reply, there is no actual content that needs to
661 be sent, so the content dict is empty.
661 be sent, so the content dict is empty.
662
662
663 Message type: ``shutdown_request``::
663 Message type: ``shutdown_request``::
664
664
665 content = {
665 content = {
666 'restart' : bool # whether the shutdown is final, or precedes a restart
666 'restart' : bool # whether the shutdown is final, or precedes a restart
667 }
667 }
668
668
669 Message type: ``shutdown_reply``::
669 Message type: ``shutdown_reply``::
670
670
671 content = {
671 content = {
672 'restart' : bool # whether the shutdown is final, or precedes a restart
672 'restart' : bool # whether the shutdown is final, or precedes a restart
673 }
673 }
674
674
675 .. Note::
675 .. Note::
676
676
677 When the clients detect a dead kernel thanks to inactivity on the heartbeat
677 When the clients detect a dead kernel thanks to inactivity on the heartbeat
678 socket, they simply send a forceful process termination signal, since a dead
678 socket, they simply send a forceful process termination signal, since a dead
679 process is unlikely to respond in any useful way to messages.
679 process is unlikely to respond in any useful way to messages.
680
680
681
681
682 Messages on the PUB/SUB socket
682 Messages on the PUB/SUB socket
683 ==============================
683 ==============================
684
684
685 Streams (stdout, stderr, etc)
685 Streams (stdout, stderr, etc)
686 ------------------------------
686 ------------------------------
687
687
688 Message type: ``stream``::
688 Message type: ``stream``::
689
689
690 content = {
690 content = {
691 # The name of the stream is one of 'stdin', 'stdout', 'stderr'
691 # The name of the stream is one of 'stdin', 'stdout', 'stderr'
692 'name' : str,
692 'name' : str,
693
693
694 # The data is an arbitrary string to be written to that stream
694 # The data is an arbitrary string to be written to that stream
695 'data' : str,
695 'data' : str,
696 }
696 }
697
697
698 When a kernel receives a raw_input call, it should also broadcast it on the pub
698 When a kernel receives a raw_input call, it should also broadcast it on the pub
699 socket with the names 'stdin' and 'stdin_reply'. This will allow other clients
699 socket with the names 'stdin' and 'stdin_reply'. This will allow other clients
700 to monitor/display kernel interactions and possibly replay them to their user
700 to monitor/display kernel interactions and possibly replay them to their user
701 or otherwise expose them.
701 or otherwise expose them.
702
702
703 Representation Data
703 Display Data
704 -------------------
704 ------------
705
705
706 This type of message is used to bring back representations (text, html, svg,
706 This type of message is used to bring back data that should be diplayed (text,
707 etc.) of Python objects to the frontend. Each message can have multiple
707 html, svg, etc.) in the frontends. This data is published to all frontends.
708 representations of the object; it is up to the frontend to decide which to use
708 Each message can have multiple representations of the data; it is up to the
709 and how. A single message should contain the different representations of a
709 frontend to decide which to use and how. A single message should contain all
710 single Python object. Each representation should be a JSON'able data structure,
710 possible representations of the same information. Each representation should
711 and should be a valid MIME type.
711 be a JSON'able data structure, and should be a valid MIME type.
712
712
713 Some questions remain about this design:
713 Some questions remain about this design:
714
714
715 * Do we use this message type for pyout/displayhook?
715 * Do we use this message type for pyout/displayhook? Probably not, because
716 * What is the best way to organize the content dict of the message?
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 content = {
721 content = {
722 'source' : str # Who create the data
722 'source' : str # Who create the data
723 'data' : dict # {'mimetype1' : data1, 'mimetype2' : data2}
723 'data' : dict # {'mimetype1' : data1, 'mimetype2' : data2}
724 'metadata' : dict # Any metadata that describes the data
724 'metadata' : dict # Any metadata that describes the data
725 }
725 }
726
726
727 Other options for ``display_data`` content::
728
727 # Option 2: allowing for a different source for each representation,
729 # Option 2: allowing for a different source for each representation,
728 but not keyed by anything.
730 but not keyed by anything.
729 content = {
731 content = {
730 'data' = [(source, type, data), (source, type, data)]
732 'data' = [(source, type, data), (source, type, data)]
731 'metadata' = dict
733 'metadata' = dict
732 }
734 }
733
735
734 # Option 3: like option 2, but keyed by the MIME types.
736 # Option 3: like option 2, but keyed by the MIME types.
735 content = {
737 content = {
736 'data' = {'mimetype1' : (source, data), 'mimetype2' : (source, data)}
738 'data' = {'mimetype1' : (source, data), 'mimetype2' : (source, data)}
737 'metadata' = dict
739 'metadata' = dict
738 }
740 }
739
741
740 # Option 4: like option 2, but keyed by the source.
742 # Option 4: like option 2, but keyed by the source.
741 content = {
743 content = {
742 'data' = {'source' : (mimetype, data), 'source' : (mimetype, data)}
744 'data' = {'source' : (mimetype, data), 'source' : (mimetype, data)}
743 'metadata' = dict
745 'metadata' = dict
744 }
746 }
745
747
746 Python inputs
748 Python inputs
747 -------------
749 -------------
748
750
749 These messages are the re-broadcast of the ``execute_request``.
751 These messages are the re-broadcast of the ``execute_request``.
750
752
751 Message type: ``pyin``::
753 Message type: ``pyin``::
752
754
753 content = {
755 content = {
754 'code' : str # Source code to be executed, one or more lines
756 'code' : str # Source code to be executed, one or more lines
755 }
757 }
756
758
757 Python outputs
759 Python outputs
758 --------------
760 --------------
759
761
760 When Python produces output from code that has been compiled in with the
762 When Python produces output from code that has been compiled in with the
761 'single' flag to :func:`compile`, any expression that produces a value (such as
763 'single' flag to :func:`compile`, any expression that produces a value (such as
762 ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with
764 ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with
763 this value whatever it wants. The default behavior of ``sys.displayhook`` in
765 this value whatever it wants. The default behavior of ``sys.displayhook`` in
764 the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of
766 the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of
765 the value as long as it is not ``None`` (which isn't printed at all). In our
767 the value as long as it is not ``None`` (which isn't printed at all). In our
766 case, the kernel instantiates as ``sys.displayhook`` an object which has
768 case, the kernel instantiates as ``sys.displayhook`` an object which has
767 similar behavior, but which instead of printing to stdout, broadcasts these
769 similar behavior, but which instead of printing to stdout, broadcasts these
768 values as ``pyout`` messages for clients to display appropriately.
770 values as ``pyout`` messages for clients to display appropriately.
769
771
770 IPython's displayhook can handle multiple simultaneous formats depending on its
772 IPython's displayhook can handle multiple simultaneous formats depending on its
771 configuration. The default pretty-printed repr text is always given with the
773 configuration. The default pretty-printed repr text is always given with the
772 ``data`` entry in this message. Any other formats are provided in the
774 ``data`` entry in this message. Any other formats are provided in the
773 ``extra_formats`` list. Frontends are free to display any or all of these
775 ``extra_formats`` list. Frontends are free to display any or all of these
774 according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID
776 according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID
775 string, a type string, and the data. The ID is unique to the formatter
777 string, a type string, and the data. The ID is unique to the formatter
776 implementation that created the data. Frontends will typically ignore the ID
778 implementation that created the data. Frontends will typically ignore the ID
777 unless if it has requested a particular formatter. The type string tells the
779 unless if it has requested a particular formatter. The type string tells the
778 frontend how to interpret the data. It is often, but not always a MIME type.
780 frontend how to interpret the data. It is often, but not always a MIME type.
779 Frontends should ignore types that it does not understand. The data itself is
781 Frontends should ignore types that it does not understand. The data itself is
780 any JSON object and depends on the format. It is often, but not always a string.
782 any JSON object and depends on the format. It is often, but not always a string.
781
783
782 Message type: ``pyout``::
784 Message type: ``pyout``::
783
785
784 content = {
786 content = {
785 # The data is typically the repr() of the object. It should be displayed
787 # The data is typically the repr() of the object. It should be displayed
786 # as monospaced text.
788 # as monospaced text.
787 'data' : str,
789 'data' : str,
788
790
789 # The counter for this execution is also provided so that clients can
791 # The counter for this execution is also provided so that clients can
790 # display it, since IPython automatically creates variables called _N
792 # display it, since IPython automatically creates variables called _N
791 # (for prompt N).
793 # (for prompt N).
792 'execution_count' : int,
794 'execution_count' : int,
793
795
794 # Any extra formats.
796 # Any extra formats.
795 # The tuples are of the form (ID, type, data).
797 # The tuples are of the form (ID, type, data).
796 'extra_formats' : [
798 'extra_formats' : [
797 [str, str, object]
799 [str, str, object]
798 ]
800 ]
799 }
801 }
800
802
801 Python errors
803 Python errors
802 -------------
804 -------------
803
805
804 When an error occurs during code execution
806 When an error occurs during code execution
805
807
806 Message type: ``pyerr``::
808 Message type: ``pyerr``::
807
809
808 content = {
810 content = {
809 # Similar content to the execute_reply messages for the 'error' case,
811 # Similar content to the execute_reply messages for the 'error' case,
810 # except the 'status' field is omitted.
812 # except the 'status' field is omitted.
811 }
813 }
812
814
813 Kernel status
815 Kernel status
814 -------------
816 -------------
815
817
816 This message type is used by frontends to monitor the status of the kernel.
818 This message type is used by frontends to monitor the status of the kernel.
817
819
818 Message type: ``status``::
820 Message type: ``status``::
819
821
820 content = {
822 content = {
821 # When the kernel starts to execute code, it will enter the 'busy'
823 # When the kernel starts to execute code, it will enter the 'busy'
822 # state and when it finishes, it will enter the 'idle' state.
824 # state and when it finishes, it will enter the 'idle' state.
823 execution_state : ('busy', 'idle')
825 execution_state : ('busy', 'idle')
824 }
826 }
825
827
826 Kernel crashes
828 Kernel crashes
827 --------------
829 --------------
828
830
829 When the kernel has an unexpected exception, caught by the last-resort
831 When the kernel has an unexpected exception, caught by the last-resort
830 sys.excepthook, we should broadcast the crash handler's output before exiting.
832 sys.excepthook, we should broadcast the crash handler's output before exiting.
831 This will allow clients to notice that a kernel died, inform the user and
833 This will allow clients to notice that a kernel died, inform the user and
832 propose further actions.
834 propose further actions.
833
835
834 Message type: ``crash``::
836 Message type: ``crash``::
835
837
836 content = {
838 content = {
837 # Similarly to the 'error' case for execute_reply messages, this will
839 # Similarly to the 'error' case for execute_reply messages, this will
838 # contain exc_name, exc_type and traceback fields.
840 # contain exc_name, exc_type and traceback fields.
839
841
840 # An additional field with supplementary information such as where to
842 # An additional field with supplementary information such as where to
841 # send the crash message
843 # send the crash message
842 'info' : str,
844 'info' : str,
843 }
845 }
844
846
845
847
846 Future ideas
848 Future ideas
847 ------------
849 ------------
848
850
849 Other potential message types, currently unimplemented, listed below as ideas.
851 Other potential message types, currently unimplemented, listed below as ideas.
850
852
851 Message type: ``file``::
853 Message type: ``file``::
852
854
853 content = {
855 content = {
854 'path' : 'cool.jpg',
856 'path' : 'cool.jpg',
855 'mimetype' : str,
857 'mimetype' : str,
856 'data' : str,
858 'data' : str,
857 }
859 }
858
860
859
861
860 Messages on the REQ/REP socket
862 Messages on the REQ/REP socket
861 ==============================
863 ==============================
862
864
863 This is a socket that goes in the opposite direction: from the kernel to a
865 This is a socket that goes in the opposite direction: from the kernel to a
864 *single* frontend, and its purpose is to allow ``raw_input`` and similar
866 *single* frontend, and its purpose is to allow ``raw_input`` and similar
865 operations that read from ``sys.stdin`` on the kernel to be fulfilled by the
867 operations that read from ``sys.stdin`` on the kernel to be fulfilled by the
866 client. For now we will keep these messages as simple as possible, since they
868 client. For now we will keep these messages as simple as possible, since they
867 basically only mean to convey the ``raw_input(prompt)`` call.
869 basically only mean to convey the ``raw_input(prompt)`` call.
868
870
869 Message type: ``input_request``::
871 Message type: ``input_request``::
870
872
871 content = { 'prompt' : str }
873 content = { 'prompt' : str }
872
874
873 Message type: ``input_reply``::
875 Message type: ``input_reply``::
874
876
875 content = { 'value' : str }
877 content = { 'value' : str }
876
878
877 .. Note::
879 .. Note::
878
880
879 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
881 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
880 practice the kernel should behave like an interactive program. When a
882 practice the kernel should behave like an interactive program. When a
881 program is opened on the console, the keyboard effectively takes over the
883 program is opened on the console, the keyboard effectively takes over the
882 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
884 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
883 Since the IPython kernel effectively behaves like a console program (albeit
885 Since the IPython kernel effectively behaves like a console program (albeit
884 one whose "keyboard" is actually living in a separate process and
886 one whose "keyboard" is actually living in a separate process and
885 transported over the zmq connection), raw ``stdin`` isn't expected to be
887 transported over the zmq connection), raw ``stdin`` isn't expected to be
886 available.
888 available.
887
889
888
890
889 Heartbeat for kernels
891 Heartbeat for kernels
890 =====================
892 =====================
891
893
892 Initially we had considered using messages like those above over ZMQ for a
894 Initially we had considered using messages like those above over ZMQ for a
893 kernel 'heartbeat' (a way to detect quickly and reliably whether a kernel is
895 kernel 'heartbeat' (a way to detect quickly and reliably whether a kernel is
894 alive at all, even if it may be busy executing user code). But this has the
896 alive at all, even if it may be busy executing user code). But this has the
895 problem that if the kernel is locked inside extension code, it wouldn't execute
897 problem that if the kernel is locked inside extension code, it wouldn't execute
896 the python heartbeat code. But it turns out that we can implement a basic
898 the python heartbeat code. But it turns out that we can implement a basic
897 heartbeat with pure ZMQ, without using any Python messaging at all.
899 heartbeat with pure ZMQ, without using any Python messaging at all.
898
900
899 The monitor sends out a single zmq message (right now, it is a str of the
901 The monitor sends out a single zmq message (right now, it is a str of the
900 monitor's lifetime in seconds), and gets the same message right back, prefixed
902 monitor's lifetime in seconds), and gets the same message right back, prefixed
901 with the zmq identity of the XREQ socket in the heartbeat process. This can be
903 with the zmq identity of the XREQ socket in the heartbeat process. This can be
902 a uuid, or even a full message, but there doesn't seem to be a need for packing
904 a uuid, or even a full message, but there doesn't seem to be a need for packing
903 up a message when the sender and receiver are the exact same Python object.
905 up a message when the sender and receiver are the exact same Python object.
904
906
905 The model is this::
907 The model is this::
906
908
907 monitor.send(str(self.lifetime)) # '1.2345678910'
909 monitor.send(str(self.lifetime)) # '1.2345678910'
908
910
909 and the monitor receives some number of messages of the form::
911 and the monitor receives some number of messages of the form::
910
912
911 ['uuid-abcd-dead-beef', '1.2345678910']
913 ['uuid-abcd-dead-beef', '1.2345678910']
912
914
913 where the first part is the zmq.IDENTITY of the heart's XREQ on the engine, and
915 where the first part is the zmq.IDENTITY of the heart's XREQ on the engine, and
914 the rest is the message sent by the monitor. No Python code ever has any
916 the rest is the message sent by the monitor. No Python code ever has any
915 access to the message between the monitor's send, and the monitor's recv.
917 access to the message between the monitor's send, and the monitor's recv.
916
918
917
919
918 ToDo
920 ToDo
919 ====
921 ====
920
922
921 Missing things include:
923 Missing things include:
922
924
923 * Important: finish thinking through the payload concept and API.
925 * Important: finish thinking through the payload concept and API.
924
926
925 * Important: ensure that we have a good solution for magics like %edit. It's
927 * Important: ensure that we have a good solution for magics like %edit. It's
926 likely that with the payload concept we can build a full solution, but not
928 likely that with the payload concept we can build a full solution, but not
927 100% clear yet.
929 100% clear yet.
928
930
929 * Finishing the details of the heartbeat protocol.
931 * Finishing the details of the heartbeat protocol.
930
932
931 * Signal handling: specify what kind of information kernel should broadcast (or
933 * Signal handling: specify what kind of information kernel should broadcast (or
932 not) when it receives signals.
934 not) when it receives signals.
933
935
934 .. include:: ../links.rst
936 .. include:: ../links.rst
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now