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