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