##// END OF EJS Templates
Make comm_manager a property of kernel, not shell
Thomas Kluyver -
Show More
@@ -1,3288 +1,3279 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-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 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 from __future__ import absolute_import, print_function
13 from __future__ import absolute_import, print_function
14
14
15 import __future__
15 import __future__
16 import abc
16 import abc
17 import ast
17 import ast
18 import atexit
18 import atexit
19 import functools
19 import functools
20 import os
20 import os
21 import re
21 import re
22 import runpy
22 import runpy
23 import sys
23 import sys
24 import tempfile
24 import tempfile
25 import types
25 import types
26 import subprocess
26 import subprocess
27 from io import open as io_open
27 from io import open as io_open
28
28
29 from IPython.config.configurable import SingletonConfigurable
29 from IPython.config.configurable import SingletonConfigurable
30 from IPython.core import debugger, oinspect
30 from IPython.core import debugger, oinspect
31 from IPython.core import magic
31 from IPython.core import magic
32 from IPython.core import page
32 from IPython.core import page
33 from IPython.core import prefilter
33 from IPython.core import prefilter
34 from IPython.core import shadowns
34 from IPython.core import shadowns
35 from IPython.core import ultratb
35 from IPython.core import ultratb
36 from IPython.core.alias import AliasManager, AliasError
36 from IPython.core.alias import AliasManager, AliasError
37 from IPython.core.autocall import ExitAutocall
37 from IPython.core.autocall import ExitAutocall
38 from IPython.core.builtin_trap import BuiltinTrap
38 from IPython.core.builtin_trap import BuiltinTrap
39 from IPython.core.events import EventManager, available_events
39 from IPython.core.events import EventManager, available_events
40 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
40 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
41 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.displayhook import DisplayHook
42 from IPython.core.displayhook import DisplayHook
43 from IPython.core.displaypub import DisplayPublisher
43 from IPython.core.displaypub import DisplayPublisher
44 from IPython.core.error import InputRejected, UsageError
44 from IPython.core.error import InputRejected, UsageError
45 from IPython.core.extensions import ExtensionManager
45 from IPython.core.extensions import ExtensionManager
46 from IPython.core.formatters import DisplayFormatter
46 from IPython.core.formatters import DisplayFormatter
47 from IPython.core.history import HistoryManager
47 from IPython.core.history import HistoryManager
48 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
48 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
49 from IPython.core.logger import Logger
49 from IPython.core.logger import Logger
50 from IPython.core.macro import Macro
50 from IPython.core.macro import Macro
51 from IPython.core.payload import PayloadManager
51 from IPython.core.payload import PayloadManager
52 from IPython.core.prefilter import PrefilterManager
52 from IPython.core.prefilter import PrefilterManager
53 from IPython.core.profiledir import ProfileDir
53 from IPython.core.profiledir import ProfileDir
54 from IPython.core.prompts import PromptManager
54 from IPython.core.prompts import PromptManager
55 from IPython.core.usage import default_banner
55 from IPython.core.usage import default_banner
56 from IPython.lib.latextools import LaTeXTool
56 from IPython.lib.latextools import LaTeXTool
57 from IPython.testing.skipdoctest import skip_doctest
57 from IPython.testing.skipdoctest import skip_doctest
58 from IPython.utils import PyColorize
58 from IPython.utils import PyColorize
59 from IPython.utils import io
59 from IPython.utils import io
60 from IPython.utils import py3compat
60 from IPython.utils import py3compat
61 from IPython.utils import openpy
61 from IPython.utils import openpy
62 from IPython.utils.decorators import undoc
62 from IPython.utils.decorators import undoc
63 from IPython.utils.io import ask_yes_no
63 from IPython.utils.io import ask_yes_no
64 from IPython.utils.ipstruct import Struct
64 from IPython.utils.ipstruct import Struct
65 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename, ensure_dir_exists
65 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename, ensure_dir_exists
66 from IPython.utils.pickleshare import PickleShareDB
66 from IPython.utils.pickleshare import PickleShareDB
67 from IPython.utils.process import system, getoutput
67 from IPython.utils.process import system, getoutput
68 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
68 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
69 with_metaclass, iteritems)
69 with_metaclass, iteritems)
70 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.strdispatch import StrDispatch
71 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.syspathcontext import prepended_to_syspath
72 from IPython.utils.text import (format_screen, LSString, SList,
72 from IPython.utils.text import (format_screen, LSString, SList,
73 DollarFormatter)
73 DollarFormatter)
74 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
74 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
75 List, Unicode, Instance, Type)
75 List, Unicode, Instance, Type)
76 from IPython.utils.warn import warn, error
76 from IPython.utils.warn import warn, error
77 import IPython.core.hooks
77 import IPython.core.hooks
78
78
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80 # Globals
80 # Globals
81 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
82
82
83 # compiled regexps for autoindent management
83 # compiled regexps for autoindent management
84 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
84 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85
85
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87 # Utilities
87 # Utilities
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89
89
90 @undoc
90 @undoc
91 def softspace(file, newvalue):
91 def softspace(file, newvalue):
92 """Copied from code.py, to remove the dependency"""
92 """Copied from code.py, to remove the dependency"""
93
93
94 oldvalue = 0
94 oldvalue = 0
95 try:
95 try:
96 oldvalue = file.softspace
96 oldvalue = file.softspace
97 except AttributeError:
97 except AttributeError:
98 pass
98 pass
99 try:
99 try:
100 file.softspace = newvalue
100 file.softspace = newvalue
101 except (AttributeError, TypeError):
101 except (AttributeError, TypeError):
102 # "attribute-less object" or "read-only attributes"
102 # "attribute-less object" or "read-only attributes"
103 pass
103 pass
104 return oldvalue
104 return oldvalue
105
105
106 @undoc
106 @undoc
107 def no_op(*a, **kw): pass
107 def no_op(*a, **kw): pass
108
108
109 @undoc
109 @undoc
110 class NoOpContext(object):
110 class NoOpContext(object):
111 def __enter__(self): pass
111 def __enter__(self): pass
112 def __exit__(self, type, value, traceback): pass
112 def __exit__(self, type, value, traceback): pass
113 no_op_context = NoOpContext()
113 no_op_context = NoOpContext()
114
114
115 class SpaceInInput(Exception): pass
115 class SpaceInInput(Exception): pass
116
116
117 @undoc
117 @undoc
118 class Bunch: pass
118 class Bunch: pass
119
119
120
120
121 def get_default_colors():
121 def get_default_colors():
122 if sys.platform=='darwin':
122 if sys.platform=='darwin':
123 return "LightBG"
123 return "LightBG"
124 elif os.name=='nt':
124 elif os.name=='nt':
125 return 'Linux'
125 return 'Linux'
126 else:
126 else:
127 return 'Linux'
127 return 'Linux'
128
128
129
129
130 class SeparateUnicode(Unicode):
130 class SeparateUnicode(Unicode):
131 r"""A Unicode subclass to validate separate_in, separate_out, etc.
131 r"""A Unicode subclass to validate separate_in, separate_out, etc.
132
132
133 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
133 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
134 """
134 """
135
135
136 def validate(self, obj, value):
136 def validate(self, obj, value):
137 if value == '0': value = ''
137 if value == '0': value = ''
138 value = value.replace('\\n','\n')
138 value = value.replace('\\n','\n')
139 return super(SeparateUnicode, self).validate(obj, value)
139 return super(SeparateUnicode, self).validate(obj, value)
140
140
141
141
142 class ReadlineNoRecord(object):
142 class ReadlineNoRecord(object):
143 """Context manager to execute some code, then reload readline history
143 """Context manager to execute some code, then reload readline history
144 so that interactive input to the code doesn't appear when pressing up."""
144 so that interactive input to the code doesn't appear when pressing up."""
145 def __init__(self, shell):
145 def __init__(self, shell):
146 self.shell = shell
146 self.shell = shell
147 self._nested_level = 0
147 self._nested_level = 0
148
148
149 def __enter__(self):
149 def __enter__(self):
150 if self._nested_level == 0:
150 if self._nested_level == 0:
151 try:
151 try:
152 self.orig_length = self.current_length()
152 self.orig_length = self.current_length()
153 self.readline_tail = self.get_readline_tail()
153 self.readline_tail = self.get_readline_tail()
154 except (AttributeError, IndexError): # Can fail with pyreadline
154 except (AttributeError, IndexError): # Can fail with pyreadline
155 self.orig_length, self.readline_tail = 999999, []
155 self.orig_length, self.readline_tail = 999999, []
156 self._nested_level += 1
156 self._nested_level += 1
157
157
158 def __exit__(self, type, value, traceback):
158 def __exit__(self, type, value, traceback):
159 self._nested_level -= 1
159 self._nested_level -= 1
160 if self._nested_level == 0:
160 if self._nested_level == 0:
161 # Try clipping the end if it's got longer
161 # Try clipping the end if it's got longer
162 try:
162 try:
163 e = self.current_length() - self.orig_length
163 e = self.current_length() - self.orig_length
164 if e > 0:
164 if e > 0:
165 for _ in range(e):
165 for _ in range(e):
166 self.shell.readline.remove_history_item(self.orig_length)
166 self.shell.readline.remove_history_item(self.orig_length)
167
167
168 # If it still doesn't match, just reload readline history.
168 # If it still doesn't match, just reload readline history.
169 if self.current_length() != self.orig_length \
169 if self.current_length() != self.orig_length \
170 or self.get_readline_tail() != self.readline_tail:
170 or self.get_readline_tail() != self.readline_tail:
171 self.shell.refill_readline_hist()
171 self.shell.refill_readline_hist()
172 except (AttributeError, IndexError):
172 except (AttributeError, IndexError):
173 pass
173 pass
174 # Returning False will cause exceptions to propagate
174 # Returning False will cause exceptions to propagate
175 return False
175 return False
176
176
177 def current_length(self):
177 def current_length(self):
178 return self.shell.readline.get_current_history_length()
178 return self.shell.readline.get_current_history_length()
179
179
180 def get_readline_tail(self, n=10):
180 def get_readline_tail(self, n=10):
181 """Get the last n items in readline history."""
181 """Get the last n items in readline history."""
182 end = self.shell.readline.get_current_history_length() + 1
182 end = self.shell.readline.get_current_history_length() + 1
183 start = max(end-n, 1)
183 start = max(end-n, 1)
184 ghi = self.shell.readline.get_history_item
184 ghi = self.shell.readline.get_history_item
185 return [ghi(x) for x in range(start, end)]
185 return [ghi(x) for x in range(start, end)]
186
186
187
187
188 @undoc
188 @undoc
189 class DummyMod(object):
189 class DummyMod(object):
190 """A dummy module used for IPython's interactive module when
190 """A dummy module used for IPython's interactive module when
191 a namespace must be assigned to the module's __dict__."""
191 a namespace must be assigned to the module's __dict__."""
192 pass
192 pass
193
193
194 #-----------------------------------------------------------------------------
194 #-----------------------------------------------------------------------------
195 # Main IPython class
195 # Main IPython class
196 #-----------------------------------------------------------------------------
196 #-----------------------------------------------------------------------------
197
197
198 class InteractiveShell(SingletonConfigurable):
198 class InteractiveShell(SingletonConfigurable):
199 """An enhanced, interactive shell for Python."""
199 """An enhanced, interactive shell for Python."""
200
200
201 _instance = None
201 _instance = None
202
202
203 ast_transformers = List([], config=True, help=
203 ast_transformers = List([], config=True, help=
204 """
204 """
205 A list of ast.NodeTransformer subclass instances, which will be applied
205 A list of ast.NodeTransformer subclass instances, which will be applied
206 to user input before code is run.
206 to user input before code is run.
207 """
207 """
208 )
208 )
209
209
210 autocall = Enum((0,1,2), default_value=0, config=True, help=
210 autocall = Enum((0,1,2), default_value=0, config=True, help=
211 """
211 """
212 Make IPython automatically call any callable object even if you didn't
212 Make IPython automatically call any callable object even if you didn't
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 automatically. The value can be '0' to disable the feature, '1' for
214 automatically. The value can be '0' to disable the feature, '1' for
215 'smart' autocall, where it is not applied if there are no more
215 'smart' autocall, where it is not applied if there are no more
216 arguments on the line, and '2' for 'full' autocall, where all callable
216 arguments on the line, and '2' for 'full' autocall, where all callable
217 objects are automatically called (even if no arguments are present).
217 objects are automatically called (even if no arguments are present).
218 """
218 """
219 )
219 )
220 # TODO: remove all autoindent logic and put into frontends.
220 # TODO: remove all autoindent logic and put into frontends.
221 # We can't do this yet because even runlines uses the autoindent.
221 # We can't do this yet because even runlines uses the autoindent.
222 autoindent = CBool(True, config=True, help=
222 autoindent = CBool(True, config=True, help=
223 """
223 """
224 Autoindent IPython code entered interactively.
224 Autoindent IPython code entered interactively.
225 """
225 """
226 )
226 )
227 automagic = CBool(True, config=True, help=
227 automagic = CBool(True, config=True, help=
228 """
228 """
229 Enable magic commands to be called without the leading %.
229 Enable magic commands to be called without the leading %.
230 """
230 """
231 )
231 )
232
232
233 banner = Unicode('')
233 banner = Unicode('')
234
234
235 banner1 = Unicode(default_banner, config=True,
235 banner1 = Unicode(default_banner, config=True,
236 help="""The part of the banner to be printed before the profile"""
236 help="""The part of the banner to be printed before the profile"""
237 )
237 )
238 banner2 = Unicode('', config=True,
238 banner2 = Unicode('', config=True,
239 help="""The part of the banner to be printed after the profile"""
239 help="""The part of the banner to be printed after the profile"""
240 )
240 )
241
241
242 cache_size = Integer(1000, config=True, help=
242 cache_size = Integer(1000, config=True, help=
243 """
243 """
244 Set the size of the output cache. The default is 1000, you can
244 Set the size of the output cache. The default is 1000, you can
245 change it permanently in your config file. Setting it to 0 completely
245 change it permanently in your config file. Setting it to 0 completely
246 disables the caching system, and the minimum value accepted is 20 (if
246 disables the caching system, and the minimum value accepted is 20 (if
247 you provide a value less than 20, it is reset to 0 and a warning is
247 you provide a value less than 20, it is reset to 0 and a warning is
248 issued). This limit is defined because otherwise you'll spend more
248 issued). This limit is defined because otherwise you'll spend more
249 time re-flushing a too small cache than working
249 time re-flushing a too small cache than working
250 """
250 """
251 )
251 )
252 color_info = CBool(True, config=True, help=
252 color_info = CBool(True, config=True, help=
253 """
253 """
254 Use colors for displaying information about objects. Because this
254 Use colors for displaying information about objects. Because this
255 information is passed through a pager (like 'less'), and some pagers
255 information is passed through a pager (like 'less'), and some pagers
256 get confused with color codes, this capability can be turned off.
256 get confused with color codes, this capability can be turned off.
257 """
257 """
258 )
258 )
259 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
259 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
260 default_value=get_default_colors(), config=True,
260 default_value=get_default_colors(), config=True,
261 help="Set the color scheme (NoColor, Linux, or LightBG)."
261 help="Set the color scheme (NoColor, Linux, or LightBG)."
262 )
262 )
263 colors_force = CBool(False, help=
263 colors_force = CBool(False, help=
264 """
264 """
265 Force use of ANSI color codes, regardless of OS and readline
265 Force use of ANSI color codes, regardless of OS and readline
266 availability.
266 availability.
267 """
267 """
268 # FIXME: This is essentially a hack to allow ZMQShell to show colors
268 # FIXME: This is essentially a hack to allow ZMQShell to show colors
269 # without readline on Win32. When the ZMQ formatting system is
269 # without readline on Win32. When the ZMQ formatting system is
270 # refactored, this should be removed.
270 # refactored, this should be removed.
271 )
271 )
272 debug = CBool(False, config=True)
272 debug = CBool(False, config=True)
273 deep_reload = CBool(False, config=True, help=
273 deep_reload = CBool(False, config=True, help=
274 """
274 """
275 Enable deep (recursive) reloading by default. IPython can use the
275 Enable deep (recursive) reloading by default. IPython can use the
276 deep_reload module which reloads changes in modules recursively (it
276 deep_reload module which reloads changes in modules recursively (it
277 replaces the reload() function, so you don't need to change anything to
277 replaces the reload() function, so you don't need to change anything to
278 use it). deep_reload() forces a full reload of modules whose code may
278 use it). deep_reload() forces a full reload of modules whose code may
279 have changed, which the default reload() function does not. When
279 have changed, which the default reload() function does not. When
280 deep_reload is off, IPython will use the normal reload(), but
280 deep_reload is off, IPython will use the normal reload(), but
281 deep_reload will still be available as dreload().
281 deep_reload will still be available as dreload().
282 """
282 """
283 )
283 )
284 disable_failing_post_execute = CBool(False, config=True,
284 disable_failing_post_execute = CBool(False, config=True,
285 help="Don't call post-execute functions that have failed in the past."
285 help="Don't call post-execute functions that have failed in the past."
286 )
286 )
287 display_formatter = Instance(DisplayFormatter)
287 display_formatter = Instance(DisplayFormatter)
288 displayhook_class = Type(DisplayHook)
288 displayhook_class = Type(DisplayHook)
289 display_pub_class = Type(DisplayPublisher)
289 display_pub_class = Type(DisplayPublisher)
290 data_pub_class = None
290 data_pub_class = None
291
291
292 exit_now = CBool(False)
292 exit_now = CBool(False)
293 exiter = Instance(ExitAutocall)
293 exiter = Instance(ExitAutocall)
294 def _exiter_default(self):
294 def _exiter_default(self):
295 return ExitAutocall(self)
295 return ExitAutocall(self)
296 # Monotonically increasing execution counter
296 # Monotonically increasing execution counter
297 execution_count = Integer(1)
297 execution_count = Integer(1)
298 filename = Unicode("<ipython console>")
298 filename = Unicode("<ipython console>")
299 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
299 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
300
300
301 # Input splitter, to transform input line by line and detect when a block
301 # Input splitter, to transform input line by line and detect when a block
302 # is ready to be executed.
302 # is ready to be executed.
303 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
303 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
304 (), {'line_input_checker': True})
304 (), {'line_input_checker': True})
305
305
306 # This InputSplitter instance is used to transform completed cells before
306 # This InputSplitter instance is used to transform completed cells before
307 # running them. It allows cell magics to contain blank lines.
307 # running them. It allows cell magics to contain blank lines.
308 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
308 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
309 (), {'line_input_checker': False})
309 (), {'line_input_checker': False})
310
310
311 logstart = CBool(False, config=True, help=
311 logstart = CBool(False, config=True, help=
312 """
312 """
313 Start logging to the default log file.
313 Start logging to the default log file.
314 """
314 """
315 )
315 )
316 logfile = Unicode('', config=True, help=
316 logfile = Unicode('', config=True, help=
317 """
317 """
318 The name of the logfile to use.
318 The name of the logfile to use.
319 """
319 """
320 )
320 )
321 logappend = Unicode('', config=True, help=
321 logappend = Unicode('', config=True, help=
322 """
322 """
323 Start logging to the given file in append mode.
323 Start logging to the given file in append mode.
324 """
324 """
325 )
325 )
326 object_info_string_level = Enum((0,1,2), default_value=0,
326 object_info_string_level = Enum((0,1,2), default_value=0,
327 config=True)
327 config=True)
328 pdb = CBool(False, config=True, help=
328 pdb = CBool(False, config=True, help=
329 """
329 """
330 Automatically call the pdb debugger after every exception.
330 Automatically call the pdb debugger after every exception.
331 """
331 """
332 )
332 )
333 multiline_history = CBool(sys.platform != 'win32', config=True,
333 multiline_history = CBool(sys.platform != 'win32', config=True,
334 help="Save multi-line entries as one entry in readline history"
334 help="Save multi-line entries as one entry in readline history"
335 )
335 )
336
336
337 # deprecated prompt traits:
337 # deprecated prompt traits:
338
338
339 prompt_in1 = Unicode('In [\\#]: ', config=True,
339 prompt_in1 = Unicode('In [\\#]: ', config=True,
340 help="Deprecated, use PromptManager.in_template")
340 help="Deprecated, use PromptManager.in_template")
341 prompt_in2 = Unicode(' .\\D.: ', config=True,
341 prompt_in2 = Unicode(' .\\D.: ', config=True,
342 help="Deprecated, use PromptManager.in2_template")
342 help="Deprecated, use PromptManager.in2_template")
343 prompt_out = Unicode('Out[\\#]: ', config=True,
343 prompt_out = Unicode('Out[\\#]: ', config=True,
344 help="Deprecated, use PromptManager.out_template")
344 help="Deprecated, use PromptManager.out_template")
345 prompts_pad_left = CBool(True, config=True,
345 prompts_pad_left = CBool(True, config=True,
346 help="Deprecated, use PromptManager.justify")
346 help="Deprecated, use PromptManager.justify")
347
347
348 def _prompt_trait_changed(self, name, old, new):
348 def _prompt_trait_changed(self, name, old, new):
349 table = {
349 table = {
350 'prompt_in1' : 'in_template',
350 'prompt_in1' : 'in_template',
351 'prompt_in2' : 'in2_template',
351 'prompt_in2' : 'in2_template',
352 'prompt_out' : 'out_template',
352 'prompt_out' : 'out_template',
353 'prompts_pad_left' : 'justify',
353 'prompts_pad_left' : 'justify',
354 }
354 }
355 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
355 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
356 name=name, newname=table[name])
356 name=name, newname=table[name])
357 )
357 )
358 # protect against weird cases where self.config may not exist:
358 # protect against weird cases where self.config may not exist:
359 if self.config is not None:
359 if self.config is not None:
360 # propagate to corresponding PromptManager trait
360 # propagate to corresponding PromptManager trait
361 setattr(self.config.PromptManager, table[name], new)
361 setattr(self.config.PromptManager, table[name], new)
362
362
363 _prompt_in1_changed = _prompt_trait_changed
363 _prompt_in1_changed = _prompt_trait_changed
364 _prompt_in2_changed = _prompt_trait_changed
364 _prompt_in2_changed = _prompt_trait_changed
365 _prompt_out_changed = _prompt_trait_changed
365 _prompt_out_changed = _prompt_trait_changed
366 _prompt_pad_left_changed = _prompt_trait_changed
366 _prompt_pad_left_changed = _prompt_trait_changed
367
367
368 show_rewritten_input = CBool(True, config=True,
368 show_rewritten_input = CBool(True, config=True,
369 help="Show rewritten input, e.g. for autocall."
369 help="Show rewritten input, e.g. for autocall."
370 )
370 )
371
371
372 quiet = CBool(False, config=True)
372 quiet = CBool(False, config=True)
373
373
374 history_length = Integer(10000, config=True)
374 history_length = Integer(10000, config=True)
375
375
376 # The readline stuff will eventually be moved to the terminal subclass
376 # The readline stuff will eventually be moved to the terminal subclass
377 # but for now, we can't do that as readline is welded in everywhere.
377 # but for now, we can't do that as readline is welded in everywhere.
378 readline_use = CBool(True, config=True)
378 readline_use = CBool(True, config=True)
379 readline_remove_delims = Unicode('-/~', config=True)
379 readline_remove_delims = Unicode('-/~', config=True)
380 readline_delims = Unicode() # set by init_readline()
380 readline_delims = Unicode() # set by init_readline()
381 # don't use \M- bindings by default, because they
381 # don't use \M- bindings by default, because they
382 # conflict with 8-bit encodings. See gh-58,gh-88
382 # conflict with 8-bit encodings. See gh-58,gh-88
383 readline_parse_and_bind = List([
383 readline_parse_and_bind = List([
384 'tab: complete',
384 'tab: complete',
385 '"\C-l": clear-screen',
385 '"\C-l": clear-screen',
386 'set show-all-if-ambiguous on',
386 'set show-all-if-ambiguous on',
387 '"\C-o": tab-insert',
387 '"\C-o": tab-insert',
388 '"\C-r": reverse-search-history',
388 '"\C-r": reverse-search-history',
389 '"\C-s": forward-search-history',
389 '"\C-s": forward-search-history',
390 '"\C-p": history-search-backward',
390 '"\C-p": history-search-backward',
391 '"\C-n": history-search-forward',
391 '"\C-n": history-search-forward',
392 '"\e[A": history-search-backward',
392 '"\e[A": history-search-backward',
393 '"\e[B": history-search-forward',
393 '"\e[B": history-search-forward',
394 '"\C-k": kill-line',
394 '"\C-k": kill-line',
395 '"\C-u": unix-line-discard',
395 '"\C-u": unix-line-discard',
396 ], config=True)
396 ], config=True)
397
397
398 _custom_readline_config = False
398 _custom_readline_config = False
399
399
400 def _readline_parse_and_bind_changed(self, name, old, new):
400 def _readline_parse_and_bind_changed(self, name, old, new):
401 # notice that readline config is customized
401 # notice that readline config is customized
402 # indicates that it should have higher priority than inputrc
402 # indicates that it should have higher priority than inputrc
403 self._custom_readline_config = True
403 self._custom_readline_config = True
404
404
405 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
405 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
406 default_value='last_expr', config=True,
406 default_value='last_expr', config=True,
407 help="""
407 help="""
408 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
408 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
409 run interactively (displaying output from expressions).""")
409 run interactively (displaying output from expressions).""")
410
410
411 # TODO: this part of prompt management should be moved to the frontends.
411 # TODO: this part of prompt management should be moved to the frontends.
412 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
412 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
413 separate_in = SeparateUnicode('\n', config=True)
413 separate_in = SeparateUnicode('\n', config=True)
414 separate_out = SeparateUnicode('', config=True)
414 separate_out = SeparateUnicode('', config=True)
415 separate_out2 = SeparateUnicode('', config=True)
415 separate_out2 = SeparateUnicode('', config=True)
416 wildcards_case_sensitive = CBool(True, config=True)
416 wildcards_case_sensitive = CBool(True, config=True)
417 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
417 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
418 default_value='Context', config=True)
418 default_value='Context', config=True)
419
419
420 # Subcomponents of InteractiveShell
420 # Subcomponents of InteractiveShell
421 alias_manager = Instance('IPython.core.alias.AliasManager')
421 alias_manager = Instance('IPython.core.alias.AliasManager')
422 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
422 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
423 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
423 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
424 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
424 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
425 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
425 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
426 payload_manager = Instance('IPython.core.payload.PayloadManager')
426 payload_manager = Instance('IPython.core.payload.PayloadManager')
427 history_manager = Instance('IPython.core.history.HistoryManager')
427 history_manager = Instance('IPython.core.history.HistoryManager')
428 magics_manager = Instance('IPython.core.magic.MagicsManager')
428 magics_manager = Instance('IPython.core.magic.MagicsManager')
429
429
430 profile_dir = Instance('IPython.core.application.ProfileDir')
430 profile_dir = Instance('IPython.core.application.ProfileDir')
431 @property
431 @property
432 def profile(self):
432 def profile(self):
433 if self.profile_dir is not None:
433 if self.profile_dir is not None:
434 name = os.path.basename(self.profile_dir.location)
434 name = os.path.basename(self.profile_dir.location)
435 return name.replace('profile_','')
435 return name.replace('profile_','')
436
436
437
437
438 # Private interface
438 # Private interface
439 _post_execute = Instance(dict)
439 _post_execute = Instance(dict)
440
440
441 # Tracks any GUI loop loaded for pylab
441 # Tracks any GUI loop loaded for pylab
442 pylab_gui_select = None
442 pylab_gui_select = None
443
443
444 def __init__(self, ipython_dir=None, profile_dir=None,
444 def __init__(self, ipython_dir=None, profile_dir=None,
445 user_module=None, user_ns=None,
445 user_module=None, user_ns=None,
446 custom_exceptions=((), None), **kwargs):
446 custom_exceptions=((), None), **kwargs):
447
447
448 # This is where traits with a config_key argument are updated
448 # This is where traits with a config_key argument are updated
449 # from the values on config.
449 # from the values on config.
450 super(InteractiveShell, self).__init__(**kwargs)
450 super(InteractiveShell, self).__init__(**kwargs)
451 self.configurables = [self]
451 self.configurables = [self]
452
452
453 # These are relatively independent and stateless
453 # These are relatively independent and stateless
454 self.init_ipython_dir(ipython_dir)
454 self.init_ipython_dir(ipython_dir)
455 self.init_profile_dir(profile_dir)
455 self.init_profile_dir(profile_dir)
456 self.init_instance_attrs()
456 self.init_instance_attrs()
457 self.init_environment()
457 self.init_environment()
458
458
459 # Check if we're in a virtualenv, and set up sys.path.
459 # Check if we're in a virtualenv, and set up sys.path.
460 self.init_virtualenv()
460 self.init_virtualenv()
461
461
462 # Create namespaces (user_ns, user_global_ns, etc.)
462 # Create namespaces (user_ns, user_global_ns, etc.)
463 self.init_create_namespaces(user_module, user_ns)
463 self.init_create_namespaces(user_module, user_ns)
464 # This has to be done after init_create_namespaces because it uses
464 # This has to be done after init_create_namespaces because it uses
465 # something in self.user_ns, but before init_sys_modules, which
465 # something in self.user_ns, but before init_sys_modules, which
466 # is the first thing to modify sys.
466 # is the first thing to modify sys.
467 # TODO: When we override sys.stdout and sys.stderr before this class
467 # TODO: When we override sys.stdout and sys.stderr before this class
468 # is created, we are saving the overridden ones here. Not sure if this
468 # is created, we are saving the overridden ones here. Not sure if this
469 # is what we want to do.
469 # is what we want to do.
470 self.save_sys_module_state()
470 self.save_sys_module_state()
471 self.init_sys_modules()
471 self.init_sys_modules()
472
472
473 # While we're trying to have each part of the code directly access what
473 # While we're trying to have each part of the code directly access what
474 # it needs without keeping redundant references to objects, we have too
474 # it needs without keeping redundant references to objects, we have too
475 # much legacy code that expects ip.db to exist.
475 # much legacy code that expects ip.db to exist.
476 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
476 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
477
477
478 self.init_history()
478 self.init_history()
479 self.init_encoding()
479 self.init_encoding()
480 self.init_prefilter()
480 self.init_prefilter()
481
481
482 self.init_syntax_highlighting()
482 self.init_syntax_highlighting()
483 self.init_hooks()
483 self.init_hooks()
484 self.init_events()
484 self.init_events()
485 self.init_pushd_popd_magic()
485 self.init_pushd_popd_magic()
486 # self.init_traceback_handlers use to be here, but we moved it below
486 # self.init_traceback_handlers use to be here, but we moved it below
487 # because it and init_io have to come after init_readline.
487 # because it and init_io have to come after init_readline.
488 self.init_user_ns()
488 self.init_user_ns()
489 self.init_logger()
489 self.init_logger()
490 self.init_builtins()
490 self.init_builtins()
491
491
492 # The following was in post_config_initialization
492 # The following was in post_config_initialization
493 self.init_inspector()
493 self.init_inspector()
494 # init_readline() must come before init_io(), because init_io uses
494 # init_readline() must come before init_io(), because init_io uses
495 # readline related things.
495 # readline related things.
496 self.init_readline()
496 self.init_readline()
497 # We save this here in case user code replaces raw_input, but it needs
497 # We save this here in case user code replaces raw_input, but it needs
498 # to be after init_readline(), because PyPy's readline works by replacing
498 # to be after init_readline(), because PyPy's readline works by replacing
499 # raw_input.
499 # raw_input.
500 if py3compat.PY3:
500 if py3compat.PY3:
501 self.raw_input_original = input
501 self.raw_input_original = input
502 else:
502 else:
503 self.raw_input_original = raw_input
503 self.raw_input_original = raw_input
504 # init_completer must come after init_readline, because it needs to
504 # init_completer must come after init_readline, because it needs to
505 # know whether readline is present or not system-wide to configure the
505 # know whether readline is present or not system-wide to configure the
506 # completers, since the completion machinery can now operate
506 # completers, since the completion machinery can now operate
507 # independently of readline (e.g. over the network)
507 # independently of readline (e.g. over the network)
508 self.init_completer()
508 self.init_completer()
509 # TODO: init_io() needs to happen before init_traceback handlers
509 # TODO: init_io() needs to happen before init_traceback handlers
510 # because the traceback handlers hardcode the stdout/stderr streams.
510 # because the traceback handlers hardcode the stdout/stderr streams.
511 # This logic in in debugger.Pdb and should eventually be changed.
511 # This logic in in debugger.Pdb and should eventually be changed.
512 self.init_io()
512 self.init_io()
513 self.init_traceback_handlers(custom_exceptions)
513 self.init_traceback_handlers(custom_exceptions)
514 self.init_prompts()
514 self.init_prompts()
515 self.init_display_formatter()
515 self.init_display_formatter()
516 self.init_display_pub()
516 self.init_display_pub()
517 self.init_data_pub()
517 self.init_data_pub()
518 self.init_displayhook()
518 self.init_displayhook()
519 self.init_latextool()
519 self.init_latextool()
520 self.init_magics()
520 self.init_magics()
521 self.init_alias()
521 self.init_alias()
522 self.init_logstart()
522 self.init_logstart()
523 self.init_pdb()
523 self.init_pdb()
524 self.init_extension_manager()
524 self.init_extension_manager()
525 self.init_payload()
525 self.init_payload()
526 self.init_comms()
527 self.hooks.late_startup_hook()
526 self.hooks.late_startup_hook()
528 self.events.trigger('shell_initialized', self)
527 self.events.trigger('shell_initialized', self)
529 atexit.register(self.atexit_operations)
528 atexit.register(self.atexit_operations)
530
529
531 def get_ipython(self):
530 def get_ipython(self):
532 """Return the currently running IPython instance."""
531 """Return the currently running IPython instance."""
533 return self
532 return self
534
533
535 #-------------------------------------------------------------------------
534 #-------------------------------------------------------------------------
536 # Trait changed handlers
535 # Trait changed handlers
537 #-------------------------------------------------------------------------
536 #-------------------------------------------------------------------------
538
537
539 def _ipython_dir_changed(self, name, new):
538 def _ipython_dir_changed(self, name, new):
540 ensure_dir_exists(new)
539 ensure_dir_exists(new)
541
540
542 def set_autoindent(self,value=None):
541 def set_autoindent(self,value=None):
543 """Set the autoindent flag, checking for readline support.
542 """Set the autoindent flag, checking for readline support.
544
543
545 If called with no arguments, it acts as a toggle."""
544 If called with no arguments, it acts as a toggle."""
546
545
547 if value != 0 and not self.has_readline:
546 if value != 0 and not self.has_readline:
548 if os.name == 'posix':
547 if os.name == 'posix':
549 warn("The auto-indent feature requires the readline library")
548 warn("The auto-indent feature requires the readline library")
550 self.autoindent = 0
549 self.autoindent = 0
551 return
550 return
552 if value is None:
551 if value is None:
553 self.autoindent = not self.autoindent
552 self.autoindent = not self.autoindent
554 else:
553 else:
555 self.autoindent = value
554 self.autoindent = value
556
555
557 #-------------------------------------------------------------------------
556 #-------------------------------------------------------------------------
558 # init_* methods called by __init__
557 # init_* methods called by __init__
559 #-------------------------------------------------------------------------
558 #-------------------------------------------------------------------------
560
559
561 def init_ipython_dir(self, ipython_dir):
560 def init_ipython_dir(self, ipython_dir):
562 if ipython_dir is not None:
561 if ipython_dir is not None:
563 self.ipython_dir = ipython_dir
562 self.ipython_dir = ipython_dir
564 return
563 return
565
564
566 self.ipython_dir = get_ipython_dir()
565 self.ipython_dir = get_ipython_dir()
567
566
568 def init_profile_dir(self, profile_dir):
567 def init_profile_dir(self, profile_dir):
569 if profile_dir is not None:
568 if profile_dir is not None:
570 self.profile_dir = profile_dir
569 self.profile_dir = profile_dir
571 return
570 return
572 self.profile_dir =\
571 self.profile_dir =\
573 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
572 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
574
573
575 def init_instance_attrs(self):
574 def init_instance_attrs(self):
576 self.more = False
575 self.more = False
577
576
578 # command compiler
577 # command compiler
579 self.compile = CachingCompiler()
578 self.compile = CachingCompiler()
580
579
581 # Make an empty namespace, which extension writers can rely on both
580 # Make an empty namespace, which extension writers can rely on both
582 # existing and NEVER being used by ipython itself. This gives them a
581 # existing and NEVER being used by ipython itself. This gives them a
583 # convenient location for storing additional information and state
582 # convenient location for storing additional information and state
584 # their extensions may require, without fear of collisions with other
583 # their extensions may require, without fear of collisions with other
585 # ipython names that may develop later.
584 # ipython names that may develop later.
586 self.meta = Struct()
585 self.meta = Struct()
587
586
588 # Temporary files used for various purposes. Deleted at exit.
587 # Temporary files used for various purposes. Deleted at exit.
589 self.tempfiles = []
588 self.tempfiles = []
590 self.tempdirs = []
589 self.tempdirs = []
591
590
592 # Keep track of readline usage (later set by init_readline)
591 # Keep track of readline usage (later set by init_readline)
593 self.has_readline = False
592 self.has_readline = False
594
593
595 # keep track of where we started running (mainly for crash post-mortem)
594 # keep track of where we started running (mainly for crash post-mortem)
596 # This is not being used anywhere currently.
595 # This is not being used anywhere currently.
597 self.starting_dir = py3compat.getcwd()
596 self.starting_dir = py3compat.getcwd()
598
597
599 # Indentation management
598 # Indentation management
600 self.indent_current_nsp = 0
599 self.indent_current_nsp = 0
601
600
602 # Dict to track post-execution functions that have been registered
601 # Dict to track post-execution functions that have been registered
603 self._post_execute = {}
602 self._post_execute = {}
604
603
605 def init_environment(self):
604 def init_environment(self):
606 """Any changes we need to make to the user's environment."""
605 """Any changes we need to make to the user's environment."""
607 pass
606 pass
608
607
609 def init_encoding(self):
608 def init_encoding(self):
610 # Get system encoding at startup time. Certain terminals (like Emacs
609 # Get system encoding at startup time. Certain terminals (like Emacs
611 # under Win32 have it set to None, and we need to have a known valid
610 # under Win32 have it set to None, and we need to have a known valid
612 # encoding to use in the raw_input() method
611 # encoding to use in the raw_input() method
613 try:
612 try:
614 self.stdin_encoding = sys.stdin.encoding or 'ascii'
613 self.stdin_encoding = sys.stdin.encoding or 'ascii'
615 except AttributeError:
614 except AttributeError:
616 self.stdin_encoding = 'ascii'
615 self.stdin_encoding = 'ascii'
617
616
618 def init_syntax_highlighting(self):
617 def init_syntax_highlighting(self):
619 # Python source parser/formatter for syntax highlighting
618 # Python source parser/formatter for syntax highlighting
620 pyformat = PyColorize.Parser().format
619 pyformat = PyColorize.Parser().format
621 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
620 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
622
621
623 def init_pushd_popd_magic(self):
622 def init_pushd_popd_magic(self):
624 # for pushd/popd management
623 # for pushd/popd management
625 self.home_dir = get_home_dir()
624 self.home_dir = get_home_dir()
626
625
627 self.dir_stack = []
626 self.dir_stack = []
628
627
629 def init_logger(self):
628 def init_logger(self):
630 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
629 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
631 logmode='rotate')
630 logmode='rotate')
632
631
633 def init_logstart(self):
632 def init_logstart(self):
634 """Initialize logging in case it was requested at the command line.
633 """Initialize logging in case it was requested at the command line.
635 """
634 """
636 if self.logappend:
635 if self.logappend:
637 self.magic('logstart %s append' % self.logappend)
636 self.magic('logstart %s append' % self.logappend)
638 elif self.logfile:
637 elif self.logfile:
639 self.magic('logstart %s' % self.logfile)
638 self.magic('logstart %s' % self.logfile)
640 elif self.logstart:
639 elif self.logstart:
641 self.magic('logstart')
640 self.magic('logstart')
642
641
643 def init_builtins(self):
642 def init_builtins(self):
644 # A single, static flag that we set to True. Its presence indicates
643 # A single, static flag that we set to True. Its presence indicates
645 # that an IPython shell has been created, and we make no attempts at
644 # that an IPython shell has been created, and we make no attempts at
646 # removing on exit or representing the existence of more than one
645 # removing on exit or representing the existence of more than one
647 # IPython at a time.
646 # IPython at a time.
648 builtin_mod.__dict__['__IPYTHON__'] = True
647 builtin_mod.__dict__['__IPYTHON__'] = True
649
648
650 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
649 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
651 # manage on enter/exit, but with all our shells it's virtually
650 # manage on enter/exit, but with all our shells it's virtually
652 # impossible to get all the cases right. We're leaving the name in for
651 # impossible to get all the cases right. We're leaving the name in for
653 # those who adapted their codes to check for this flag, but will
652 # those who adapted their codes to check for this flag, but will
654 # eventually remove it after a few more releases.
653 # eventually remove it after a few more releases.
655 builtin_mod.__dict__['__IPYTHON__active'] = \
654 builtin_mod.__dict__['__IPYTHON__active'] = \
656 'Deprecated, check for __IPYTHON__'
655 'Deprecated, check for __IPYTHON__'
657
656
658 self.builtin_trap = BuiltinTrap(shell=self)
657 self.builtin_trap = BuiltinTrap(shell=self)
659
658
660 def init_inspector(self):
659 def init_inspector(self):
661 # Object inspector
660 # Object inspector
662 self.inspector = oinspect.Inspector(oinspect.InspectColors,
661 self.inspector = oinspect.Inspector(oinspect.InspectColors,
663 PyColorize.ANSICodeColors,
662 PyColorize.ANSICodeColors,
664 'NoColor',
663 'NoColor',
665 self.object_info_string_level)
664 self.object_info_string_level)
666
665
667 def init_io(self):
666 def init_io(self):
668 # This will just use sys.stdout and sys.stderr. If you want to
667 # This will just use sys.stdout and sys.stderr. If you want to
669 # override sys.stdout and sys.stderr themselves, you need to do that
668 # override sys.stdout and sys.stderr themselves, you need to do that
670 # *before* instantiating this class, because io holds onto
669 # *before* instantiating this class, because io holds onto
671 # references to the underlying streams.
670 # references to the underlying streams.
672 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
671 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
673 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
672 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
674 else:
673 else:
675 io.stdout = io.IOStream(sys.stdout)
674 io.stdout = io.IOStream(sys.stdout)
676 io.stderr = io.IOStream(sys.stderr)
675 io.stderr = io.IOStream(sys.stderr)
677
676
678 def init_prompts(self):
677 def init_prompts(self):
679 self.prompt_manager = PromptManager(shell=self, parent=self)
678 self.prompt_manager = PromptManager(shell=self, parent=self)
680 self.configurables.append(self.prompt_manager)
679 self.configurables.append(self.prompt_manager)
681 # Set system prompts, so that scripts can decide if they are running
680 # Set system prompts, so that scripts can decide if they are running
682 # interactively.
681 # interactively.
683 sys.ps1 = 'In : '
682 sys.ps1 = 'In : '
684 sys.ps2 = '...: '
683 sys.ps2 = '...: '
685 sys.ps3 = 'Out: '
684 sys.ps3 = 'Out: '
686
685
687 def init_display_formatter(self):
686 def init_display_formatter(self):
688 self.display_formatter = DisplayFormatter(parent=self)
687 self.display_formatter = DisplayFormatter(parent=self)
689 self.configurables.append(self.display_formatter)
688 self.configurables.append(self.display_formatter)
690
689
691 def init_display_pub(self):
690 def init_display_pub(self):
692 self.display_pub = self.display_pub_class(parent=self)
691 self.display_pub = self.display_pub_class(parent=self)
693 self.configurables.append(self.display_pub)
692 self.configurables.append(self.display_pub)
694
693
695 def init_data_pub(self):
694 def init_data_pub(self):
696 if not self.data_pub_class:
695 if not self.data_pub_class:
697 self.data_pub = None
696 self.data_pub = None
698 return
697 return
699 self.data_pub = self.data_pub_class(parent=self)
698 self.data_pub = self.data_pub_class(parent=self)
700 self.configurables.append(self.data_pub)
699 self.configurables.append(self.data_pub)
701
700
702 def init_displayhook(self):
701 def init_displayhook(self):
703 # Initialize displayhook, set in/out prompts and printing system
702 # Initialize displayhook, set in/out prompts and printing system
704 self.displayhook = self.displayhook_class(
703 self.displayhook = self.displayhook_class(
705 parent=self,
704 parent=self,
706 shell=self,
705 shell=self,
707 cache_size=self.cache_size,
706 cache_size=self.cache_size,
708 )
707 )
709 self.configurables.append(self.displayhook)
708 self.configurables.append(self.displayhook)
710 # This is a context manager that installs/revmoes the displayhook at
709 # This is a context manager that installs/revmoes the displayhook at
711 # the appropriate time.
710 # the appropriate time.
712 self.display_trap = DisplayTrap(hook=self.displayhook)
711 self.display_trap = DisplayTrap(hook=self.displayhook)
713
712
714 def init_latextool(self):
713 def init_latextool(self):
715 """Configure LaTeXTool."""
714 """Configure LaTeXTool."""
716 cfg = LaTeXTool.instance(parent=self)
715 cfg = LaTeXTool.instance(parent=self)
717 if cfg not in self.configurables:
716 if cfg not in self.configurables:
718 self.configurables.append(cfg)
717 self.configurables.append(cfg)
719
718
720 def init_virtualenv(self):
719 def init_virtualenv(self):
721 """Add a virtualenv to sys.path so the user can import modules from it.
720 """Add a virtualenv to sys.path so the user can import modules from it.
722 This isn't perfect: it doesn't use the Python interpreter with which the
721 This isn't perfect: it doesn't use the Python interpreter with which the
723 virtualenv was built, and it ignores the --no-site-packages option. A
722 virtualenv was built, and it ignores the --no-site-packages option. A
724 warning will appear suggesting the user installs IPython in the
723 warning will appear suggesting the user installs IPython in the
725 virtualenv, but for many cases, it probably works well enough.
724 virtualenv, but for many cases, it probably works well enough.
726
725
727 Adapted from code snippets online.
726 Adapted from code snippets online.
728
727
729 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
728 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
730 """
729 """
731 if 'VIRTUAL_ENV' not in os.environ:
730 if 'VIRTUAL_ENV' not in os.environ:
732 # Not in a virtualenv
731 # Not in a virtualenv
733 return
732 return
734
733
735 # venv detection:
734 # venv detection:
736 # stdlib venv may symlink sys.executable, so we can't use realpath.
735 # stdlib venv may symlink sys.executable, so we can't use realpath.
737 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
736 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
738 # So we just check every item in the symlink tree (generally <= 3)
737 # So we just check every item in the symlink tree (generally <= 3)
739 p = os.path.normcase(sys.executable)
738 p = os.path.normcase(sys.executable)
740 paths = [p]
739 paths = [p]
741 while os.path.islink(p):
740 while os.path.islink(p):
742 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
741 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
743 paths.append(p)
742 paths.append(p)
744 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
743 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
745 if any(p.startswith(p_venv) for p in paths):
744 if any(p.startswith(p_venv) for p in paths):
746 # Running properly in the virtualenv, don't need to do anything
745 # Running properly in the virtualenv, don't need to do anything
747 return
746 return
748
747
749 warn("Attempting to work in a virtualenv. If you encounter problems, please "
748 warn("Attempting to work in a virtualenv. If you encounter problems, please "
750 "install IPython inside the virtualenv.")
749 "install IPython inside the virtualenv.")
751 if sys.platform == "win32":
750 if sys.platform == "win32":
752 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
751 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
753 else:
752 else:
754 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
753 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
755 'python%d.%d' % sys.version_info[:2], 'site-packages')
754 'python%d.%d' % sys.version_info[:2], 'site-packages')
756
755
757 import site
756 import site
758 sys.path.insert(0, virtual_env)
757 sys.path.insert(0, virtual_env)
759 site.addsitedir(virtual_env)
758 site.addsitedir(virtual_env)
760
759
761 #-------------------------------------------------------------------------
760 #-------------------------------------------------------------------------
762 # Things related to injections into the sys module
761 # Things related to injections into the sys module
763 #-------------------------------------------------------------------------
762 #-------------------------------------------------------------------------
764
763
765 def save_sys_module_state(self):
764 def save_sys_module_state(self):
766 """Save the state of hooks in the sys module.
765 """Save the state of hooks in the sys module.
767
766
768 This has to be called after self.user_module is created.
767 This has to be called after self.user_module is created.
769 """
768 """
770 self._orig_sys_module_state = {}
769 self._orig_sys_module_state = {}
771 self._orig_sys_module_state['stdin'] = sys.stdin
770 self._orig_sys_module_state['stdin'] = sys.stdin
772 self._orig_sys_module_state['stdout'] = sys.stdout
771 self._orig_sys_module_state['stdout'] = sys.stdout
773 self._orig_sys_module_state['stderr'] = sys.stderr
772 self._orig_sys_module_state['stderr'] = sys.stderr
774 self._orig_sys_module_state['excepthook'] = sys.excepthook
773 self._orig_sys_module_state['excepthook'] = sys.excepthook
775 self._orig_sys_modules_main_name = self.user_module.__name__
774 self._orig_sys_modules_main_name = self.user_module.__name__
776 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
775 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
777
776
778 def restore_sys_module_state(self):
777 def restore_sys_module_state(self):
779 """Restore the state of the sys module."""
778 """Restore the state of the sys module."""
780 try:
779 try:
781 for k, v in iteritems(self._orig_sys_module_state):
780 for k, v in iteritems(self._orig_sys_module_state):
782 setattr(sys, k, v)
781 setattr(sys, k, v)
783 except AttributeError:
782 except AttributeError:
784 pass
783 pass
785 # Reset what what done in self.init_sys_modules
784 # Reset what what done in self.init_sys_modules
786 if self._orig_sys_modules_main_mod is not None:
785 if self._orig_sys_modules_main_mod is not None:
787 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
786 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
788
787
789 #-------------------------------------------------------------------------
788 #-------------------------------------------------------------------------
790 # Things related to the banner
789 # Things related to the banner
791 #-------------------------------------------------------------------------
790 #-------------------------------------------------------------------------
792
791
793 @property
792 @property
794 def banner(self):
793 def banner(self):
795 banner = self.banner1
794 banner = self.banner1
796 if self.profile and self.profile != 'default':
795 if self.profile and self.profile != 'default':
797 banner += '\nIPython profile: %s\n' % self.profile
796 banner += '\nIPython profile: %s\n' % self.profile
798 if self.banner2:
797 if self.banner2:
799 banner += '\n' + self.banner2
798 banner += '\n' + self.banner2
800 return banner
799 return banner
801
800
802 def show_banner(self, banner=None):
801 def show_banner(self, banner=None):
803 if banner is None:
802 if banner is None:
804 banner = self.banner
803 banner = self.banner
805 self.write(banner)
804 self.write(banner)
806
805
807 #-------------------------------------------------------------------------
806 #-------------------------------------------------------------------------
808 # Things related to hooks
807 # Things related to hooks
809 #-------------------------------------------------------------------------
808 #-------------------------------------------------------------------------
810
809
811 def init_hooks(self):
810 def init_hooks(self):
812 # hooks holds pointers used for user-side customizations
811 # hooks holds pointers used for user-side customizations
813 self.hooks = Struct()
812 self.hooks = Struct()
814
813
815 self.strdispatchers = {}
814 self.strdispatchers = {}
816
815
817 # Set all default hooks, defined in the IPython.hooks module.
816 # Set all default hooks, defined in the IPython.hooks module.
818 hooks = IPython.core.hooks
817 hooks = IPython.core.hooks
819 for hook_name in hooks.__all__:
818 for hook_name in hooks.__all__:
820 # default hooks have priority 100, i.e. low; user hooks should have
819 # default hooks have priority 100, i.e. low; user hooks should have
821 # 0-100 priority
820 # 0-100 priority
822 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
821 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
823
822
824 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
823 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
825 _warn_deprecated=True):
824 _warn_deprecated=True):
826 """set_hook(name,hook) -> sets an internal IPython hook.
825 """set_hook(name,hook) -> sets an internal IPython hook.
827
826
828 IPython exposes some of its internal API as user-modifiable hooks. By
827 IPython exposes some of its internal API as user-modifiable hooks. By
829 adding your function to one of these hooks, you can modify IPython's
828 adding your function to one of these hooks, you can modify IPython's
830 behavior to call at runtime your own routines."""
829 behavior to call at runtime your own routines."""
831
830
832 # At some point in the future, this should validate the hook before it
831 # At some point in the future, this should validate the hook before it
833 # accepts it. Probably at least check that the hook takes the number
832 # accepts it. Probably at least check that the hook takes the number
834 # of args it's supposed to.
833 # of args it's supposed to.
835
834
836 f = types.MethodType(hook,self)
835 f = types.MethodType(hook,self)
837
836
838 # check if the hook is for strdispatcher first
837 # check if the hook is for strdispatcher first
839 if str_key is not None:
838 if str_key is not None:
840 sdp = self.strdispatchers.get(name, StrDispatch())
839 sdp = self.strdispatchers.get(name, StrDispatch())
841 sdp.add_s(str_key, f, priority )
840 sdp.add_s(str_key, f, priority )
842 self.strdispatchers[name] = sdp
841 self.strdispatchers[name] = sdp
843 return
842 return
844 if re_key is not None:
843 if re_key is not None:
845 sdp = self.strdispatchers.get(name, StrDispatch())
844 sdp = self.strdispatchers.get(name, StrDispatch())
846 sdp.add_re(re.compile(re_key), f, priority )
845 sdp.add_re(re.compile(re_key), f, priority )
847 self.strdispatchers[name] = sdp
846 self.strdispatchers[name] = sdp
848 return
847 return
849
848
850 dp = getattr(self.hooks, name, None)
849 dp = getattr(self.hooks, name, None)
851 if name not in IPython.core.hooks.__all__:
850 if name not in IPython.core.hooks.__all__:
852 print("Warning! Hook '%s' is not one of %s" % \
851 print("Warning! Hook '%s' is not one of %s" % \
853 (name, IPython.core.hooks.__all__ ))
852 (name, IPython.core.hooks.__all__ ))
854
853
855 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
854 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
856 alternative = IPython.core.hooks.deprecated[name]
855 alternative = IPython.core.hooks.deprecated[name]
857 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
856 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
858
857
859 if not dp:
858 if not dp:
860 dp = IPython.core.hooks.CommandChainDispatcher()
859 dp = IPython.core.hooks.CommandChainDispatcher()
861
860
862 try:
861 try:
863 dp.add(f,priority)
862 dp.add(f,priority)
864 except AttributeError:
863 except AttributeError:
865 # it was not commandchain, plain old func - replace
864 # it was not commandchain, plain old func - replace
866 dp = f
865 dp = f
867
866
868 setattr(self.hooks,name, dp)
867 setattr(self.hooks,name, dp)
869
868
870 #-------------------------------------------------------------------------
869 #-------------------------------------------------------------------------
871 # Things related to events
870 # Things related to events
872 #-------------------------------------------------------------------------
871 #-------------------------------------------------------------------------
873
872
874 def init_events(self):
873 def init_events(self):
875 self.events = EventManager(self, available_events)
874 self.events = EventManager(self, available_events)
876
875
877 def register_post_execute(self, func):
876 def register_post_execute(self, func):
878 """DEPRECATED: Use ip.events.register('post_run_cell', func)
877 """DEPRECATED: Use ip.events.register('post_run_cell', func)
879
878
880 Register a function for calling after code execution.
879 Register a function for calling after code execution.
881 """
880 """
882 warn("ip.register_post_execute is deprecated, use "
881 warn("ip.register_post_execute is deprecated, use "
883 "ip.events.register('post_run_cell', func) instead.")
882 "ip.events.register('post_run_cell', func) instead.")
884 self.events.register('post_run_cell', func)
883 self.events.register('post_run_cell', func)
885
884
886 #-------------------------------------------------------------------------
885 #-------------------------------------------------------------------------
887 # Things related to the "main" module
886 # Things related to the "main" module
888 #-------------------------------------------------------------------------
887 #-------------------------------------------------------------------------
889
888
890 def new_main_mod(self, filename, modname):
889 def new_main_mod(self, filename, modname):
891 """Return a new 'main' module object for user code execution.
890 """Return a new 'main' module object for user code execution.
892
891
893 ``filename`` should be the path of the script which will be run in the
892 ``filename`` should be the path of the script which will be run in the
894 module. Requests with the same filename will get the same module, with
893 module. Requests with the same filename will get the same module, with
895 its namespace cleared.
894 its namespace cleared.
896
895
897 ``modname`` should be the module name - normally either '__main__' or
896 ``modname`` should be the module name - normally either '__main__' or
898 the basename of the file without the extension.
897 the basename of the file without the extension.
899
898
900 When scripts are executed via %run, we must keep a reference to their
899 When scripts are executed via %run, we must keep a reference to their
901 __main__ module around so that Python doesn't
900 __main__ module around so that Python doesn't
902 clear it, rendering references to module globals useless.
901 clear it, rendering references to module globals useless.
903
902
904 This method keeps said reference in a private dict, keyed by the
903 This method keeps said reference in a private dict, keyed by the
905 absolute path of the script. This way, for multiple executions of the
904 absolute path of the script. This way, for multiple executions of the
906 same script we only keep one copy of the namespace (the last one),
905 same script we only keep one copy of the namespace (the last one),
907 thus preventing memory leaks from old references while allowing the
906 thus preventing memory leaks from old references while allowing the
908 objects from the last execution to be accessible.
907 objects from the last execution to be accessible.
909 """
908 """
910 filename = os.path.abspath(filename)
909 filename = os.path.abspath(filename)
911 try:
910 try:
912 main_mod = self._main_mod_cache[filename]
911 main_mod = self._main_mod_cache[filename]
913 except KeyError:
912 except KeyError:
914 main_mod = self._main_mod_cache[filename] = types.ModuleType(
913 main_mod = self._main_mod_cache[filename] = types.ModuleType(
915 py3compat.cast_bytes_py2(modname),
914 py3compat.cast_bytes_py2(modname),
916 doc="Module created for script run in IPython")
915 doc="Module created for script run in IPython")
917 else:
916 else:
918 main_mod.__dict__.clear()
917 main_mod.__dict__.clear()
919 main_mod.__name__ = modname
918 main_mod.__name__ = modname
920
919
921 main_mod.__file__ = filename
920 main_mod.__file__ = filename
922 # It seems pydoc (and perhaps others) needs any module instance to
921 # It seems pydoc (and perhaps others) needs any module instance to
923 # implement a __nonzero__ method
922 # implement a __nonzero__ method
924 main_mod.__nonzero__ = lambda : True
923 main_mod.__nonzero__ = lambda : True
925
924
926 return main_mod
925 return main_mod
927
926
928 def clear_main_mod_cache(self):
927 def clear_main_mod_cache(self):
929 """Clear the cache of main modules.
928 """Clear the cache of main modules.
930
929
931 Mainly for use by utilities like %reset.
930 Mainly for use by utilities like %reset.
932
931
933 Examples
932 Examples
934 --------
933 --------
935
934
936 In [15]: import IPython
935 In [15]: import IPython
937
936
938 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
937 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
939
938
940 In [17]: len(_ip._main_mod_cache) > 0
939 In [17]: len(_ip._main_mod_cache) > 0
941 Out[17]: True
940 Out[17]: True
942
941
943 In [18]: _ip.clear_main_mod_cache()
942 In [18]: _ip.clear_main_mod_cache()
944
943
945 In [19]: len(_ip._main_mod_cache) == 0
944 In [19]: len(_ip._main_mod_cache) == 0
946 Out[19]: True
945 Out[19]: True
947 """
946 """
948 self._main_mod_cache.clear()
947 self._main_mod_cache.clear()
949
948
950 #-------------------------------------------------------------------------
949 #-------------------------------------------------------------------------
951 # Things related to debugging
950 # Things related to debugging
952 #-------------------------------------------------------------------------
951 #-------------------------------------------------------------------------
953
952
954 def init_pdb(self):
953 def init_pdb(self):
955 # Set calling of pdb on exceptions
954 # Set calling of pdb on exceptions
956 # self.call_pdb is a property
955 # self.call_pdb is a property
957 self.call_pdb = self.pdb
956 self.call_pdb = self.pdb
958
957
959 def _get_call_pdb(self):
958 def _get_call_pdb(self):
960 return self._call_pdb
959 return self._call_pdb
961
960
962 def _set_call_pdb(self,val):
961 def _set_call_pdb(self,val):
963
962
964 if val not in (0,1,False,True):
963 if val not in (0,1,False,True):
965 raise ValueError('new call_pdb value must be boolean')
964 raise ValueError('new call_pdb value must be boolean')
966
965
967 # store value in instance
966 # store value in instance
968 self._call_pdb = val
967 self._call_pdb = val
969
968
970 # notify the actual exception handlers
969 # notify the actual exception handlers
971 self.InteractiveTB.call_pdb = val
970 self.InteractiveTB.call_pdb = val
972
971
973 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
972 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
974 'Control auto-activation of pdb at exceptions')
973 'Control auto-activation of pdb at exceptions')
975
974
976 def debugger(self,force=False):
975 def debugger(self,force=False):
977 """Call the pydb/pdb debugger.
976 """Call the pydb/pdb debugger.
978
977
979 Keywords:
978 Keywords:
980
979
981 - force(False): by default, this routine checks the instance call_pdb
980 - force(False): by default, this routine checks the instance call_pdb
982 flag and does not actually invoke the debugger if the flag is false.
981 flag and does not actually invoke the debugger if the flag is false.
983 The 'force' option forces the debugger to activate even if the flag
982 The 'force' option forces the debugger to activate even if the flag
984 is false.
983 is false.
985 """
984 """
986
985
987 if not (force or self.call_pdb):
986 if not (force or self.call_pdb):
988 return
987 return
989
988
990 if not hasattr(sys,'last_traceback'):
989 if not hasattr(sys,'last_traceback'):
991 error('No traceback has been produced, nothing to debug.')
990 error('No traceback has been produced, nothing to debug.')
992 return
991 return
993
992
994 # use pydb if available
993 # use pydb if available
995 if debugger.has_pydb:
994 if debugger.has_pydb:
996 from pydb import pm
995 from pydb import pm
997 else:
996 else:
998 # fallback to our internal debugger
997 # fallback to our internal debugger
999 pm = lambda : self.InteractiveTB.debugger(force=True)
998 pm = lambda : self.InteractiveTB.debugger(force=True)
1000
999
1001 with self.readline_no_record:
1000 with self.readline_no_record:
1002 pm()
1001 pm()
1003
1002
1004 #-------------------------------------------------------------------------
1003 #-------------------------------------------------------------------------
1005 # Things related to IPython's various namespaces
1004 # Things related to IPython's various namespaces
1006 #-------------------------------------------------------------------------
1005 #-------------------------------------------------------------------------
1007 default_user_namespaces = True
1006 default_user_namespaces = True
1008
1007
1009 def init_create_namespaces(self, user_module=None, user_ns=None):
1008 def init_create_namespaces(self, user_module=None, user_ns=None):
1010 # Create the namespace where the user will operate. user_ns is
1009 # Create the namespace where the user will operate. user_ns is
1011 # normally the only one used, and it is passed to the exec calls as
1010 # normally the only one used, and it is passed to the exec calls as
1012 # the locals argument. But we do carry a user_global_ns namespace
1011 # the locals argument. But we do carry a user_global_ns namespace
1013 # given as the exec 'globals' argument, This is useful in embedding
1012 # given as the exec 'globals' argument, This is useful in embedding
1014 # situations where the ipython shell opens in a context where the
1013 # situations where the ipython shell opens in a context where the
1015 # distinction between locals and globals is meaningful. For
1014 # distinction between locals and globals is meaningful. For
1016 # non-embedded contexts, it is just the same object as the user_ns dict.
1015 # non-embedded contexts, it is just the same object as the user_ns dict.
1017
1016
1018 # FIXME. For some strange reason, __builtins__ is showing up at user
1017 # FIXME. For some strange reason, __builtins__ is showing up at user
1019 # level as a dict instead of a module. This is a manual fix, but I
1018 # level as a dict instead of a module. This is a manual fix, but I
1020 # should really track down where the problem is coming from. Alex
1019 # should really track down where the problem is coming from. Alex
1021 # Schmolck reported this problem first.
1020 # Schmolck reported this problem first.
1022
1021
1023 # A useful post by Alex Martelli on this topic:
1022 # A useful post by Alex Martelli on this topic:
1024 # Re: inconsistent value from __builtins__
1023 # Re: inconsistent value from __builtins__
1025 # Von: Alex Martelli <aleaxit@yahoo.com>
1024 # Von: Alex Martelli <aleaxit@yahoo.com>
1026 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1025 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1027 # Gruppen: comp.lang.python
1026 # Gruppen: comp.lang.python
1028
1027
1029 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1028 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1030 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1029 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1031 # > <type 'dict'>
1030 # > <type 'dict'>
1032 # > >>> print type(__builtins__)
1031 # > >>> print type(__builtins__)
1033 # > <type 'module'>
1032 # > <type 'module'>
1034 # > Is this difference in return value intentional?
1033 # > Is this difference in return value intentional?
1035
1034
1036 # Well, it's documented that '__builtins__' can be either a dictionary
1035 # Well, it's documented that '__builtins__' can be either a dictionary
1037 # or a module, and it's been that way for a long time. Whether it's
1036 # or a module, and it's been that way for a long time. Whether it's
1038 # intentional (or sensible), I don't know. In any case, the idea is
1037 # intentional (or sensible), I don't know. In any case, the idea is
1039 # that if you need to access the built-in namespace directly, you
1038 # that if you need to access the built-in namespace directly, you
1040 # should start with "import __builtin__" (note, no 's') which will
1039 # should start with "import __builtin__" (note, no 's') which will
1041 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1040 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1042
1041
1043 # These routines return a properly built module and dict as needed by
1042 # These routines return a properly built module and dict as needed by
1044 # the rest of the code, and can also be used by extension writers to
1043 # the rest of the code, and can also be used by extension writers to
1045 # generate properly initialized namespaces.
1044 # generate properly initialized namespaces.
1046 if (user_ns is not None) or (user_module is not None):
1045 if (user_ns is not None) or (user_module is not None):
1047 self.default_user_namespaces = False
1046 self.default_user_namespaces = False
1048 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1047 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1049
1048
1050 # A record of hidden variables we have added to the user namespace, so
1049 # A record of hidden variables we have added to the user namespace, so
1051 # we can list later only variables defined in actual interactive use.
1050 # we can list later only variables defined in actual interactive use.
1052 self.user_ns_hidden = {}
1051 self.user_ns_hidden = {}
1053
1052
1054 # Now that FakeModule produces a real module, we've run into a nasty
1053 # Now that FakeModule produces a real module, we've run into a nasty
1055 # problem: after script execution (via %run), the module where the user
1054 # problem: after script execution (via %run), the module where the user
1056 # code ran is deleted. Now that this object is a true module (needed
1055 # code ran is deleted. Now that this object is a true module (needed
1057 # so docetst and other tools work correctly), the Python module
1056 # so docetst and other tools work correctly), the Python module
1058 # teardown mechanism runs over it, and sets to None every variable
1057 # teardown mechanism runs over it, and sets to None every variable
1059 # present in that module. Top-level references to objects from the
1058 # present in that module. Top-level references to objects from the
1060 # script survive, because the user_ns is updated with them. However,
1059 # script survive, because the user_ns is updated with them. However,
1061 # calling functions defined in the script that use other things from
1060 # calling functions defined in the script that use other things from
1062 # the script will fail, because the function's closure had references
1061 # the script will fail, because the function's closure had references
1063 # to the original objects, which are now all None. So we must protect
1062 # to the original objects, which are now all None. So we must protect
1064 # these modules from deletion by keeping a cache.
1063 # these modules from deletion by keeping a cache.
1065 #
1064 #
1066 # To avoid keeping stale modules around (we only need the one from the
1065 # To avoid keeping stale modules around (we only need the one from the
1067 # last run), we use a dict keyed with the full path to the script, so
1066 # last run), we use a dict keyed with the full path to the script, so
1068 # only the last version of the module is held in the cache. Note,
1067 # only the last version of the module is held in the cache. Note,
1069 # however, that we must cache the module *namespace contents* (their
1068 # however, that we must cache the module *namespace contents* (their
1070 # __dict__). Because if we try to cache the actual modules, old ones
1069 # __dict__). Because if we try to cache the actual modules, old ones
1071 # (uncached) could be destroyed while still holding references (such as
1070 # (uncached) could be destroyed while still holding references (such as
1072 # those held by GUI objects that tend to be long-lived)>
1071 # those held by GUI objects that tend to be long-lived)>
1073 #
1072 #
1074 # The %reset command will flush this cache. See the cache_main_mod()
1073 # The %reset command will flush this cache. See the cache_main_mod()
1075 # and clear_main_mod_cache() methods for details on use.
1074 # and clear_main_mod_cache() methods for details on use.
1076
1075
1077 # This is the cache used for 'main' namespaces
1076 # This is the cache used for 'main' namespaces
1078 self._main_mod_cache = {}
1077 self._main_mod_cache = {}
1079
1078
1080 # A table holding all the namespaces IPython deals with, so that
1079 # A table holding all the namespaces IPython deals with, so that
1081 # introspection facilities can search easily.
1080 # introspection facilities can search easily.
1082 self.ns_table = {'user_global':self.user_module.__dict__,
1081 self.ns_table = {'user_global':self.user_module.__dict__,
1083 'user_local':self.user_ns,
1082 'user_local':self.user_ns,
1084 'builtin':builtin_mod.__dict__
1083 'builtin':builtin_mod.__dict__
1085 }
1084 }
1086
1085
1087 @property
1086 @property
1088 def user_global_ns(self):
1087 def user_global_ns(self):
1089 return self.user_module.__dict__
1088 return self.user_module.__dict__
1090
1089
1091 def prepare_user_module(self, user_module=None, user_ns=None):
1090 def prepare_user_module(self, user_module=None, user_ns=None):
1092 """Prepare the module and namespace in which user code will be run.
1091 """Prepare the module and namespace in which user code will be run.
1093
1092
1094 When IPython is started normally, both parameters are None: a new module
1093 When IPython is started normally, both parameters are None: a new module
1095 is created automatically, and its __dict__ used as the namespace.
1094 is created automatically, and its __dict__ used as the namespace.
1096
1095
1097 If only user_module is provided, its __dict__ is used as the namespace.
1096 If only user_module is provided, its __dict__ is used as the namespace.
1098 If only user_ns is provided, a dummy module is created, and user_ns
1097 If only user_ns is provided, a dummy module is created, and user_ns
1099 becomes the global namespace. If both are provided (as they may be
1098 becomes the global namespace. If both are provided (as they may be
1100 when embedding), user_ns is the local namespace, and user_module
1099 when embedding), user_ns is the local namespace, and user_module
1101 provides the global namespace.
1100 provides the global namespace.
1102
1101
1103 Parameters
1102 Parameters
1104 ----------
1103 ----------
1105 user_module : module, optional
1104 user_module : module, optional
1106 The current user module in which IPython is being run. If None,
1105 The current user module in which IPython is being run. If None,
1107 a clean module will be created.
1106 a clean module will be created.
1108 user_ns : dict, optional
1107 user_ns : dict, optional
1109 A namespace in which to run interactive commands.
1108 A namespace in which to run interactive commands.
1110
1109
1111 Returns
1110 Returns
1112 -------
1111 -------
1113 A tuple of user_module and user_ns, each properly initialised.
1112 A tuple of user_module and user_ns, each properly initialised.
1114 """
1113 """
1115 if user_module is None and user_ns is not None:
1114 if user_module is None and user_ns is not None:
1116 user_ns.setdefault("__name__", "__main__")
1115 user_ns.setdefault("__name__", "__main__")
1117 user_module = DummyMod()
1116 user_module = DummyMod()
1118 user_module.__dict__ = user_ns
1117 user_module.__dict__ = user_ns
1119
1118
1120 if user_module is None:
1119 if user_module is None:
1121 user_module = types.ModuleType("__main__",
1120 user_module = types.ModuleType("__main__",
1122 doc="Automatically created module for IPython interactive environment")
1121 doc="Automatically created module for IPython interactive environment")
1123
1122
1124 # We must ensure that __builtin__ (without the final 's') is always
1123 # We must ensure that __builtin__ (without the final 's') is always
1125 # available and pointing to the __builtin__ *module*. For more details:
1124 # available and pointing to the __builtin__ *module*. For more details:
1126 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1125 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1127 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1126 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1128 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1127 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1129
1128
1130 if user_ns is None:
1129 if user_ns is None:
1131 user_ns = user_module.__dict__
1130 user_ns = user_module.__dict__
1132
1131
1133 return user_module, user_ns
1132 return user_module, user_ns
1134
1133
1135 def init_sys_modules(self):
1134 def init_sys_modules(self):
1136 # We need to insert into sys.modules something that looks like a
1135 # We need to insert into sys.modules something that looks like a
1137 # module but which accesses the IPython namespace, for shelve and
1136 # module but which accesses the IPython namespace, for shelve and
1138 # pickle to work interactively. Normally they rely on getting
1137 # pickle to work interactively. Normally they rely on getting
1139 # everything out of __main__, but for embedding purposes each IPython
1138 # everything out of __main__, but for embedding purposes each IPython
1140 # instance has its own private namespace, so we can't go shoving
1139 # instance has its own private namespace, so we can't go shoving
1141 # everything into __main__.
1140 # everything into __main__.
1142
1141
1143 # note, however, that we should only do this for non-embedded
1142 # note, however, that we should only do this for non-embedded
1144 # ipythons, which really mimic the __main__.__dict__ with their own
1143 # ipythons, which really mimic the __main__.__dict__ with their own
1145 # namespace. Embedded instances, on the other hand, should not do
1144 # namespace. Embedded instances, on the other hand, should not do
1146 # this because they need to manage the user local/global namespaces
1145 # this because they need to manage the user local/global namespaces
1147 # only, but they live within a 'normal' __main__ (meaning, they
1146 # only, but they live within a 'normal' __main__ (meaning, they
1148 # shouldn't overtake the execution environment of the script they're
1147 # shouldn't overtake the execution environment of the script they're
1149 # embedded in).
1148 # embedded in).
1150
1149
1151 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1150 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1152 main_name = self.user_module.__name__
1151 main_name = self.user_module.__name__
1153 sys.modules[main_name] = self.user_module
1152 sys.modules[main_name] = self.user_module
1154
1153
1155 def init_user_ns(self):
1154 def init_user_ns(self):
1156 """Initialize all user-visible namespaces to their minimum defaults.
1155 """Initialize all user-visible namespaces to their minimum defaults.
1157
1156
1158 Certain history lists are also initialized here, as they effectively
1157 Certain history lists are also initialized here, as they effectively
1159 act as user namespaces.
1158 act as user namespaces.
1160
1159
1161 Notes
1160 Notes
1162 -----
1161 -----
1163 All data structures here are only filled in, they are NOT reset by this
1162 All data structures here are only filled in, they are NOT reset by this
1164 method. If they were not empty before, data will simply be added to
1163 method. If they were not empty before, data will simply be added to
1165 therm.
1164 therm.
1166 """
1165 """
1167 # This function works in two parts: first we put a few things in
1166 # This function works in two parts: first we put a few things in
1168 # user_ns, and we sync that contents into user_ns_hidden so that these
1167 # user_ns, and we sync that contents into user_ns_hidden so that these
1169 # initial variables aren't shown by %who. After the sync, we add the
1168 # initial variables aren't shown by %who. After the sync, we add the
1170 # rest of what we *do* want the user to see with %who even on a new
1169 # rest of what we *do* want the user to see with %who even on a new
1171 # session (probably nothing, so theye really only see their own stuff)
1170 # session (probably nothing, so theye really only see their own stuff)
1172
1171
1173 # The user dict must *always* have a __builtin__ reference to the
1172 # The user dict must *always* have a __builtin__ reference to the
1174 # Python standard __builtin__ namespace, which must be imported.
1173 # Python standard __builtin__ namespace, which must be imported.
1175 # This is so that certain operations in prompt evaluation can be
1174 # This is so that certain operations in prompt evaluation can be
1176 # reliably executed with builtins. Note that we can NOT use
1175 # reliably executed with builtins. Note that we can NOT use
1177 # __builtins__ (note the 's'), because that can either be a dict or a
1176 # __builtins__ (note the 's'), because that can either be a dict or a
1178 # module, and can even mutate at runtime, depending on the context
1177 # module, and can even mutate at runtime, depending on the context
1179 # (Python makes no guarantees on it). In contrast, __builtin__ is
1178 # (Python makes no guarantees on it). In contrast, __builtin__ is
1180 # always a module object, though it must be explicitly imported.
1179 # always a module object, though it must be explicitly imported.
1181
1180
1182 # For more details:
1181 # For more details:
1183 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1182 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1184 ns = dict()
1183 ns = dict()
1185
1184
1186 # make global variables for user access to the histories
1185 # make global variables for user access to the histories
1187 ns['_ih'] = self.history_manager.input_hist_parsed
1186 ns['_ih'] = self.history_manager.input_hist_parsed
1188 ns['_oh'] = self.history_manager.output_hist
1187 ns['_oh'] = self.history_manager.output_hist
1189 ns['_dh'] = self.history_manager.dir_hist
1188 ns['_dh'] = self.history_manager.dir_hist
1190
1189
1191 ns['_sh'] = shadowns
1190 ns['_sh'] = shadowns
1192
1191
1193 # user aliases to input and output histories. These shouldn't show up
1192 # user aliases to input and output histories. These shouldn't show up
1194 # in %who, as they can have very large reprs.
1193 # in %who, as they can have very large reprs.
1195 ns['In'] = self.history_manager.input_hist_parsed
1194 ns['In'] = self.history_manager.input_hist_parsed
1196 ns['Out'] = self.history_manager.output_hist
1195 ns['Out'] = self.history_manager.output_hist
1197
1196
1198 # Store myself as the public api!!!
1197 # Store myself as the public api!!!
1199 ns['get_ipython'] = self.get_ipython
1198 ns['get_ipython'] = self.get_ipython
1200
1199
1201 ns['exit'] = self.exiter
1200 ns['exit'] = self.exiter
1202 ns['quit'] = self.exiter
1201 ns['quit'] = self.exiter
1203
1202
1204 # Sync what we've added so far to user_ns_hidden so these aren't seen
1203 # Sync what we've added so far to user_ns_hidden so these aren't seen
1205 # by %who
1204 # by %who
1206 self.user_ns_hidden.update(ns)
1205 self.user_ns_hidden.update(ns)
1207
1206
1208 # Anything put into ns now would show up in %who. Think twice before
1207 # Anything put into ns now would show up in %who. Think twice before
1209 # putting anything here, as we really want %who to show the user their
1208 # putting anything here, as we really want %who to show the user their
1210 # stuff, not our variables.
1209 # stuff, not our variables.
1211
1210
1212 # Finally, update the real user's namespace
1211 # Finally, update the real user's namespace
1213 self.user_ns.update(ns)
1212 self.user_ns.update(ns)
1214
1213
1215 @property
1214 @property
1216 def all_ns_refs(self):
1215 def all_ns_refs(self):
1217 """Get a list of references to all the namespace dictionaries in which
1216 """Get a list of references to all the namespace dictionaries in which
1218 IPython might store a user-created object.
1217 IPython might store a user-created object.
1219
1218
1220 Note that this does not include the displayhook, which also caches
1219 Note that this does not include the displayhook, which also caches
1221 objects from the output."""
1220 objects from the output."""
1222 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1221 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1223 [m.__dict__ for m in self._main_mod_cache.values()]
1222 [m.__dict__ for m in self._main_mod_cache.values()]
1224
1223
1225 def reset(self, new_session=True):
1224 def reset(self, new_session=True):
1226 """Clear all internal namespaces, and attempt to release references to
1225 """Clear all internal namespaces, and attempt to release references to
1227 user objects.
1226 user objects.
1228
1227
1229 If new_session is True, a new history session will be opened.
1228 If new_session is True, a new history session will be opened.
1230 """
1229 """
1231 # Clear histories
1230 # Clear histories
1232 self.history_manager.reset(new_session)
1231 self.history_manager.reset(new_session)
1233 # Reset counter used to index all histories
1232 # Reset counter used to index all histories
1234 if new_session:
1233 if new_session:
1235 self.execution_count = 1
1234 self.execution_count = 1
1236
1235
1237 # Flush cached output items
1236 # Flush cached output items
1238 if self.displayhook.do_full_cache:
1237 if self.displayhook.do_full_cache:
1239 self.displayhook.flush()
1238 self.displayhook.flush()
1240
1239
1241 # The main execution namespaces must be cleared very carefully,
1240 # The main execution namespaces must be cleared very carefully,
1242 # skipping the deletion of the builtin-related keys, because doing so
1241 # skipping the deletion of the builtin-related keys, because doing so
1243 # would cause errors in many object's __del__ methods.
1242 # would cause errors in many object's __del__ methods.
1244 if self.user_ns is not self.user_global_ns:
1243 if self.user_ns is not self.user_global_ns:
1245 self.user_ns.clear()
1244 self.user_ns.clear()
1246 ns = self.user_global_ns
1245 ns = self.user_global_ns
1247 drop_keys = set(ns.keys())
1246 drop_keys = set(ns.keys())
1248 drop_keys.discard('__builtin__')
1247 drop_keys.discard('__builtin__')
1249 drop_keys.discard('__builtins__')
1248 drop_keys.discard('__builtins__')
1250 drop_keys.discard('__name__')
1249 drop_keys.discard('__name__')
1251 for k in drop_keys:
1250 for k in drop_keys:
1252 del ns[k]
1251 del ns[k]
1253
1252
1254 self.user_ns_hidden.clear()
1253 self.user_ns_hidden.clear()
1255
1254
1256 # Restore the user namespaces to minimal usability
1255 # Restore the user namespaces to minimal usability
1257 self.init_user_ns()
1256 self.init_user_ns()
1258
1257
1259 # Restore the default and user aliases
1258 # Restore the default and user aliases
1260 self.alias_manager.clear_aliases()
1259 self.alias_manager.clear_aliases()
1261 self.alias_manager.init_aliases()
1260 self.alias_manager.init_aliases()
1262
1261
1263 # Flush the private list of module references kept for script
1262 # Flush the private list of module references kept for script
1264 # execution protection
1263 # execution protection
1265 self.clear_main_mod_cache()
1264 self.clear_main_mod_cache()
1266
1265
1267 def del_var(self, varname, by_name=False):
1266 def del_var(self, varname, by_name=False):
1268 """Delete a variable from the various namespaces, so that, as
1267 """Delete a variable from the various namespaces, so that, as
1269 far as possible, we're not keeping any hidden references to it.
1268 far as possible, we're not keeping any hidden references to it.
1270
1269
1271 Parameters
1270 Parameters
1272 ----------
1271 ----------
1273 varname : str
1272 varname : str
1274 The name of the variable to delete.
1273 The name of the variable to delete.
1275 by_name : bool
1274 by_name : bool
1276 If True, delete variables with the given name in each
1275 If True, delete variables with the given name in each
1277 namespace. If False (default), find the variable in the user
1276 namespace. If False (default), find the variable in the user
1278 namespace, and delete references to it.
1277 namespace, and delete references to it.
1279 """
1278 """
1280 if varname in ('__builtin__', '__builtins__'):
1279 if varname in ('__builtin__', '__builtins__'):
1281 raise ValueError("Refusing to delete %s" % varname)
1280 raise ValueError("Refusing to delete %s" % varname)
1282
1281
1283 ns_refs = self.all_ns_refs
1282 ns_refs = self.all_ns_refs
1284
1283
1285 if by_name: # Delete by name
1284 if by_name: # Delete by name
1286 for ns in ns_refs:
1285 for ns in ns_refs:
1287 try:
1286 try:
1288 del ns[varname]
1287 del ns[varname]
1289 except KeyError:
1288 except KeyError:
1290 pass
1289 pass
1291 else: # Delete by object
1290 else: # Delete by object
1292 try:
1291 try:
1293 obj = self.user_ns[varname]
1292 obj = self.user_ns[varname]
1294 except KeyError:
1293 except KeyError:
1295 raise NameError("name '%s' is not defined" % varname)
1294 raise NameError("name '%s' is not defined" % varname)
1296 # Also check in output history
1295 # Also check in output history
1297 ns_refs.append(self.history_manager.output_hist)
1296 ns_refs.append(self.history_manager.output_hist)
1298 for ns in ns_refs:
1297 for ns in ns_refs:
1299 to_delete = [n for n, o in iteritems(ns) if o is obj]
1298 to_delete = [n for n, o in iteritems(ns) if o is obj]
1300 for name in to_delete:
1299 for name in to_delete:
1301 del ns[name]
1300 del ns[name]
1302
1301
1303 # displayhook keeps extra references, but not in a dictionary
1302 # displayhook keeps extra references, but not in a dictionary
1304 for name in ('_', '__', '___'):
1303 for name in ('_', '__', '___'):
1305 if getattr(self.displayhook, name) is obj:
1304 if getattr(self.displayhook, name) is obj:
1306 setattr(self.displayhook, name, None)
1305 setattr(self.displayhook, name, None)
1307
1306
1308 def reset_selective(self, regex=None):
1307 def reset_selective(self, regex=None):
1309 """Clear selective variables from internal namespaces based on a
1308 """Clear selective variables from internal namespaces based on a
1310 specified regular expression.
1309 specified regular expression.
1311
1310
1312 Parameters
1311 Parameters
1313 ----------
1312 ----------
1314 regex : string or compiled pattern, optional
1313 regex : string or compiled pattern, optional
1315 A regular expression pattern that will be used in searching
1314 A regular expression pattern that will be used in searching
1316 variable names in the users namespaces.
1315 variable names in the users namespaces.
1317 """
1316 """
1318 if regex is not None:
1317 if regex is not None:
1319 try:
1318 try:
1320 m = re.compile(regex)
1319 m = re.compile(regex)
1321 except TypeError:
1320 except TypeError:
1322 raise TypeError('regex must be a string or compiled pattern')
1321 raise TypeError('regex must be a string or compiled pattern')
1323 # Search for keys in each namespace that match the given regex
1322 # Search for keys in each namespace that match the given regex
1324 # If a match is found, delete the key/value pair.
1323 # If a match is found, delete the key/value pair.
1325 for ns in self.all_ns_refs:
1324 for ns in self.all_ns_refs:
1326 for var in ns:
1325 for var in ns:
1327 if m.search(var):
1326 if m.search(var):
1328 del ns[var]
1327 del ns[var]
1329
1328
1330 def push(self, variables, interactive=True):
1329 def push(self, variables, interactive=True):
1331 """Inject a group of variables into the IPython user namespace.
1330 """Inject a group of variables into the IPython user namespace.
1332
1331
1333 Parameters
1332 Parameters
1334 ----------
1333 ----------
1335 variables : dict, str or list/tuple of str
1334 variables : dict, str or list/tuple of str
1336 The variables to inject into the user's namespace. If a dict, a
1335 The variables to inject into the user's namespace. If a dict, a
1337 simple update is done. If a str, the string is assumed to have
1336 simple update is done. If a str, the string is assumed to have
1338 variable names separated by spaces. A list/tuple of str can also
1337 variable names separated by spaces. A list/tuple of str can also
1339 be used to give the variable names. If just the variable names are
1338 be used to give the variable names. If just the variable names are
1340 give (list/tuple/str) then the variable values looked up in the
1339 give (list/tuple/str) then the variable values looked up in the
1341 callers frame.
1340 callers frame.
1342 interactive : bool
1341 interactive : bool
1343 If True (default), the variables will be listed with the ``who``
1342 If True (default), the variables will be listed with the ``who``
1344 magic.
1343 magic.
1345 """
1344 """
1346 vdict = None
1345 vdict = None
1347
1346
1348 # We need a dict of name/value pairs to do namespace updates.
1347 # We need a dict of name/value pairs to do namespace updates.
1349 if isinstance(variables, dict):
1348 if isinstance(variables, dict):
1350 vdict = variables
1349 vdict = variables
1351 elif isinstance(variables, string_types+(list, tuple)):
1350 elif isinstance(variables, string_types+(list, tuple)):
1352 if isinstance(variables, string_types):
1351 if isinstance(variables, string_types):
1353 vlist = variables.split()
1352 vlist = variables.split()
1354 else:
1353 else:
1355 vlist = variables
1354 vlist = variables
1356 vdict = {}
1355 vdict = {}
1357 cf = sys._getframe(1)
1356 cf = sys._getframe(1)
1358 for name in vlist:
1357 for name in vlist:
1359 try:
1358 try:
1360 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1359 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1361 except:
1360 except:
1362 print('Could not get variable %s from %s' %
1361 print('Could not get variable %s from %s' %
1363 (name,cf.f_code.co_name))
1362 (name,cf.f_code.co_name))
1364 else:
1363 else:
1365 raise ValueError('variables must be a dict/str/list/tuple')
1364 raise ValueError('variables must be a dict/str/list/tuple')
1366
1365
1367 # Propagate variables to user namespace
1366 # Propagate variables to user namespace
1368 self.user_ns.update(vdict)
1367 self.user_ns.update(vdict)
1369
1368
1370 # And configure interactive visibility
1369 # And configure interactive visibility
1371 user_ns_hidden = self.user_ns_hidden
1370 user_ns_hidden = self.user_ns_hidden
1372 if interactive:
1371 if interactive:
1373 for name in vdict:
1372 for name in vdict:
1374 user_ns_hidden.pop(name, None)
1373 user_ns_hidden.pop(name, None)
1375 else:
1374 else:
1376 user_ns_hidden.update(vdict)
1375 user_ns_hidden.update(vdict)
1377
1376
1378 def drop_by_id(self, variables):
1377 def drop_by_id(self, variables):
1379 """Remove a dict of variables from the user namespace, if they are the
1378 """Remove a dict of variables from the user namespace, if they are the
1380 same as the values in the dictionary.
1379 same as the values in the dictionary.
1381
1380
1382 This is intended for use by extensions: variables that they've added can
1381 This is intended for use by extensions: variables that they've added can
1383 be taken back out if they are unloaded, without removing any that the
1382 be taken back out if they are unloaded, without removing any that the
1384 user has overwritten.
1383 user has overwritten.
1385
1384
1386 Parameters
1385 Parameters
1387 ----------
1386 ----------
1388 variables : dict
1387 variables : dict
1389 A dictionary mapping object names (as strings) to the objects.
1388 A dictionary mapping object names (as strings) to the objects.
1390 """
1389 """
1391 for name, obj in iteritems(variables):
1390 for name, obj in iteritems(variables):
1392 if name in self.user_ns and self.user_ns[name] is obj:
1391 if name in self.user_ns and self.user_ns[name] is obj:
1393 del self.user_ns[name]
1392 del self.user_ns[name]
1394 self.user_ns_hidden.pop(name, None)
1393 self.user_ns_hidden.pop(name, None)
1395
1394
1396 #-------------------------------------------------------------------------
1395 #-------------------------------------------------------------------------
1397 # Things related to object introspection
1396 # Things related to object introspection
1398 #-------------------------------------------------------------------------
1397 #-------------------------------------------------------------------------
1399
1398
1400 def _ofind(self, oname, namespaces=None):
1399 def _ofind(self, oname, namespaces=None):
1401 """Find an object in the available namespaces.
1400 """Find an object in the available namespaces.
1402
1401
1403 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1402 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1404
1403
1405 Has special code to detect magic functions.
1404 Has special code to detect magic functions.
1406 """
1405 """
1407 oname = oname.strip()
1406 oname = oname.strip()
1408 #print '1- oname: <%r>' % oname # dbg
1407 #print '1- oname: <%r>' % oname # dbg
1409 if not oname.startswith(ESC_MAGIC) and \
1408 if not oname.startswith(ESC_MAGIC) and \
1410 not oname.startswith(ESC_MAGIC2) and \
1409 not oname.startswith(ESC_MAGIC2) and \
1411 not py3compat.isidentifier(oname, dotted=True):
1410 not py3compat.isidentifier(oname, dotted=True):
1412 return dict(found=False)
1411 return dict(found=False)
1413
1412
1414 alias_ns = None
1413 alias_ns = None
1415 if namespaces is None:
1414 if namespaces is None:
1416 # Namespaces to search in:
1415 # Namespaces to search in:
1417 # Put them in a list. The order is important so that we
1416 # Put them in a list. The order is important so that we
1418 # find things in the same order that Python finds them.
1417 # find things in the same order that Python finds them.
1419 namespaces = [ ('Interactive', self.user_ns),
1418 namespaces = [ ('Interactive', self.user_ns),
1420 ('Interactive (global)', self.user_global_ns),
1419 ('Interactive (global)', self.user_global_ns),
1421 ('Python builtin', builtin_mod.__dict__),
1420 ('Python builtin', builtin_mod.__dict__),
1422 ]
1421 ]
1423
1422
1424 # initialize results to 'null'
1423 # initialize results to 'null'
1425 found = False; obj = None; ospace = None; ds = None;
1424 found = False; obj = None; ospace = None; ds = None;
1426 ismagic = False; isalias = False; parent = None
1425 ismagic = False; isalias = False; parent = None
1427
1426
1428 # We need to special-case 'print', which as of python2.6 registers as a
1427 # We need to special-case 'print', which as of python2.6 registers as a
1429 # function but should only be treated as one if print_function was
1428 # function but should only be treated as one if print_function was
1430 # loaded with a future import. In this case, just bail.
1429 # loaded with a future import. In this case, just bail.
1431 if (oname == 'print' and not py3compat.PY3 and not \
1430 if (oname == 'print' and not py3compat.PY3 and not \
1432 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1431 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1433 return {'found':found, 'obj':obj, 'namespace':ospace,
1432 return {'found':found, 'obj':obj, 'namespace':ospace,
1434 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1433 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1435
1434
1436 # Look for the given name by splitting it in parts. If the head is
1435 # Look for the given name by splitting it in parts. If the head is
1437 # found, then we look for all the remaining parts as members, and only
1436 # found, then we look for all the remaining parts as members, and only
1438 # declare success if we can find them all.
1437 # declare success if we can find them all.
1439 oname_parts = oname.split('.')
1438 oname_parts = oname.split('.')
1440 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1439 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1441 for nsname,ns in namespaces:
1440 for nsname,ns in namespaces:
1442 try:
1441 try:
1443 obj = ns[oname_head]
1442 obj = ns[oname_head]
1444 except KeyError:
1443 except KeyError:
1445 continue
1444 continue
1446 else:
1445 else:
1447 #print 'oname_rest:', oname_rest # dbg
1446 #print 'oname_rest:', oname_rest # dbg
1448 for idx, part in enumerate(oname_rest):
1447 for idx, part in enumerate(oname_rest):
1449 try:
1448 try:
1450 parent = obj
1449 parent = obj
1451 # The last part is looked up in a special way to avoid
1450 # The last part is looked up in a special way to avoid
1452 # descriptor invocation as it may raise or have side
1451 # descriptor invocation as it may raise or have side
1453 # effects.
1452 # effects.
1454 if idx == len(oname_rest) - 1:
1453 if idx == len(oname_rest) - 1:
1455 obj = self._getattr_property(obj, part)
1454 obj = self._getattr_property(obj, part)
1456 else:
1455 else:
1457 obj = getattr(obj, part)
1456 obj = getattr(obj, part)
1458 except:
1457 except:
1459 # Blanket except b/c some badly implemented objects
1458 # Blanket except b/c some badly implemented objects
1460 # allow __getattr__ to raise exceptions other than
1459 # allow __getattr__ to raise exceptions other than
1461 # AttributeError, which then crashes IPython.
1460 # AttributeError, which then crashes IPython.
1462 break
1461 break
1463 else:
1462 else:
1464 # If we finish the for loop (no break), we got all members
1463 # If we finish the for loop (no break), we got all members
1465 found = True
1464 found = True
1466 ospace = nsname
1465 ospace = nsname
1467 break # namespace loop
1466 break # namespace loop
1468
1467
1469 # Try to see if it's magic
1468 # Try to see if it's magic
1470 if not found:
1469 if not found:
1471 obj = None
1470 obj = None
1472 if oname.startswith(ESC_MAGIC2):
1471 if oname.startswith(ESC_MAGIC2):
1473 oname = oname.lstrip(ESC_MAGIC2)
1472 oname = oname.lstrip(ESC_MAGIC2)
1474 obj = self.find_cell_magic(oname)
1473 obj = self.find_cell_magic(oname)
1475 elif oname.startswith(ESC_MAGIC):
1474 elif oname.startswith(ESC_MAGIC):
1476 oname = oname.lstrip(ESC_MAGIC)
1475 oname = oname.lstrip(ESC_MAGIC)
1477 obj = self.find_line_magic(oname)
1476 obj = self.find_line_magic(oname)
1478 else:
1477 else:
1479 # search without prefix, so run? will find %run?
1478 # search without prefix, so run? will find %run?
1480 obj = self.find_line_magic(oname)
1479 obj = self.find_line_magic(oname)
1481 if obj is None:
1480 if obj is None:
1482 obj = self.find_cell_magic(oname)
1481 obj = self.find_cell_magic(oname)
1483 if obj is not None:
1482 if obj is not None:
1484 found = True
1483 found = True
1485 ospace = 'IPython internal'
1484 ospace = 'IPython internal'
1486 ismagic = True
1485 ismagic = True
1487
1486
1488 # Last try: special-case some literals like '', [], {}, etc:
1487 # Last try: special-case some literals like '', [], {}, etc:
1489 if not found and oname_head in ["''",'""','[]','{}','()']:
1488 if not found and oname_head in ["''",'""','[]','{}','()']:
1490 obj = eval(oname_head)
1489 obj = eval(oname_head)
1491 found = True
1490 found = True
1492 ospace = 'Interactive'
1491 ospace = 'Interactive'
1493
1492
1494 return {'found':found, 'obj':obj, 'namespace':ospace,
1493 return {'found':found, 'obj':obj, 'namespace':ospace,
1495 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1494 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1496
1495
1497 @staticmethod
1496 @staticmethod
1498 def _getattr_property(obj, attrname):
1497 def _getattr_property(obj, attrname):
1499 """Property-aware getattr to use in object finding.
1498 """Property-aware getattr to use in object finding.
1500
1499
1501 If attrname represents a property, return it unevaluated (in case it has
1500 If attrname represents a property, return it unevaluated (in case it has
1502 side effects or raises an error.
1501 side effects or raises an error.
1503
1502
1504 """
1503 """
1505 if not isinstance(obj, type):
1504 if not isinstance(obj, type):
1506 try:
1505 try:
1507 # `getattr(type(obj), attrname)` is not guaranteed to return
1506 # `getattr(type(obj), attrname)` is not guaranteed to return
1508 # `obj`, but does so for property:
1507 # `obj`, but does so for property:
1509 #
1508 #
1510 # property.__get__(self, None, cls) -> self
1509 # property.__get__(self, None, cls) -> self
1511 #
1510 #
1512 # The universal alternative is to traverse the mro manually
1511 # The universal alternative is to traverse the mro manually
1513 # searching for attrname in class dicts.
1512 # searching for attrname in class dicts.
1514 attr = getattr(type(obj), attrname)
1513 attr = getattr(type(obj), attrname)
1515 except AttributeError:
1514 except AttributeError:
1516 pass
1515 pass
1517 else:
1516 else:
1518 # This relies on the fact that data descriptors (with both
1517 # This relies on the fact that data descriptors (with both
1519 # __get__ & __set__ magic methods) take precedence over
1518 # __get__ & __set__ magic methods) take precedence over
1520 # instance-level attributes:
1519 # instance-level attributes:
1521 #
1520 #
1522 # class A(object):
1521 # class A(object):
1523 # @property
1522 # @property
1524 # def foobar(self): return 123
1523 # def foobar(self): return 123
1525 # a = A()
1524 # a = A()
1526 # a.__dict__['foobar'] = 345
1525 # a.__dict__['foobar'] = 345
1527 # a.foobar # == 123
1526 # a.foobar # == 123
1528 #
1527 #
1529 # So, a property may be returned right away.
1528 # So, a property may be returned right away.
1530 if isinstance(attr, property):
1529 if isinstance(attr, property):
1531 return attr
1530 return attr
1532
1531
1533 # Nothing helped, fall back.
1532 # Nothing helped, fall back.
1534 return getattr(obj, attrname)
1533 return getattr(obj, attrname)
1535
1534
1536 def _object_find(self, oname, namespaces=None):
1535 def _object_find(self, oname, namespaces=None):
1537 """Find an object and return a struct with info about it."""
1536 """Find an object and return a struct with info about it."""
1538 return Struct(self._ofind(oname, namespaces))
1537 return Struct(self._ofind(oname, namespaces))
1539
1538
1540 def _inspect(self, meth, oname, namespaces=None, **kw):
1539 def _inspect(self, meth, oname, namespaces=None, **kw):
1541 """Generic interface to the inspector system.
1540 """Generic interface to the inspector system.
1542
1541
1543 This function is meant to be called by pdef, pdoc & friends."""
1542 This function is meant to be called by pdef, pdoc & friends."""
1544 info = self._object_find(oname, namespaces)
1543 info = self._object_find(oname, namespaces)
1545 if info.found:
1544 if info.found:
1546 pmethod = getattr(self.inspector, meth)
1545 pmethod = getattr(self.inspector, meth)
1547 formatter = format_screen if info.ismagic else None
1546 formatter = format_screen if info.ismagic else None
1548 if meth == 'pdoc':
1547 if meth == 'pdoc':
1549 pmethod(info.obj, oname, formatter)
1548 pmethod(info.obj, oname, formatter)
1550 elif meth == 'pinfo':
1549 elif meth == 'pinfo':
1551 pmethod(info.obj, oname, formatter, info, **kw)
1550 pmethod(info.obj, oname, formatter, info, **kw)
1552 else:
1551 else:
1553 pmethod(info.obj, oname)
1552 pmethod(info.obj, oname)
1554 else:
1553 else:
1555 print('Object `%s` not found.' % oname)
1554 print('Object `%s` not found.' % oname)
1556 return 'not found' # so callers can take other action
1555 return 'not found' # so callers can take other action
1557
1556
1558 def object_inspect(self, oname, detail_level=0):
1557 def object_inspect(self, oname, detail_level=0):
1559 """Get object info about oname"""
1558 """Get object info about oname"""
1560 with self.builtin_trap:
1559 with self.builtin_trap:
1561 info = self._object_find(oname)
1560 info = self._object_find(oname)
1562 if info.found:
1561 if info.found:
1563 return self.inspector.info(info.obj, oname, info=info,
1562 return self.inspector.info(info.obj, oname, info=info,
1564 detail_level=detail_level
1563 detail_level=detail_level
1565 )
1564 )
1566 else:
1565 else:
1567 return oinspect.object_info(name=oname, found=False)
1566 return oinspect.object_info(name=oname, found=False)
1568
1567
1569 def object_inspect_text(self, oname, detail_level=0):
1568 def object_inspect_text(self, oname, detail_level=0):
1570 """Get object info as formatted text"""
1569 """Get object info as formatted text"""
1571 with self.builtin_trap:
1570 with self.builtin_trap:
1572 info = self._object_find(oname)
1571 info = self._object_find(oname)
1573 if info.found:
1572 if info.found:
1574 return self.inspector._format_info(info.obj, oname, info=info,
1573 return self.inspector._format_info(info.obj, oname, info=info,
1575 detail_level=detail_level
1574 detail_level=detail_level
1576 )
1575 )
1577 else:
1576 else:
1578 raise KeyError(oname)
1577 raise KeyError(oname)
1579
1578
1580 #-------------------------------------------------------------------------
1579 #-------------------------------------------------------------------------
1581 # Things related to history management
1580 # Things related to history management
1582 #-------------------------------------------------------------------------
1581 #-------------------------------------------------------------------------
1583
1582
1584 def init_history(self):
1583 def init_history(self):
1585 """Sets up the command history, and starts regular autosaves."""
1584 """Sets up the command history, and starts regular autosaves."""
1586 self.history_manager = HistoryManager(shell=self, parent=self)
1585 self.history_manager = HistoryManager(shell=self, parent=self)
1587 self.configurables.append(self.history_manager)
1586 self.configurables.append(self.history_manager)
1588
1587
1589 #-------------------------------------------------------------------------
1588 #-------------------------------------------------------------------------
1590 # Things related to exception handling and tracebacks (not debugging)
1589 # Things related to exception handling and tracebacks (not debugging)
1591 #-------------------------------------------------------------------------
1590 #-------------------------------------------------------------------------
1592
1591
1593 def init_traceback_handlers(self, custom_exceptions):
1592 def init_traceback_handlers(self, custom_exceptions):
1594 # Syntax error handler.
1593 # Syntax error handler.
1595 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1594 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1596
1595
1597 # The interactive one is initialized with an offset, meaning we always
1596 # The interactive one is initialized with an offset, meaning we always
1598 # want to remove the topmost item in the traceback, which is our own
1597 # want to remove the topmost item in the traceback, which is our own
1599 # internal code. Valid modes: ['Plain','Context','Verbose']
1598 # internal code. Valid modes: ['Plain','Context','Verbose']
1600 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1599 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1601 color_scheme='NoColor',
1600 color_scheme='NoColor',
1602 tb_offset = 1,
1601 tb_offset = 1,
1603 check_cache=check_linecache_ipython)
1602 check_cache=check_linecache_ipython)
1604
1603
1605 # The instance will store a pointer to the system-wide exception hook,
1604 # The instance will store a pointer to the system-wide exception hook,
1606 # so that runtime code (such as magics) can access it. This is because
1605 # so that runtime code (such as magics) can access it. This is because
1607 # during the read-eval loop, it may get temporarily overwritten.
1606 # during the read-eval loop, it may get temporarily overwritten.
1608 self.sys_excepthook = sys.excepthook
1607 self.sys_excepthook = sys.excepthook
1609
1608
1610 # and add any custom exception handlers the user may have specified
1609 # and add any custom exception handlers the user may have specified
1611 self.set_custom_exc(*custom_exceptions)
1610 self.set_custom_exc(*custom_exceptions)
1612
1611
1613 # Set the exception mode
1612 # Set the exception mode
1614 self.InteractiveTB.set_mode(mode=self.xmode)
1613 self.InteractiveTB.set_mode(mode=self.xmode)
1615
1614
1616 def set_custom_exc(self, exc_tuple, handler):
1615 def set_custom_exc(self, exc_tuple, handler):
1617 """set_custom_exc(exc_tuple,handler)
1616 """set_custom_exc(exc_tuple,handler)
1618
1617
1619 Set a custom exception handler, which will be called if any of the
1618 Set a custom exception handler, which will be called if any of the
1620 exceptions in exc_tuple occur in the mainloop (specifically, in the
1619 exceptions in exc_tuple occur in the mainloop (specifically, in the
1621 run_code() method).
1620 run_code() method).
1622
1621
1623 Parameters
1622 Parameters
1624 ----------
1623 ----------
1625
1624
1626 exc_tuple : tuple of exception classes
1625 exc_tuple : tuple of exception classes
1627 A *tuple* of exception classes, for which to call the defined
1626 A *tuple* of exception classes, for which to call the defined
1628 handler. It is very important that you use a tuple, and NOT A
1627 handler. It is very important that you use a tuple, and NOT A
1629 LIST here, because of the way Python's except statement works. If
1628 LIST here, because of the way Python's except statement works. If
1630 you only want to trap a single exception, use a singleton tuple::
1629 you only want to trap a single exception, use a singleton tuple::
1631
1630
1632 exc_tuple == (MyCustomException,)
1631 exc_tuple == (MyCustomException,)
1633
1632
1634 handler : callable
1633 handler : callable
1635 handler must have the following signature::
1634 handler must have the following signature::
1636
1635
1637 def my_handler(self, etype, value, tb, tb_offset=None):
1636 def my_handler(self, etype, value, tb, tb_offset=None):
1638 ...
1637 ...
1639 return structured_traceback
1638 return structured_traceback
1640
1639
1641 Your handler must return a structured traceback (a list of strings),
1640 Your handler must return a structured traceback (a list of strings),
1642 or None.
1641 or None.
1643
1642
1644 This will be made into an instance method (via types.MethodType)
1643 This will be made into an instance method (via types.MethodType)
1645 of IPython itself, and it will be called if any of the exceptions
1644 of IPython itself, and it will be called if any of the exceptions
1646 listed in the exc_tuple are caught. If the handler is None, an
1645 listed in the exc_tuple are caught. If the handler is None, an
1647 internal basic one is used, which just prints basic info.
1646 internal basic one is used, which just prints basic info.
1648
1647
1649 To protect IPython from crashes, if your handler ever raises an
1648 To protect IPython from crashes, if your handler ever raises an
1650 exception or returns an invalid result, it will be immediately
1649 exception or returns an invalid result, it will be immediately
1651 disabled.
1650 disabled.
1652
1651
1653 WARNING: by putting in your own exception handler into IPython's main
1652 WARNING: by putting in your own exception handler into IPython's main
1654 execution loop, you run a very good chance of nasty crashes. This
1653 execution loop, you run a very good chance of nasty crashes. This
1655 facility should only be used if you really know what you are doing."""
1654 facility should only be used if you really know what you are doing."""
1656
1655
1657 assert type(exc_tuple)==type(()) , \
1656 assert type(exc_tuple)==type(()) , \
1658 "The custom exceptions must be given AS A TUPLE."
1657 "The custom exceptions must be given AS A TUPLE."
1659
1658
1660 def dummy_handler(self,etype,value,tb,tb_offset=None):
1659 def dummy_handler(self,etype,value,tb,tb_offset=None):
1661 print('*** Simple custom exception handler ***')
1660 print('*** Simple custom exception handler ***')
1662 print('Exception type :',etype)
1661 print('Exception type :',etype)
1663 print('Exception value:',value)
1662 print('Exception value:',value)
1664 print('Traceback :',tb)
1663 print('Traceback :',tb)
1665 #print 'Source code :','\n'.join(self.buffer)
1664 #print 'Source code :','\n'.join(self.buffer)
1666
1665
1667 def validate_stb(stb):
1666 def validate_stb(stb):
1668 """validate structured traceback return type
1667 """validate structured traceback return type
1669
1668
1670 return type of CustomTB *should* be a list of strings, but allow
1669 return type of CustomTB *should* be a list of strings, but allow
1671 single strings or None, which are harmless.
1670 single strings or None, which are harmless.
1672
1671
1673 This function will *always* return a list of strings,
1672 This function will *always* return a list of strings,
1674 and will raise a TypeError if stb is inappropriate.
1673 and will raise a TypeError if stb is inappropriate.
1675 """
1674 """
1676 msg = "CustomTB must return list of strings, not %r" % stb
1675 msg = "CustomTB must return list of strings, not %r" % stb
1677 if stb is None:
1676 if stb is None:
1678 return []
1677 return []
1679 elif isinstance(stb, string_types):
1678 elif isinstance(stb, string_types):
1680 return [stb]
1679 return [stb]
1681 elif not isinstance(stb, list):
1680 elif not isinstance(stb, list):
1682 raise TypeError(msg)
1681 raise TypeError(msg)
1683 # it's a list
1682 # it's a list
1684 for line in stb:
1683 for line in stb:
1685 # check every element
1684 # check every element
1686 if not isinstance(line, string_types):
1685 if not isinstance(line, string_types):
1687 raise TypeError(msg)
1686 raise TypeError(msg)
1688 return stb
1687 return stb
1689
1688
1690 if handler is None:
1689 if handler is None:
1691 wrapped = dummy_handler
1690 wrapped = dummy_handler
1692 else:
1691 else:
1693 def wrapped(self,etype,value,tb,tb_offset=None):
1692 def wrapped(self,etype,value,tb,tb_offset=None):
1694 """wrap CustomTB handler, to protect IPython from user code
1693 """wrap CustomTB handler, to protect IPython from user code
1695
1694
1696 This makes it harder (but not impossible) for custom exception
1695 This makes it harder (but not impossible) for custom exception
1697 handlers to crash IPython.
1696 handlers to crash IPython.
1698 """
1697 """
1699 try:
1698 try:
1700 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1699 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1701 return validate_stb(stb)
1700 return validate_stb(stb)
1702 except:
1701 except:
1703 # clear custom handler immediately
1702 # clear custom handler immediately
1704 self.set_custom_exc((), None)
1703 self.set_custom_exc((), None)
1705 print("Custom TB Handler failed, unregistering", file=io.stderr)
1704 print("Custom TB Handler failed, unregistering", file=io.stderr)
1706 # show the exception in handler first
1705 # show the exception in handler first
1707 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1706 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1708 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1707 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1709 print("The original exception:", file=io.stdout)
1708 print("The original exception:", file=io.stdout)
1710 stb = self.InteractiveTB.structured_traceback(
1709 stb = self.InteractiveTB.structured_traceback(
1711 (etype,value,tb), tb_offset=tb_offset
1710 (etype,value,tb), tb_offset=tb_offset
1712 )
1711 )
1713 return stb
1712 return stb
1714
1713
1715 self.CustomTB = types.MethodType(wrapped,self)
1714 self.CustomTB = types.MethodType(wrapped,self)
1716 self.custom_exceptions = exc_tuple
1715 self.custom_exceptions = exc_tuple
1717
1716
1718 def excepthook(self, etype, value, tb):
1717 def excepthook(self, etype, value, tb):
1719 """One more defense for GUI apps that call sys.excepthook.
1718 """One more defense for GUI apps that call sys.excepthook.
1720
1719
1721 GUI frameworks like wxPython trap exceptions and call
1720 GUI frameworks like wxPython trap exceptions and call
1722 sys.excepthook themselves. I guess this is a feature that
1721 sys.excepthook themselves. I guess this is a feature that
1723 enables them to keep running after exceptions that would
1722 enables them to keep running after exceptions that would
1724 otherwise kill their mainloop. This is a bother for IPython
1723 otherwise kill their mainloop. This is a bother for IPython
1725 which excepts to catch all of the program exceptions with a try:
1724 which excepts to catch all of the program exceptions with a try:
1726 except: statement.
1725 except: statement.
1727
1726
1728 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1727 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1729 any app directly invokes sys.excepthook, it will look to the user like
1728 any app directly invokes sys.excepthook, it will look to the user like
1730 IPython crashed. In order to work around this, we can disable the
1729 IPython crashed. In order to work around this, we can disable the
1731 CrashHandler and replace it with this excepthook instead, which prints a
1730 CrashHandler and replace it with this excepthook instead, which prints a
1732 regular traceback using our InteractiveTB. In this fashion, apps which
1731 regular traceback using our InteractiveTB. In this fashion, apps which
1733 call sys.excepthook will generate a regular-looking exception from
1732 call sys.excepthook will generate a regular-looking exception from
1734 IPython, and the CrashHandler will only be triggered by real IPython
1733 IPython, and the CrashHandler will only be triggered by real IPython
1735 crashes.
1734 crashes.
1736
1735
1737 This hook should be used sparingly, only in places which are not likely
1736 This hook should be used sparingly, only in places which are not likely
1738 to be true IPython errors.
1737 to be true IPython errors.
1739 """
1738 """
1740 self.showtraceback((etype, value, tb), tb_offset=0)
1739 self.showtraceback((etype, value, tb), tb_offset=0)
1741
1740
1742 def _get_exc_info(self, exc_tuple=None):
1741 def _get_exc_info(self, exc_tuple=None):
1743 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1742 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1744
1743
1745 Ensures sys.last_type,value,traceback hold the exc_info we found,
1744 Ensures sys.last_type,value,traceback hold the exc_info we found,
1746 from whichever source.
1745 from whichever source.
1747
1746
1748 raises ValueError if none of these contain any information
1747 raises ValueError if none of these contain any information
1749 """
1748 """
1750 if exc_tuple is None:
1749 if exc_tuple is None:
1751 etype, value, tb = sys.exc_info()
1750 etype, value, tb = sys.exc_info()
1752 else:
1751 else:
1753 etype, value, tb = exc_tuple
1752 etype, value, tb = exc_tuple
1754
1753
1755 if etype is None:
1754 if etype is None:
1756 if hasattr(sys, 'last_type'):
1755 if hasattr(sys, 'last_type'):
1757 etype, value, tb = sys.last_type, sys.last_value, \
1756 etype, value, tb = sys.last_type, sys.last_value, \
1758 sys.last_traceback
1757 sys.last_traceback
1759
1758
1760 if etype is None:
1759 if etype is None:
1761 raise ValueError("No exception to find")
1760 raise ValueError("No exception to find")
1762
1761
1763 # Now store the exception info in sys.last_type etc.
1762 # Now store the exception info in sys.last_type etc.
1764 # WARNING: these variables are somewhat deprecated and not
1763 # WARNING: these variables are somewhat deprecated and not
1765 # necessarily safe to use in a threaded environment, but tools
1764 # necessarily safe to use in a threaded environment, but tools
1766 # like pdb depend on their existence, so let's set them. If we
1765 # like pdb depend on their existence, so let's set them. If we
1767 # find problems in the field, we'll need to revisit their use.
1766 # find problems in the field, we'll need to revisit their use.
1768 sys.last_type = etype
1767 sys.last_type = etype
1769 sys.last_value = value
1768 sys.last_value = value
1770 sys.last_traceback = tb
1769 sys.last_traceback = tb
1771
1770
1772 return etype, value, tb
1771 return etype, value, tb
1773
1772
1774 def show_usage_error(self, exc):
1773 def show_usage_error(self, exc):
1775 """Show a short message for UsageErrors
1774 """Show a short message for UsageErrors
1776
1775
1777 These are special exceptions that shouldn't show a traceback.
1776 These are special exceptions that shouldn't show a traceback.
1778 """
1777 """
1779 self.write_err("UsageError: %s" % exc)
1778 self.write_err("UsageError: %s" % exc)
1780
1779
1781 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1780 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1782 exception_only=False):
1781 exception_only=False):
1783 """Display the exception that just occurred.
1782 """Display the exception that just occurred.
1784
1783
1785 If nothing is known about the exception, this is the method which
1784 If nothing is known about the exception, this is the method which
1786 should be used throughout the code for presenting user tracebacks,
1785 should be used throughout the code for presenting user tracebacks,
1787 rather than directly invoking the InteractiveTB object.
1786 rather than directly invoking the InteractiveTB object.
1788
1787
1789 A specific showsyntaxerror() also exists, but this method can take
1788 A specific showsyntaxerror() also exists, but this method can take
1790 care of calling it if needed, so unless you are explicitly catching a
1789 care of calling it if needed, so unless you are explicitly catching a
1791 SyntaxError exception, don't try to analyze the stack manually and
1790 SyntaxError exception, don't try to analyze the stack manually and
1792 simply call this method."""
1791 simply call this method."""
1793
1792
1794 try:
1793 try:
1795 try:
1794 try:
1796 etype, value, tb = self._get_exc_info(exc_tuple)
1795 etype, value, tb = self._get_exc_info(exc_tuple)
1797 except ValueError:
1796 except ValueError:
1798 self.write_err('No traceback available to show.\n')
1797 self.write_err('No traceback available to show.\n')
1799 return
1798 return
1800
1799
1801 if issubclass(etype, SyntaxError):
1800 if issubclass(etype, SyntaxError):
1802 # Though this won't be called by syntax errors in the input
1801 # Though this won't be called by syntax errors in the input
1803 # line, there may be SyntaxError cases with imported code.
1802 # line, there may be SyntaxError cases with imported code.
1804 self.showsyntaxerror(filename)
1803 self.showsyntaxerror(filename)
1805 elif etype is UsageError:
1804 elif etype is UsageError:
1806 self.show_usage_error(value)
1805 self.show_usage_error(value)
1807 else:
1806 else:
1808 if exception_only:
1807 if exception_only:
1809 stb = ['An exception has occurred, use %tb to see '
1808 stb = ['An exception has occurred, use %tb to see '
1810 'the full traceback.\n']
1809 'the full traceback.\n']
1811 stb.extend(self.InteractiveTB.get_exception_only(etype,
1810 stb.extend(self.InteractiveTB.get_exception_only(etype,
1812 value))
1811 value))
1813 else:
1812 else:
1814 try:
1813 try:
1815 # Exception classes can customise their traceback - we
1814 # Exception classes can customise their traceback - we
1816 # use this in IPython.parallel for exceptions occurring
1815 # use this in IPython.parallel for exceptions occurring
1817 # in the engines. This should return a list of strings.
1816 # in the engines. This should return a list of strings.
1818 stb = value._render_traceback_()
1817 stb = value._render_traceback_()
1819 except Exception:
1818 except Exception:
1820 stb = self.InteractiveTB.structured_traceback(etype,
1819 stb = self.InteractiveTB.structured_traceback(etype,
1821 value, tb, tb_offset=tb_offset)
1820 value, tb, tb_offset=tb_offset)
1822
1821
1823 self._showtraceback(etype, value, stb)
1822 self._showtraceback(etype, value, stb)
1824 if self.call_pdb:
1823 if self.call_pdb:
1825 # drop into debugger
1824 # drop into debugger
1826 self.debugger(force=True)
1825 self.debugger(force=True)
1827 return
1826 return
1828
1827
1829 # Actually show the traceback
1828 # Actually show the traceback
1830 self._showtraceback(etype, value, stb)
1829 self._showtraceback(etype, value, stb)
1831
1830
1832 except KeyboardInterrupt:
1831 except KeyboardInterrupt:
1833 self.write_err("\nKeyboardInterrupt\n")
1832 self.write_err("\nKeyboardInterrupt\n")
1834
1833
1835 def _showtraceback(self, etype, evalue, stb):
1834 def _showtraceback(self, etype, evalue, stb):
1836 """Actually show a traceback.
1835 """Actually show a traceback.
1837
1836
1838 Subclasses may override this method to put the traceback on a different
1837 Subclasses may override this method to put the traceback on a different
1839 place, like a side channel.
1838 place, like a side channel.
1840 """
1839 """
1841 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1840 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1842
1841
1843 def showsyntaxerror(self, filename=None):
1842 def showsyntaxerror(self, filename=None):
1844 """Display the syntax error that just occurred.
1843 """Display the syntax error that just occurred.
1845
1844
1846 This doesn't display a stack trace because there isn't one.
1845 This doesn't display a stack trace because there isn't one.
1847
1846
1848 If a filename is given, it is stuffed in the exception instead
1847 If a filename is given, it is stuffed in the exception instead
1849 of what was there before (because Python's parser always uses
1848 of what was there before (because Python's parser always uses
1850 "<string>" when reading from a string).
1849 "<string>" when reading from a string).
1851 """
1850 """
1852 etype, value, last_traceback = self._get_exc_info()
1851 etype, value, last_traceback = self._get_exc_info()
1853
1852
1854 if filename and issubclass(etype, SyntaxError):
1853 if filename and issubclass(etype, SyntaxError):
1855 try:
1854 try:
1856 value.filename = filename
1855 value.filename = filename
1857 except:
1856 except:
1858 # Not the format we expect; leave it alone
1857 # Not the format we expect; leave it alone
1859 pass
1858 pass
1860
1859
1861 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1860 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1862 self._showtraceback(etype, value, stb)
1861 self._showtraceback(etype, value, stb)
1863
1862
1864 # This is overridden in TerminalInteractiveShell to show a message about
1863 # This is overridden in TerminalInteractiveShell to show a message about
1865 # the %paste magic.
1864 # the %paste magic.
1866 def showindentationerror(self):
1865 def showindentationerror(self):
1867 """Called by run_cell when there's an IndentationError in code entered
1866 """Called by run_cell when there's an IndentationError in code entered
1868 at the prompt.
1867 at the prompt.
1869
1868
1870 This is overridden in TerminalInteractiveShell to show a message about
1869 This is overridden in TerminalInteractiveShell to show a message about
1871 the %paste magic."""
1870 the %paste magic."""
1872 self.showsyntaxerror()
1871 self.showsyntaxerror()
1873
1872
1874 #-------------------------------------------------------------------------
1873 #-------------------------------------------------------------------------
1875 # Things related to readline
1874 # Things related to readline
1876 #-------------------------------------------------------------------------
1875 #-------------------------------------------------------------------------
1877
1876
1878 def init_readline(self):
1877 def init_readline(self):
1879 """Command history completion/saving/reloading."""
1878 """Command history completion/saving/reloading."""
1880
1879
1881 if self.readline_use:
1880 if self.readline_use:
1882 import IPython.utils.rlineimpl as readline
1881 import IPython.utils.rlineimpl as readline
1883
1882
1884 self.rl_next_input = None
1883 self.rl_next_input = None
1885 self.rl_do_indent = False
1884 self.rl_do_indent = False
1886
1885
1887 if not self.readline_use or not readline.have_readline:
1886 if not self.readline_use or not readline.have_readline:
1888 self.has_readline = False
1887 self.has_readline = False
1889 self.readline = None
1888 self.readline = None
1890 # Set a number of methods that depend on readline to be no-op
1889 # Set a number of methods that depend on readline to be no-op
1891 self.readline_no_record = no_op_context
1890 self.readline_no_record = no_op_context
1892 self.set_readline_completer = no_op
1891 self.set_readline_completer = no_op
1893 self.set_custom_completer = no_op
1892 self.set_custom_completer = no_op
1894 if self.readline_use:
1893 if self.readline_use:
1895 warn('Readline services not available or not loaded.')
1894 warn('Readline services not available or not loaded.')
1896 else:
1895 else:
1897 self.has_readline = True
1896 self.has_readline = True
1898 self.readline = readline
1897 self.readline = readline
1899 sys.modules['readline'] = readline
1898 sys.modules['readline'] = readline
1900
1899
1901 # Platform-specific configuration
1900 # Platform-specific configuration
1902 if os.name == 'nt':
1901 if os.name == 'nt':
1903 # FIXME - check with Frederick to see if we can harmonize
1902 # FIXME - check with Frederick to see if we can harmonize
1904 # naming conventions with pyreadline to avoid this
1903 # naming conventions with pyreadline to avoid this
1905 # platform-dependent check
1904 # platform-dependent check
1906 self.readline_startup_hook = readline.set_pre_input_hook
1905 self.readline_startup_hook = readline.set_pre_input_hook
1907 else:
1906 else:
1908 self.readline_startup_hook = readline.set_startup_hook
1907 self.readline_startup_hook = readline.set_startup_hook
1909
1908
1910 # Readline config order:
1909 # Readline config order:
1911 # - IPython config (default value)
1910 # - IPython config (default value)
1912 # - custom inputrc
1911 # - custom inputrc
1913 # - IPython config (user customized)
1912 # - IPython config (user customized)
1914
1913
1915 # load IPython config before inputrc if default
1914 # load IPython config before inputrc if default
1916 # skip if libedit because parse_and_bind syntax is different
1915 # skip if libedit because parse_and_bind syntax is different
1917 if not self._custom_readline_config and not readline.uses_libedit:
1916 if not self._custom_readline_config and not readline.uses_libedit:
1918 for rlcommand in self.readline_parse_and_bind:
1917 for rlcommand in self.readline_parse_and_bind:
1919 readline.parse_and_bind(rlcommand)
1918 readline.parse_and_bind(rlcommand)
1920
1919
1921 # Load user's initrc file (readline config)
1920 # Load user's initrc file (readline config)
1922 # Or if libedit is used, load editrc.
1921 # Or if libedit is used, load editrc.
1923 inputrc_name = os.environ.get('INPUTRC')
1922 inputrc_name = os.environ.get('INPUTRC')
1924 if inputrc_name is None:
1923 if inputrc_name is None:
1925 inputrc_name = '.inputrc'
1924 inputrc_name = '.inputrc'
1926 if readline.uses_libedit:
1925 if readline.uses_libedit:
1927 inputrc_name = '.editrc'
1926 inputrc_name = '.editrc'
1928 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1927 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1929 if os.path.isfile(inputrc_name):
1928 if os.path.isfile(inputrc_name):
1930 try:
1929 try:
1931 readline.read_init_file(inputrc_name)
1930 readline.read_init_file(inputrc_name)
1932 except:
1931 except:
1933 warn('Problems reading readline initialization file <%s>'
1932 warn('Problems reading readline initialization file <%s>'
1934 % inputrc_name)
1933 % inputrc_name)
1935
1934
1936 # load IPython config after inputrc if user has customized
1935 # load IPython config after inputrc if user has customized
1937 if self._custom_readline_config:
1936 if self._custom_readline_config:
1938 for rlcommand in self.readline_parse_and_bind:
1937 for rlcommand in self.readline_parse_and_bind:
1939 readline.parse_and_bind(rlcommand)
1938 readline.parse_and_bind(rlcommand)
1940
1939
1941 # Remove some chars from the delimiters list. If we encounter
1940 # Remove some chars from the delimiters list. If we encounter
1942 # unicode chars, discard them.
1941 # unicode chars, discard them.
1943 delims = readline.get_completer_delims()
1942 delims = readline.get_completer_delims()
1944 if not py3compat.PY3:
1943 if not py3compat.PY3:
1945 delims = delims.encode("ascii", "ignore")
1944 delims = delims.encode("ascii", "ignore")
1946 for d in self.readline_remove_delims:
1945 for d in self.readline_remove_delims:
1947 delims = delims.replace(d, "")
1946 delims = delims.replace(d, "")
1948 delims = delims.replace(ESC_MAGIC, '')
1947 delims = delims.replace(ESC_MAGIC, '')
1949 readline.set_completer_delims(delims)
1948 readline.set_completer_delims(delims)
1950 # Store these so we can restore them if something like rpy2 modifies
1949 # Store these so we can restore them if something like rpy2 modifies
1951 # them.
1950 # them.
1952 self.readline_delims = delims
1951 self.readline_delims = delims
1953 # otherwise we end up with a monster history after a while:
1952 # otherwise we end up with a monster history after a while:
1954 readline.set_history_length(self.history_length)
1953 readline.set_history_length(self.history_length)
1955
1954
1956 self.refill_readline_hist()
1955 self.refill_readline_hist()
1957 self.readline_no_record = ReadlineNoRecord(self)
1956 self.readline_no_record = ReadlineNoRecord(self)
1958
1957
1959 # Configure auto-indent for all platforms
1958 # Configure auto-indent for all platforms
1960 self.set_autoindent(self.autoindent)
1959 self.set_autoindent(self.autoindent)
1961
1960
1962 def refill_readline_hist(self):
1961 def refill_readline_hist(self):
1963 # Load the last 1000 lines from history
1962 # Load the last 1000 lines from history
1964 self.readline.clear_history()
1963 self.readline.clear_history()
1965 stdin_encoding = sys.stdin.encoding or "utf-8"
1964 stdin_encoding = sys.stdin.encoding or "utf-8"
1966 last_cell = u""
1965 last_cell = u""
1967 for _, _, cell in self.history_manager.get_tail(1000,
1966 for _, _, cell in self.history_manager.get_tail(1000,
1968 include_latest=True):
1967 include_latest=True):
1969 # Ignore blank lines and consecutive duplicates
1968 # Ignore blank lines and consecutive duplicates
1970 cell = cell.rstrip()
1969 cell = cell.rstrip()
1971 if cell and (cell != last_cell):
1970 if cell and (cell != last_cell):
1972 try:
1971 try:
1973 if self.multiline_history:
1972 if self.multiline_history:
1974 self.readline.add_history(py3compat.unicode_to_str(cell,
1973 self.readline.add_history(py3compat.unicode_to_str(cell,
1975 stdin_encoding))
1974 stdin_encoding))
1976 else:
1975 else:
1977 for line in cell.splitlines():
1976 for line in cell.splitlines():
1978 self.readline.add_history(py3compat.unicode_to_str(line,
1977 self.readline.add_history(py3compat.unicode_to_str(line,
1979 stdin_encoding))
1978 stdin_encoding))
1980 last_cell = cell
1979 last_cell = cell
1981
1980
1982 except TypeError:
1981 except TypeError:
1983 # The history DB can get corrupted so it returns strings
1982 # The history DB can get corrupted so it returns strings
1984 # containing null bytes, which readline objects to.
1983 # containing null bytes, which readline objects to.
1985 continue
1984 continue
1986
1985
1987 @skip_doctest
1986 @skip_doctest
1988 def set_next_input(self, s):
1987 def set_next_input(self, s):
1989 """ Sets the 'default' input string for the next command line.
1988 """ Sets the 'default' input string for the next command line.
1990
1989
1991 Requires readline.
1990 Requires readline.
1992
1991
1993 Example::
1992 Example::
1994
1993
1995 In [1]: _ip.set_next_input("Hello Word")
1994 In [1]: _ip.set_next_input("Hello Word")
1996 In [2]: Hello Word_ # cursor is here
1995 In [2]: Hello Word_ # cursor is here
1997 """
1996 """
1998 self.rl_next_input = py3compat.cast_bytes_py2(s)
1997 self.rl_next_input = py3compat.cast_bytes_py2(s)
1999
1998
2000 # Maybe move this to the terminal subclass?
1999 # Maybe move this to the terminal subclass?
2001 def pre_readline(self):
2000 def pre_readline(self):
2002 """readline hook to be used at the start of each line.
2001 """readline hook to be used at the start of each line.
2003
2002
2004 Currently it handles auto-indent only."""
2003 Currently it handles auto-indent only."""
2005
2004
2006 if self.rl_do_indent:
2005 if self.rl_do_indent:
2007 self.readline.insert_text(self._indent_current_str())
2006 self.readline.insert_text(self._indent_current_str())
2008 if self.rl_next_input is not None:
2007 if self.rl_next_input is not None:
2009 self.readline.insert_text(self.rl_next_input)
2008 self.readline.insert_text(self.rl_next_input)
2010 self.rl_next_input = None
2009 self.rl_next_input = None
2011
2010
2012 def _indent_current_str(self):
2011 def _indent_current_str(self):
2013 """return the current level of indentation as a string"""
2012 """return the current level of indentation as a string"""
2014 return self.input_splitter.indent_spaces * ' '
2013 return self.input_splitter.indent_spaces * ' '
2015
2014
2016 #-------------------------------------------------------------------------
2015 #-------------------------------------------------------------------------
2017 # Things related to text completion
2016 # Things related to text completion
2018 #-------------------------------------------------------------------------
2017 #-------------------------------------------------------------------------
2019
2018
2020 def init_completer(self):
2019 def init_completer(self):
2021 """Initialize the completion machinery.
2020 """Initialize the completion machinery.
2022
2021
2023 This creates completion machinery that can be used by client code,
2022 This creates completion machinery that can be used by client code,
2024 either interactively in-process (typically triggered by the readline
2023 either interactively in-process (typically triggered by the readline
2025 library), programatically (such as in test suites) or out-of-prcess
2024 library), programatically (such as in test suites) or out-of-prcess
2026 (typically over the network by remote frontends).
2025 (typically over the network by remote frontends).
2027 """
2026 """
2028 from IPython.core.completer import IPCompleter
2027 from IPython.core.completer import IPCompleter
2029 from IPython.core.completerlib import (module_completer,
2028 from IPython.core.completerlib import (module_completer,
2030 magic_run_completer, cd_completer, reset_completer)
2029 magic_run_completer, cd_completer, reset_completer)
2031
2030
2032 self.Completer = IPCompleter(shell=self,
2031 self.Completer = IPCompleter(shell=self,
2033 namespace=self.user_ns,
2032 namespace=self.user_ns,
2034 global_namespace=self.user_global_ns,
2033 global_namespace=self.user_global_ns,
2035 use_readline=self.has_readline,
2034 use_readline=self.has_readline,
2036 parent=self,
2035 parent=self,
2037 )
2036 )
2038 self.configurables.append(self.Completer)
2037 self.configurables.append(self.Completer)
2039
2038
2040 # Add custom completers to the basic ones built into IPCompleter
2039 # Add custom completers to the basic ones built into IPCompleter
2041 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2040 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2042 self.strdispatchers['complete_command'] = sdisp
2041 self.strdispatchers['complete_command'] = sdisp
2043 self.Completer.custom_completers = sdisp
2042 self.Completer.custom_completers = sdisp
2044
2043
2045 self.set_hook('complete_command', module_completer, str_key = 'import')
2044 self.set_hook('complete_command', module_completer, str_key = 'import')
2046 self.set_hook('complete_command', module_completer, str_key = 'from')
2045 self.set_hook('complete_command', module_completer, str_key = 'from')
2047 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2046 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2048 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2047 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2049 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2048 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2050
2049
2051 # Only configure readline if we truly are using readline. IPython can
2050 # Only configure readline if we truly are using readline. IPython can
2052 # do tab-completion over the network, in GUIs, etc, where readline
2051 # do tab-completion over the network, in GUIs, etc, where readline
2053 # itself may be absent
2052 # itself may be absent
2054 if self.has_readline:
2053 if self.has_readline:
2055 self.set_readline_completer()
2054 self.set_readline_completer()
2056
2055
2057 def complete(self, text, line=None, cursor_pos=None):
2056 def complete(self, text, line=None, cursor_pos=None):
2058 """Return the completed text and a list of completions.
2057 """Return the completed text and a list of completions.
2059
2058
2060 Parameters
2059 Parameters
2061 ----------
2060 ----------
2062
2061
2063 text : string
2062 text : string
2064 A string of text to be completed on. It can be given as empty and
2063 A string of text to be completed on. It can be given as empty and
2065 instead a line/position pair are given. In this case, the
2064 instead a line/position pair are given. In this case, the
2066 completer itself will split the line like readline does.
2065 completer itself will split the line like readline does.
2067
2066
2068 line : string, optional
2067 line : string, optional
2069 The complete line that text is part of.
2068 The complete line that text is part of.
2070
2069
2071 cursor_pos : int, optional
2070 cursor_pos : int, optional
2072 The position of the cursor on the input line.
2071 The position of the cursor on the input line.
2073
2072
2074 Returns
2073 Returns
2075 -------
2074 -------
2076 text : string
2075 text : string
2077 The actual text that was completed.
2076 The actual text that was completed.
2078
2077
2079 matches : list
2078 matches : list
2080 A sorted list with all possible completions.
2079 A sorted list with all possible completions.
2081
2080
2082 The optional arguments allow the completion to take more context into
2081 The optional arguments allow the completion to take more context into
2083 account, and are part of the low-level completion API.
2082 account, and are part of the low-level completion API.
2084
2083
2085 This is a wrapper around the completion mechanism, similar to what
2084 This is a wrapper around the completion mechanism, similar to what
2086 readline does at the command line when the TAB key is hit. By
2085 readline does at the command line when the TAB key is hit. By
2087 exposing it as a method, it can be used by other non-readline
2086 exposing it as a method, it can be used by other non-readline
2088 environments (such as GUIs) for text completion.
2087 environments (such as GUIs) for text completion.
2089
2088
2090 Simple usage example:
2089 Simple usage example:
2091
2090
2092 In [1]: x = 'hello'
2091 In [1]: x = 'hello'
2093
2092
2094 In [2]: _ip.complete('x.l')
2093 In [2]: _ip.complete('x.l')
2095 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2094 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2096 """
2095 """
2097
2096
2098 # Inject names into __builtin__ so we can complete on the added names.
2097 # Inject names into __builtin__ so we can complete on the added names.
2099 with self.builtin_trap:
2098 with self.builtin_trap:
2100 return self.Completer.complete(text, line, cursor_pos)
2099 return self.Completer.complete(text, line, cursor_pos)
2101
2100
2102 def set_custom_completer(self, completer, pos=0):
2101 def set_custom_completer(self, completer, pos=0):
2103 """Adds a new custom completer function.
2102 """Adds a new custom completer function.
2104
2103
2105 The position argument (defaults to 0) is the index in the completers
2104 The position argument (defaults to 0) is the index in the completers
2106 list where you want the completer to be inserted."""
2105 list where you want the completer to be inserted."""
2107
2106
2108 newcomp = types.MethodType(completer,self.Completer)
2107 newcomp = types.MethodType(completer,self.Completer)
2109 self.Completer.matchers.insert(pos,newcomp)
2108 self.Completer.matchers.insert(pos,newcomp)
2110
2109
2111 def set_readline_completer(self):
2110 def set_readline_completer(self):
2112 """Reset readline's completer to be our own."""
2111 """Reset readline's completer to be our own."""
2113 self.readline.set_completer(self.Completer.rlcomplete)
2112 self.readline.set_completer(self.Completer.rlcomplete)
2114
2113
2115 def set_completer_frame(self, frame=None):
2114 def set_completer_frame(self, frame=None):
2116 """Set the frame of the completer."""
2115 """Set the frame of the completer."""
2117 if frame:
2116 if frame:
2118 self.Completer.namespace = frame.f_locals
2117 self.Completer.namespace = frame.f_locals
2119 self.Completer.global_namespace = frame.f_globals
2118 self.Completer.global_namespace = frame.f_globals
2120 else:
2119 else:
2121 self.Completer.namespace = self.user_ns
2120 self.Completer.namespace = self.user_ns
2122 self.Completer.global_namespace = self.user_global_ns
2121 self.Completer.global_namespace = self.user_global_ns
2123
2122
2124 #-------------------------------------------------------------------------
2123 #-------------------------------------------------------------------------
2125 # Things related to magics
2124 # Things related to magics
2126 #-------------------------------------------------------------------------
2125 #-------------------------------------------------------------------------
2127
2126
2128 def init_magics(self):
2127 def init_magics(self):
2129 from IPython.core import magics as m
2128 from IPython.core import magics as m
2130 self.magics_manager = magic.MagicsManager(shell=self,
2129 self.magics_manager = magic.MagicsManager(shell=self,
2131 parent=self,
2130 parent=self,
2132 user_magics=m.UserMagics(self))
2131 user_magics=m.UserMagics(self))
2133 self.configurables.append(self.magics_manager)
2132 self.configurables.append(self.magics_manager)
2134
2133
2135 # Expose as public API from the magics manager
2134 # Expose as public API from the magics manager
2136 self.register_magics = self.magics_manager.register
2135 self.register_magics = self.magics_manager.register
2137 self.define_magic = self.magics_manager.define_magic
2136 self.define_magic = self.magics_manager.define_magic
2138
2137
2139 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2138 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2140 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2139 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2141 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2140 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2142 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2141 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2143 )
2142 )
2144
2143
2145 # Register Magic Aliases
2144 # Register Magic Aliases
2146 mman = self.magics_manager
2145 mman = self.magics_manager
2147 # FIXME: magic aliases should be defined by the Magics classes
2146 # FIXME: magic aliases should be defined by the Magics classes
2148 # or in MagicsManager, not here
2147 # or in MagicsManager, not here
2149 mman.register_alias('ed', 'edit')
2148 mman.register_alias('ed', 'edit')
2150 mman.register_alias('hist', 'history')
2149 mman.register_alias('hist', 'history')
2151 mman.register_alias('rep', 'recall')
2150 mman.register_alias('rep', 'recall')
2152 mman.register_alias('SVG', 'svg', 'cell')
2151 mman.register_alias('SVG', 'svg', 'cell')
2153 mman.register_alias('HTML', 'html', 'cell')
2152 mman.register_alias('HTML', 'html', 'cell')
2154 mman.register_alias('file', 'writefile', 'cell')
2153 mman.register_alias('file', 'writefile', 'cell')
2155
2154
2156 # FIXME: Move the color initialization to the DisplayHook, which
2155 # FIXME: Move the color initialization to the DisplayHook, which
2157 # should be split into a prompt manager and displayhook. We probably
2156 # should be split into a prompt manager and displayhook. We probably
2158 # even need a centralize colors management object.
2157 # even need a centralize colors management object.
2159 self.magic('colors %s' % self.colors)
2158 self.magic('colors %s' % self.colors)
2160
2159
2161 # Defined here so that it's included in the documentation
2160 # Defined here so that it's included in the documentation
2162 @functools.wraps(magic.MagicsManager.register_function)
2161 @functools.wraps(magic.MagicsManager.register_function)
2163 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2162 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2164 self.magics_manager.register_function(func,
2163 self.magics_manager.register_function(func,
2165 magic_kind=magic_kind, magic_name=magic_name)
2164 magic_kind=magic_kind, magic_name=magic_name)
2166
2165
2167 def run_line_magic(self, magic_name, line):
2166 def run_line_magic(self, magic_name, line):
2168 """Execute the given line magic.
2167 """Execute the given line magic.
2169
2168
2170 Parameters
2169 Parameters
2171 ----------
2170 ----------
2172 magic_name : str
2171 magic_name : str
2173 Name of the desired magic function, without '%' prefix.
2172 Name of the desired magic function, without '%' prefix.
2174
2173
2175 line : str
2174 line : str
2176 The rest of the input line as a single string.
2175 The rest of the input line as a single string.
2177 """
2176 """
2178 fn = self.find_line_magic(magic_name)
2177 fn = self.find_line_magic(magic_name)
2179 if fn is None:
2178 if fn is None:
2180 cm = self.find_cell_magic(magic_name)
2179 cm = self.find_cell_magic(magic_name)
2181 etpl = "Line magic function `%%%s` not found%s."
2180 etpl = "Line magic function `%%%s` not found%s."
2182 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2181 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2183 'did you mean that instead?)' % magic_name )
2182 'did you mean that instead?)' % magic_name )
2184 error(etpl % (magic_name, extra))
2183 error(etpl % (magic_name, extra))
2185 else:
2184 else:
2186 # Note: this is the distance in the stack to the user's frame.
2185 # Note: this is the distance in the stack to the user's frame.
2187 # This will need to be updated if the internal calling logic gets
2186 # This will need to be updated if the internal calling logic gets
2188 # refactored, or else we'll be expanding the wrong variables.
2187 # refactored, or else we'll be expanding the wrong variables.
2189 stack_depth = 2
2188 stack_depth = 2
2190 magic_arg_s = self.var_expand(line, stack_depth)
2189 magic_arg_s = self.var_expand(line, stack_depth)
2191 # Put magic args in a list so we can call with f(*a) syntax
2190 # Put magic args in a list so we can call with f(*a) syntax
2192 args = [magic_arg_s]
2191 args = [magic_arg_s]
2193 kwargs = {}
2192 kwargs = {}
2194 # Grab local namespace if we need it:
2193 # Grab local namespace if we need it:
2195 if getattr(fn, "needs_local_scope", False):
2194 if getattr(fn, "needs_local_scope", False):
2196 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2195 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2197 with self.builtin_trap:
2196 with self.builtin_trap:
2198 result = fn(*args,**kwargs)
2197 result = fn(*args,**kwargs)
2199 return result
2198 return result
2200
2199
2201 def run_cell_magic(self, magic_name, line, cell):
2200 def run_cell_magic(self, magic_name, line, cell):
2202 """Execute the given cell magic.
2201 """Execute the given cell magic.
2203
2202
2204 Parameters
2203 Parameters
2205 ----------
2204 ----------
2206 magic_name : str
2205 magic_name : str
2207 Name of the desired magic function, without '%' prefix.
2206 Name of the desired magic function, without '%' prefix.
2208
2207
2209 line : str
2208 line : str
2210 The rest of the first input line as a single string.
2209 The rest of the first input line as a single string.
2211
2210
2212 cell : str
2211 cell : str
2213 The body of the cell as a (possibly multiline) string.
2212 The body of the cell as a (possibly multiline) string.
2214 """
2213 """
2215 fn = self.find_cell_magic(magic_name)
2214 fn = self.find_cell_magic(magic_name)
2216 if fn is None:
2215 if fn is None:
2217 lm = self.find_line_magic(magic_name)
2216 lm = self.find_line_magic(magic_name)
2218 etpl = "Cell magic `%%{0}` not found{1}."
2217 etpl = "Cell magic `%%{0}` not found{1}."
2219 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2218 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2220 'did you mean that instead?)'.format(magic_name))
2219 'did you mean that instead?)'.format(magic_name))
2221 error(etpl.format(magic_name, extra))
2220 error(etpl.format(magic_name, extra))
2222 elif cell == '':
2221 elif cell == '':
2223 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2222 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2224 if self.find_line_magic(magic_name) is not None:
2223 if self.find_line_magic(magic_name) is not None:
2225 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2224 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2226 raise UsageError(message)
2225 raise UsageError(message)
2227 else:
2226 else:
2228 # Note: this is the distance in the stack to the user's frame.
2227 # Note: this is the distance in the stack to the user's frame.
2229 # This will need to be updated if the internal calling logic gets
2228 # This will need to be updated if the internal calling logic gets
2230 # refactored, or else we'll be expanding the wrong variables.
2229 # refactored, or else we'll be expanding the wrong variables.
2231 stack_depth = 2
2230 stack_depth = 2
2232 magic_arg_s = self.var_expand(line, stack_depth)
2231 magic_arg_s = self.var_expand(line, stack_depth)
2233 with self.builtin_trap:
2232 with self.builtin_trap:
2234 result = fn(magic_arg_s, cell)
2233 result = fn(magic_arg_s, cell)
2235 return result
2234 return result
2236
2235
2237 def find_line_magic(self, magic_name):
2236 def find_line_magic(self, magic_name):
2238 """Find and return a line magic by name.
2237 """Find and return a line magic by name.
2239
2238
2240 Returns None if the magic isn't found."""
2239 Returns None if the magic isn't found."""
2241 return self.magics_manager.magics['line'].get(magic_name)
2240 return self.magics_manager.magics['line'].get(magic_name)
2242
2241
2243 def find_cell_magic(self, magic_name):
2242 def find_cell_magic(self, magic_name):
2244 """Find and return a cell magic by name.
2243 """Find and return a cell magic by name.
2245
2244
2246 Returns None if the magic isn't found."""
2245 Returns None if the magic isn't found."""
2247 return self.magics_manager.magics['cell'].get(magic_name)
2246 return self.magics_manager.magics['cell'].get(magic_name)
2248
2247
2249 def find_magic(self, magic_name, magic_kind='line'):
2248 def find_magic(self, magic_name, magic_kind='line'):
2250 """Find and return a magic of the given type by name.
2249 """Find and return a magic of the given type by name.
2251
2250
2252 Returns None if the magic isn't found."""
2251 Returns None if the magic isn't found."""
2253 return self.magics_manager.magics[magic_kind].get(magic_name)
2252 return self.magics_manager.magics[magic_kind].get(magic_name)
2254
2253
2255 def magic(self, arg_s):
2254 def magic(self, arg_s):
2256 """DEPRECATED. Use run_line_magic() instead.
2255 """DEPRECATED. Use run_line_magic() instead.
2257
2256
2258 Call a magic function by name.
2257 Call a magic function by name.
2259
2258
2260 Input: a string containing the name of the magic function to call and
2259 Input: a string containing the name of the magic function to call and
2261 any additional arguments to be passed to the magic.
2260 any additional arguments to be passed to the magic.
2262
2261
2263 magic('name -opt foo bar') is equivalent to typing at the ipython
2262 magic('name -opt foo bar') is equivalent to typing at the ipython
2264 prompt:
2263 prompt:
2265
2264
2266 In[1]: %name -opt foo bar
2265 In[1]: %name -opt foo bar
2267
2266
2268 To call a magic without arguments, simply use magic('name').
2267 To call a magic without arguments, simply use magic('name').
2269
2268
2270 This provides a proper Python function to call IPython's magics in any
2269 This provides a proper Python function to call IPython's magics in any
2271 valid Python code you can type at the interpreter, including loops and
2270 valid Python code you can type at the interpreter, including loops and
2272 compound statements.
2271 compound statements.
2273 """
2272 """
2274 # TODO: should we issue a loud deprecation warning here?
2273 # TODO: should we issue a loud deprecation warning here?
2275 magic_name, _, magic_arg_s = arg_s.partition(' ')
2274 magic_name, _, magic_arg_s = arg_s.partition(' ')
2276 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2275 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2277 return self.run_line_magic(magic_name, magic_arg_s)
2276 return self.run_line_magic(magic_name, magic_arg_s)
2278
2277
2279 #-------------------------------------------------------------------------
2278 #-------------------------------------------------------------------------
2280 # Things related to macros
2279 # Things related to macros
2281 #-------------------------------------------------------------------------
2280 #-------------------------------------------------------------------------
2282
2281
2283 def define_macro(self, name, themacro):
2282 def define_macro(self, name, themacro):
2284 """Define a new macro
2283 """Define a new macro
2285
2284
2286 Parameters
2285 Parameters
2287 ----------
2286 ----------
2288 name : str
2287 name : str
2289 The name of the macro.
2288 The name of the macro.
2290 themacro : str or Macro
2289 themacro : str or Macro
2291 The action to do upon invoking the macro. If a string, a new
2290 The action to do upon invoking the macro. If a string, a new
2292 Macro object is created by passing the string to it.
2291 Macro object is created by passing the string to it.
2293 """
2292 """
2294
2293
2295 from IPython.core import macro
2294 from IPython.core import macro
2296
2295
2297 if isinstance(themacro, string_types):
2296 if isinstance(themacro, string_types):
2298 themacro = macro.Macro(themacro)
2297 themacro = macro.Macro(themacro)
2299 if not isinstance(themacro, macro.Macro):
2298 if not isinstance(themacro, macro.Macro):
2300 raise ValueError('A macro must be a string or a Macro instance.')
2299 raise ValueError('A macro must be a string or a Macro instance.')
2301 self.user_ns[name] = themacro
2300 self.user_ns[name] = themacro
2302
2301
2303 #-------------------------------------------------------------------------
2302 #-------------------------------------------------------------------------
2304 # Things related to the running of system commands
2303 # Things related to the running of system commands
2305 #-------------------------------------------------------------------------
2304 #-------------------------------------------------------------------------
2306
2305
2307 def system_piped(self, cmd):
2306 def system_piped(self, cmd):
2308 """Call the given cmd in a subprocess, piping stdout/err
2307 """Call the given cmd in a subprocess, piping stdout/err
2309
2308
2310 Parameters
2309 Parameters
2311 ----------
2310 ----------
2312 cmd : str
2311 cmd : str
2313 Command to execute (can not end in '&', as background processes are
2312 Command to execute (can not end in '&', as background processes are
2314 not supported. Should not be a command that expects input
2313 not supported. Should not be a command that expects input
2315 other than simple text.
2314 other than simple text.
2316 """
2315 """
2317 if cmd.rstrip().endswith('&'):
2316 if cmd.rstrip().endswith('&'):
2318 # this is *far* from a rigorous test
2317 # this is *far* from a rigorous test
2319 # We do not support backgrounding processes because we either use
2318 # We do not support backgrounding processes because we either use
2320 # pexpect or pipes to read from. Users can always just call
2319 # pexpect or pipes to read from. Users can always just call
2321 # os.system() or use ip.system=ip.system_raw
2320 # os.system() or use ip.system=ip.system_raw
2322 # if they really want a background process.
2321 # if they really want a background process.
2323 raise OSError("Background processes not supported.")
2322 raise OSError("Background processes not supported.")
2324
2323
2325 # we explicitly do NOT return the subprocess status code, because
2324 # we explicitly do NOT return the subprocess status code, because
2326 # a non-None value would trigger :func:`sys.displayhook` calls.
2325 # a non-None value would trigger :func:`sys.displayhook` calls.
2327 # Instead, we store the exit_code in user_ns.
2326 # Instead, we store the exit_code in user_ns.
2328 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2327 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2329
2328
2330 def system_raw(self, cmd):
2329 def system_raw(self, cmd):
2331 """Call the given cmd in a subprocess using os.system on Windows or
2330 """Call the given cmd in a subprocess using os.system on Windows or
2332 subprocess.call using the system shell on other platforms.
2331 subprocess.call using the system shell on other platforms.
2333
2332
2334 Parameters
2333 Parameters
2335 ----------
2334 ----------
2336 cmd : str
2335 cmd : str
2337 Command to execute.
2336 Command to execute.
2338 """
2337 """
2339 cmd = self.var_expand(cmd, depth=1)
2338 cmd = self.var_expand(cmd, depth=1)
2340 # protect os.system from UNC paths on Windows, which it can't handle:
2339 # protect os.system from UNC paths on Windows, which it can't handle:
2341 if sys.platform == 'win32':
2340 if sys.platform == 'win32':
2342 from IPython.utils._process_win32 import AvoidUNCPath
2341 from IPython.utils._process_win32 import AvoidUNCPath
2343 with AvoidUNCPath() as path:
2342 with AvoidUNCPath() as path:
2344 if path is not None:
2343 if path is not None:
2345 cmd = '"pushd %s &&"%s' % (path, cmd)
2344 cmd = '"pushd %s &&"%s' % (path, cmd)
2346 cmd = py3compat.unicode_to_str(cmd)
2345 cmd = py3compat.unicode_to_str(cmd)
2347 ec = os.system(cmd)
2346 ec = os.system(cmd)
2348 else:
2347 else:
2349 cmd = py3compat.unicode_to_str(cmd)
2348 cmd = py3compat.unicode_to_str(cmd)
2350 # Call the cmd using the OS shell, instead of the default /bin/sh, if set.
2349 # Call the cmd using the OS shell, instead of the default /bin/sh, if set.
2351 ec = subprocess.call(cmd, shell=True, executable=os.environ.get('SHELL', None))
2350 ec = subprocess.call(cmd, shell=True, executable=os.environ.get('SHELL', None))
2352 # exit code is positive for program failure, or negative for
2351 # exit code is positive for program failure, or negative for
2353 # terminating signal number.
2352 # terminating signal number.
2354
2353
2355 # Interpret ec > 128 as signal
2354 # Interpret ec > 128 as signal
2356 # Some shells (csh, fish) don't follow sh/bash conventions for exit codes
2355 # Some shells (csh, fish) don't follow sh/bash conventions for exit codes
2357 if ec > 128:
2356 if ec > 128:
2358 ec = -(ec - 128)
2357 ec = -(ec - 128)
2359
2358
2360 # We explicitly do NOT return the subprocess status code, because
2359 # We explicitly do NOT return the subprocess status code, because
2361 # a non-None value would trigger :func:`sys.displayhook` calls.
2360 # a non-None value would trigger :func:`sys.displayhook` calls.
2362 # Instead, we store the exit_code in user_ns.
2361 # Instead, we store the exit_code in user_ns.
2363 self.user_ns['_exit_code'] = ec
2362 self.user_ns['_exit_code'] = ec
2364
2363
2365 # use piped system by default, because it is better behaved
2364 # use piped system by default, because it is better behaved
2366 system = system_piped
2365 system = system_piped
2367
2366
2368 def getoutput(self, cmd, split=True, depth=0):
2367 def getoutput(self, cmd, split=True, depth=0):
2369 """Get output (possibly including stderr) from a subprocess.
2368 """Get output (possibly including stderr) from a subprocess.
2370
2369
2371 Parameters
2370 Parameters
2372 ----------
2371 ----------
2373 cmd : str
2372 cmd : str
2374 Command to execute (can not end in '&', as background processes are
2373 Command to execute (can not end in '&', as background processes are
2375 not supported.
2374 not supported.
2376 split : bool, optional
2375 split : bool, optional
2377 If True, split the output into an IPython SList. Otherwise, an
2376 If True, split the output into an IPython SList. Otherwise, an
2378 IPython LSString is returned. These are objects similar to normal
2377 IPython LSString is returned. These are objects similar to normal
2379 lists and strings, with a few convenience attributes for easier
2378 lists and strings, with a few convenience attributes for easier
2380 manipulation of line-based output. You can use '?' on them for
2379 manipulation of line-based output. You can use '?' on them for
2381 details.
2380 details.
2382 depth : int, optional
2381 depth : int, optional
2383 How many frames above the caller are the local variables which should
2382 How many frames above the caller are the local variables which should
2384 be expanded in the command string? The default (0) assumes that the
2383 be expanded in the command string? The default (0) assumes that the
2385 expansion variables are in the stack frame calling this function.
2384 expansion variables are in the stack frame calling this function.
2386 """
2385 """
2387 if cmd.rstrip().endswith('&'):
2386 if cmd.rstrip().endswith('&'):
2388 # this is *far* from a rigorous test
2387 # this is *far* from a rigorous test
2389 raise OSError("Background processes not supported.")
2388 raise OSError("Background processes not supported.")
2390 out = getoutput(self.var_expand(cmd, depth=depth+1))
2389 out = getoutput(self.var_expand(cmd, depth=depth+1))
2391 if split:
2390 if split:
2392 out = SList(out.splitlines())
2391 out = SList(out.splitlines())
2393 else:
2392 else:
2394 out = LSString(out)
2393 out = LSString(out)
2395 return out
2394 return out
2396
2395
2397 #-------------------------------------------------------------------------
2396 #-------------------------------------------------------------------------
2398 # Things related to aliases
2397 # Things related to aliases
2399 #-------------------------------------------------------------------------
2398 #-------------------------------------------------------------------------
2400
2399
2401 def init_alias(self):
2400 def init_alias(self):
2402 self.alias_manager = AliasManager(shell=self, parent=self)
2401 self.alias_manager = AliasManager(shell=self, parent=self)
2403 self.configurables.append(self.alias_manager)
2402 self.configurables.append(self.alias_manager)
2404
2403
2405 #-------------------------------------------------------------------------
2404 #-------------------------------------------------------------------------
2406 # Things related to extensions
2405 # Things related to extensions
2407 #-------------------------------------------------------------------------
2406 #-------------------------------------------------------------------------
2408
2407
2409 def init_extension_manager(self):
2408 def init_extension_manager(self):
2410 self.extension_manager = ExtensionManager(shell=self, parent=self)
2409 self.extension_manager = ExtensionManager(shell=self, parent=self)
2411 self.configurables.append(self.extension_manager)
2410 self.configurables.append(self.extension_manager)
2412
2411
2413 #-------------------------------------------------------------------------
2412 #-------------------------------------------------------------------------
2414 # Things related to payloads
2413 # Things related to payloads
2415 #-------------------------------------------------------------------------
2414 #-------------------------------------------------------------------------
2416
2415
2417 def init_payload(self):
2416 def init_payload(self):
2418 self.payload_manager = PayloadManager(parent=self)
2417 self.payload_manager = PayloadManager(parent=self)
2419 self.configurables.append(self.payload_manager)
2418 self.configurables.append(self.payload_manager)
2420
2419
2421 #-------------------------------------------------------------------------
2420 #-------------------------------------------------------------------------
2422 # Things related to widgets
2423 #-------------------------------------------------------------------------
2424
2425 def init_comms(self):
2426 # not implemented in the base class
2427 pass
2428
2429 #-------------------------------------------------------------------------
2430 # Things related to the prefilter
2421 # Things related to the prefilter
2431 #-------------------------------------------------------------------------
2422 #-------------------------------------------------------------------------
2432
2423
2433 def init_prefilter(self):
2424 def init_prefilter(self):
2434 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2425 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2435 self.configurables.append(self.prefilter_manager)
2426 self.configurables.append(self.prefilter_manager)
2436 # Ultimately this will be refactored in the new interpreter code, but
2427 # Ultimately this will be refactored in the new interpreter code, but
2437 # for now, we should expose the main prefilter method (there's legacy
2428 # for now, we should expose the main prefilter method (there's legacy
2438 # code out there that may rely on this).
2429 # code out there that may rely on this).
2439 self.prefilter = self.prefilter_manager.prefilter_lines
2430 self.prefilter = self.prefilter_manager.prefilter_lines
2440
2431
2441 def auto_rewrite_input(self, cmd):
2432 def auto_rewrite_input(self, cmd):
2442 """Print to the screen the rewritten form of the user's command.
2433 """Print to the screen the rewritten form of the user's command.
2443
2434
2444 This shows visual feedback by rewriting input lines that cause
2435 This shows visual feedback by rewriting input lines that cause
2445 automatic calling to kick in, like::
2436 automatic calling to kick in, like::
2446
2437
2447 /f x
2438 /f x
2448
2439
2449 into::
2440 into::
2450
2441
2451 ------> f(x)
2442 ------> f(x)
2452
2443
2453 after the user's input prompt. This helps the user understand that the
2444 after the user's input prompt. This helps the user understand that the
2454 input line was transformed automatically by IPython.
2445 input line was transformed automatically by IPython.
2455 """
2446 """
2456 if not self.show_rewritten_input:
2447 if not self.show_rewritten_input:
2457 return
2448 return
2458
2449
2459 rw = self.prompt_manager.render('rewrite') + cmd
2450 rw = self.prompt_manager.render('rewrite') + cmd
2460
2451
2461 try:
2452 try:
2462 # plain ascii works better w/ pyreadline, on some machines, so
2453 # plain ascii works better w/ pyreadline, on some machines, so
2463 # we use it and only print uncolored rewrite if we have unicode
2454 # we use it and only print uncolored rewrite if we have unicode
2464 rw = str(rw)
2455 rw = str(rw)
2465 print(rw, file=io.stdout)
2456 print(rw, file=io.stdout)
2466 except UnicodeEncodeError:
2457 except UnicodeEncodeError:
2467 print("------> " + cmd)
2458 print("------> " + cmd)
2468
2459
2469 #-------------------------------------------------------------------------
2460 #-------------------------------------------------------------------------
2470 # Things related to extracting values/expressions from kernel and user_ns
2461 # Things related to extracting values/expressions from kernel and user_ns
2471 #-------------------------------------------------------------------------
2462 #-------------------------------------------------------------------------
2472
2463
2473 def _user_obj_error(self):
2464 def _user_obj_error(self):
2474 """return simple exception dict
2465 """return simple exception dict
2475
2466
2476 for use in user_expressions
2467 for use in user_expressions
2477 """
2468 """
2478
2469
2479 etype, evalue, tb = self._get_exc_info()
2470 etype, evalue, tb = self._get_exc_info()
2480 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2471 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2481
2472
2482 exc_info = {
2473 exc_info = {
2483 u'status' : 'error',
2474 u'status' : 'error',
2484 u'traceback' : stb,
2475 u'traceback' : stb,
2485 u'ename' : unicode_type(etype.__name__),
2476 u'ename' : unicode_type(etype.__name__),
2486 u'evalue' : py3compat.safe_unicode(evalue),
2477 u'evalue' : py3compat.safe_unicode(evalue),
2487 }
2478 }
2488
2479
2489 return exc_info
2480 return exc_info
2490
2481
2491 def _format_user_obj(self, obj):
2482 def _format_user_obj(self, obj):
2492 """format a user object to display dict
2483 """format a user object to display dict
2493
2484
2494 for use in user_expressions
2485 for use in user_expressions
2495 """
2486 """
2496
2487
2497 data, md = self.display_formatter.format(obj)
2488 data, md = self.display_formatter.format(obj)
2498 value = {
2489 value = {
2499 'status' : 'ok',
2490 'status' : 'ok',
2500 'data' : data,
2491 'data' : data,
2501 'metadata' : md,
2492 'metadata' : md,
2502 }
2493 }
2503 return value
2494 return value
2504
2495
2505 def user_expressions(self, expressions):
2496 def user_expressions(self, expressions):
2506 """Evaluate a dict of expressions in the user's namespace.
2497 """Evaluate a dict of expressions in the user's namespace.
2507
2498
2508 Parameters
2499 Parameters
2509 ----------
2500 ----------
2510 expressions : dict
2501 expressions : dict
2511 A dict with string keys and string values. The expression values
2502 A dict with string keys and string values. The expression values
2512 should be valid Python expressions, each of which will be evaluated
2503 should be valid Python expressions, each of which will be evaluated
2513 in the user namespace.
2504 in the user namespace.
2514
2505
2515 Returns
2506 Returns
2516 -------
2507 -------
2517 A dict, keyed like the input expressions dict, with the rich mime-typed
2508 A dict, keyed like the input expressions dict, with the rich mime-typed
2518 display_data of each value.
2509 display_data of each value.
2519 """
2510 """
2520 out = {}
2511 out = {}
2521 user_ns = self.user_ns
2512 user_ns = self.user_ns
2522 global_ns = self.user_global_ns
2513 global_ns = self.user_global_ns
2523
2514
2524 for key, expr in iteritems(expressions):
2515 for key, expr in iteritems(expressions):
2525 try:
2516 try:
2526 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2517 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2527 except:
2518 except:
2528 value = self._user_obj_error()
2519 value = self._user_obj_error()
2529 out[key] = value
2520 out[key] = value
2530 return out
2521 return out
2531
2522
2532 #-------------------------------------------------------------------------
2523 #-------------------------------------------------------------------------
2533 # Things related to the running of code
2524 # Things related to the running of code
2534 #-------------------------------------------------------------------------
2525 #-------------------------------------------------------------------------
2535
2526
2536 def ex(self, cmd):
2527 def ex(self, cmd):
2537 """Execute a normal python statement in user namespace."""
2528 """Execute a normal python statement in user namespace."""
2538 with self.builtin_trap:
2529 with self.builtin_trap:
2539 exec(cmd, self.user_global_ns, self.user_ns)
2530 exec(cmd, self.user_global_ns, self.user_ns)
2540
2531
2541 def ev(self, expr):
2532 def ev(self, expr):
2542 """Evaluate python expression expr in user namespace.
2533 """Evaluate python expression expr in user namespace.
2543
2534
2544 Returns the result of evaluation
2535 Returns the result of evaluation
2545 """
2536 """
2546 with self.builtin_trap:
2537 with self.builtin_trap:
2547 return eval(expr, self.user_global_ns, self.user_ns)
2538 return eval(expr, self.user_global_ns, self.user_ns)
2548
2539
2549 def safe_execfile(self, fname, *where, **kw):
2540 def safe_execfile(self, fname, *where, **kw):
2550 """A safe version of the builtin execfile().
2541 """A safe version of the builtin execfile().
2551
2542
2552 This version will never throw an exception, but instead print
2543 This version will never throw an exception, but instead print
2553 helpful error messages to the screen. This only works on pure
2544 helpful error messages to the screen. This only works on pure
2554 Python files with the .py extension.
2545 Python files with the .py extension.
2555
2546
2556 Parameters
2547 Parameters
2557 ----------
2548 ----------
2558 fname : string
2549 fname : string
2559 The name of the file to be executed.
2550 The name of the file to be executed.
2560 where : tuple
2551 where : tuple
2561 One or two namespaces, passed to execfile() as (globals,locals).
2552 One or two namespaces, passed to execfile() as (globals,locals).
2562 If only one is given, it is passed as both.
2553 If only one is given, it is passed as both.
2563 exit_ignore : bool (False)
2554 exit_ignore : bool (False)
2564 If True, then silence SystemExit for non-zero status (it is always
2555 If True, then silence SystemExit for non-zero status (it is always
2565 silenced for zero status, as it is so common).
2556 silenced for zero status, as it is so common).
2566 raise_exceptions : bool (False)
2557 raise_exceptions : bool (False)
2567 If True raise exceptions everywhere. Meant for testing.
2558 If True raise exceptions everywhere. Meant for testing.
2568
2559
2569 """
2560 """
2570 kw.setdefault('exit_ignore', False)
2561 kw.setdefault('exit_ignore', False)
2571 kw.setdefault('raise_exceptions', False)
2562 kw.setdefault('raise_exceptions', False)
2572
2563
2573 fname = os.path.abspath(os.path.expanduser(fname))
2564 fname = os.path.abspath(os.path.expanduser(fname))
2574
2565
2575 # Make sure we can open the file
2566 # Make sure we can open the file
2576 try:
2567 try:
2577 with open(fname) as thefile:
2568 with open(fname) as thefile:
2578 pass
2569 pass
2579 except:
2570 except:
2580 warn('Could not open file <%s> for safe execution.' % fname)
2571 warn('Could not open file <%s> for safe execution.' % fname)
2581 return
2572 return
2582
2573
2583 # Find things also in current directory. This is needed to mimic the
2574 # Find things also in current directory. This is needed to mimic the
2584 # behavior of running a script from the system command line, where
2575 # behavior of running a script from the system command line, where
2585 # Python inserts the script's directory into sys.path
2576 # Python inserts the script's directory into sys.path
2586 dname = os.path.dirname(fname)
2577 dname = os.path.dirname(fname)
2587
2578
2588 with prepended_to_syspath(dname):
2579 with prepended_to_syspath(dname):
2589 try:
2580 try:
2590 py3compat.execfile(fname,*where)
2581 py3compat.execfile(fname,*where)
2591 except SystemExit as status:
2582 except SystemExit as status:
2592 # If the call was made with 0 or None exit status (sys.exit(0)
2583 # If the call was made with 0 or None exit status (sys.exit(0)
2593 # or sys.exit() ), don't bother showing a traceback, as both of
2584 # or sys.exit() ), don't bother showing a traceback, as both of
2594 # these are considered normal by the OS:
2585 # these are considered normal by the OS:
2595 # > python -c'import sys;sys.exit(0)'; echo $?
2586 # > python -c'import sys;sys.exit(0)'; echo $?
2596 # 0
2587 # 0
2597 # > python -c'import sys;sys.exit()'; echo $?
2588 # > python -c'import sys;sys.exit()'; echo $?
2598 # 0
2589 # 0
2599 # For other exit status, we show the exception unless
2590 # For other exit status, we show the exception unless
2600 # explicitly silenced, but only in short form.
2591 # explicitly silenced, but only in short form.
2601 if kw['raise_exceptions']:
2592 if kw['raise_exceptions']:
2602 raise
2593 raise
2603 if status.code and not kw['exit_ignore']:
2594 if status.code and not kw['exit_ignore']:
2604 self.showtraceback(exception_only=True)
2595 self.showtraceback(exception_only=True)
2605 except:
2596 except:
2606 if kw['raise_exceptions']:
2597 if kw['raise_exceptions']:
2607 raise
2598 raise
2608 # tb offset is 2 because we wrap execfile
2599 # tb offset is 2 because we wrap execfile
2609 self.showtraceback(tb_offset=2)
2600 self.showtraceback(tb_offset=2)
2610
2601
2611 def safe_execfile_ipy(self, fname):
2602 def safe_execfile_ipy(self, fname):
2612 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2603 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2613
2604
2614 Parameters
2605 Parameters
2615 ----------
2606 ----------
2616 fname : str
2607 fname : str
2617 The name of the file to execute. The filename must have a
2608 The name of the file to execute. The filename must have a
2618 .ipy or .ipynb extension.
2609 .ipy or .ipynb extension.
2619 """
2610 """
2620 fname = os.path.abspath(os.path.expanduser(fname))
2611 fname = os.path.abspath(os.path.expanduser(fname))
2621
2612
2622 # Make sure we can open the file
2613 # Make sure we can open the file
2623 try:
2614 try:
2624 with open(fname) as thefile:
2615 with open(fname) as thefile:
2625 pass
2616 pass
2626 except:
2617 except:
2627 warn('Could not open file <%s> for safe execution.' % fname)
2618 warn('Could not open file <%s> for safe execution.' % fname)
2628 return
2619 return
2629
2620
2630 # Find things also in current directory. This is needed to mimic the
2621 # Find things also in current directory. This is needed to mimic the
2631 # behavior of running a script from the system command line, where
2622 # behavior of running a script from the system command line, where
2632 # Python inserts the script's directory into sys.path
2623 # Python inserts the script's directory into sys.path
2633 dname = os.path.dirname(fname)
2624 dname = os.path.dirname(fname)
2634
2625
2635 def get_cells():
2626 def get_cells():
2636 """generator for sequence of code blocks to run"""
2627 """generator for sequence of code blocks to run"""
2637 if fname.endswith('.ipynb'):
2628 if fname.endswith('.ipynb'):
2638 from IPython.nbformat import current
2629 from IPython.nbformat import current
2639 with open(fname) as f:
2630 with open(fname) as f:
2640 nb = current.read(f, 'json')
2631 nb = current.read(f, 'json')
2641 if not nb.worksheets:
2632 if not nb.worksheets:
2642 return
2633 return
2643 for cell in nb.worksheets[0].cells:
2634 for cell in nb.worksheets[0].cells:
2644 if cell.cell_type == 'code':
2635 if cell.cell_type == 'code':
2645 yield cell.input
2636 yield cell.input
2646 else:
2637 else:
2647 with open(fname) as f:
2638 with open(fname) as f:
2648 yield f.read()
2639 yield f.read()
2649
2640
2650 with prepended_to_syspath(dname):
2641 with prepended_to_syspath(dname):
2651 try:
2642 try:
2652 for cell in get_cells():
2643 for cell in get_cells():
2653 # self.run_cell currently captures all exceptions
2644 # self.run_cell currently captures all exceptions
2654 # raised in user code. It would be nice if there were
2645 # raised in user code. It would be nice if there were
2655 # versions of run_cell that did raise, so
2646 # versions of run_cell that did raise, so
2656 # we could catch the errors.
2647 # we could catch the errors.
2657 self.run_cell(cell, silent=True, shell_futures=False)
2648 self.run_cell(cell, silent=True, shell_futures=False)
2658 except:
2649 except:
2659 self.showtraceback()
2650 self.showtraceback()
2660 warn('Unknown failure executing file: <%s>' % fname)
2651 warn('Unknown failure executing file: <%s>' % fname)
2661
2652
2662 def safe_run_module(self, mod_name, where):
2653 def safe_run_module(self, mod_name, where):
2663 """A safe version of runpy.run_module().
2654 """A safe version of runpy.run_module().
2664
2655
2665 This version will never throw an exception, but instead print
2656 This version will never throw an exception, but instead print
2666 helpful error messages to the screen.
2657 helpful error messages to the screen.
2667
2658
2668 `SystemExit` exceptions with status code 0 or None are ignored.
2659 `SystemExit` exceptions with status code 0 or None are ignored.
2669
2660
2670 Parameters
2661 Parameters
2671 ----------
2662 ----------
2672 mod_name : string
2663 mod_name : string
2673 The name of the module to be executed.
2664 The name of the module to be executed.
2674 where : dict
2665 where : dict
2675 The globals namespace.
2666 The globals namespace.
2676 """
2667 """
2677 try:
2668 try:
2678 try:
2669 try:
2679 where.update(
2670 where.update(
2680 runpy.run_module(str(mod_name), run_name="__main__",
2671 runpy.run_module(str(mod_name), run_name="__main__",
2681 alter_sys=True)
2672 alter_sys=True)
2682 )
2673 )
2683 except SystemExit as status:
2674 except SystemExit as status:
2684 if status.code:
2675 if status.code:
2685 raise
2676 raise
2686 except:
2677 except:
2687 self.showtraceback()
2678 self.showtraceback()
2688 warn('Unknown failure executing module: <%s>' % mod_name)
2679 warn('Unknown failure executing module: <%s>' % mod_name)
2689
2680
2690 def _run_cached_cell_magic(self, magic_name, line):
2681 def _run_cached_cell_magic(self, magic_name, line):
2691 """Special method to call a cell magic with the data stored in self.
2682 """Special method to call a cell magic with the data stored in self.
2692 """
2683 """
2693 cell = self._current_cell_magic_body
2684 cell = self._current_cell_magic_body
2694 self._current_cell_magic_body = None
2685 self._current_cell_magic_body = None
2695 return self.run_cell_magic(magic_name, line, cell)
2686 return self.run_cell_magic(magic_name, line, cell)
2696
2687
2697 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2688 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2698 """Run a complete IPython cell.
2689 """Run a complete IPython cell.
2699
2690
2700 Parameters
2691 Parameters
2701 ----------
2692 ----------
2702 raw_cell : str
2693 raw_cell : str
2703 The code (including IPython code such as %magic functions) to run.
2694 The code (including IPython code such as %magic functions) to run.
2704 store_history : bool
2695 store_history : bool
2705 If True, the raw and translated cell will be stored in IPython's
2696 If True, the raw and translated cell will be stored in IPython's
2706 history. For user code calling back into IPython's machinery, this
2697 history. For user code calling back into IPython's machinery, this
2707 should be set to False.
2698 should be set to False.
2708 silent : bool
2699 silent : bool
2709 If True, avoid side-effects, such as implicit displayhooks and
2700 If True, avoid side-effects, such as implicit displayhooks and
2710 and logging. silent=True forces store_history=False.
2701 and logging. silent=True forces store_history=False.
2711 shell_futures : bool
2702 shell_futures : bool
2712 If True, the code will share future statements with the interactive
2703 If True, the code will share future statements with the interactive
2713 shell. It will both be affected by previous __future__ imports, and
2704 shell. It will both be affected by previous __future__ imports, and
2714 any __future__ imports in the code will affect the shell. If False,
2705 any __future__ imports in the code will affect the shell. If False,
2715 __future__ imports are not shared in either direction.
2706 __future__ imports are not shared in either direction.
2716 """
2707 """
2717 if (not raw_cell) or raw_cell.isspace():
2708 if (not raw_cell) or raw_cell.isspace():
2718 return
2709 return
2719
2710
2720 if silent:
2711 if silent:
2721 store_history = False
2712 store_history = False
2722
2713
2723 self.events.trigger('pre_execute')
2714 self.events.trigger('pre_execute')
2724 if not silent:
2715 if not silent:
2725 self.events.trigger('pre_run_cell')
2716 self.events.trigger('pre_run_cell')
2726
2717
2727 # If any of our input transformation (input_transformer_manager or
2718 # If any of our input transformation (input_transformer_manager or
2728 # prefilter_manager) raises an exception, we store it in this variable
2719 # prefilter_manager) raises an exception, we store it in this variable
2729 # so that we can display the error after logging the input and storing
2720 # so that we can display the error after logging the input and storing
2730 # it in the history.
2721 # it in the history.
2731 preprocessing_exc_tuple = None
2722 preprocessing_exc_tuple = None
2732 try:
2723 try:
2733 # Static input transformations
2724 # Static input transformations
2734 cell = self.input_transformer_manager.transform_cell(raw_cell)
2725 cell = self.input_transformer_manager.transform_cell(raw_cell)
2735 except SyntaxError:
2726 except SyntaxError:
2736 preprocessing_exc_tuple = sys.exc_info()
2727 preprocessing_exc_tuple = sys.exc_info()
2737 cell = raw_cell # cell has to exist so it can be stored/logged
2728 cell = raw_cell # cell has to exist so it can be stored/logged
2738 else:
2729 else:
2739 if len(cell.splitlines()) == 1:
2730 if len(cell.splitlines()) == 1:
2740 # Dynamic transformations - only applied for single line commands
2731 # Dynamic transformations - only applied for single line commands
2741 with self.builtin_trap:
2732 with self.builtin_trap:
2742 try:
2733 try:
2743 # use prefilter_lines to handle trailing newlines
2734 # use prefilter_lines to handle trailing newlines
2744 # restore trailing newline for ast.parse
2735 # restore trailing newline for ast.parse
2745 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2736 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2746 except Exception:
2737 except Exception:
2747 # don't allow prefilter errors to crash IPython
2738 # don't allow prefilter errors to crash IPython
2748 preprocessing_exc_tuple = sys.exc_info()
2739 preprocessing_exc_tuple = sys.exc_info()
2749
2740
2750 # Store raw and processed history
2741 # Store raw and processed history
2751 if store_history:
2742 if store_history:
2752 self.history_manager.store_inputs(self.execution_count,
2743 self.history_manager.store_inputs(self.execution_count,
2753 cell, raw_cell)
2744 cell, raw_cell)
2754 if not silent:
2745 if not silent:
2755 self.logger.log(cell, raw_cell)
2746 self.logger.log(cell, raw_cell)
2756
2747
2757 # Display the exception if input processing failed.
2748 # Display the exception if input processing failed.
2758 if preprocessing_exc_tuple is not None:
2749 if preprocessing_exc_tuple is not None:
2759 self.showtraceback(preprocessing_exc_tuple)
2750 self.showtraceback(preprocessing_exc_tuple)
2760 if store_history:
2751 if store_history:
2761 self.execution_count += 1
2752 self.execution_count += 1
2762 return
2753 return
2763
2754
2764 # Our own compiler remembers the __future__ environment. If we want to
2755 # Our own compiler remembers the __future__ environment. If we want to
2765 # run code with a separate __future__ environment, use the default
2756 # run code with a separate __future__ environment, use the default
2766 # compiler
2757 # compiler
2767 compiler = self.compile if shell_futures else CachingCompiler()
2758 compiler = self.compile if shell_futures else CachingCompiler()
2768
2759
2769 with self.builtin_trap:
2760 with self.builtin_trap:
2770 cell_name = self.compile.cache(cell, self.execution_count)
2761 cell_name = self.compile.cache(cell, self.execution_count)
2771
2762
2772 with self.display_trap:
2763 with self.display_trap:
2773 # Compile to bytecode
2764 # Compile to bytecode
2774 try:
2765 try:
2775 code_ast = compiler.ast_parse(cell, filename=cell_name)
2766 code_ast = compiler.ast_parse(cell, filename=cell_name)
2776 except IndentationError:
2767 except IndentationError:
2777 self.showindentationerror()
2768 self.showindentationerror()
2778 if store_history:
2769 if store_history:
2779 self.execution_count += 1
2770 self.execution_count += 1
2780 return None
2771 return None
2781 except (OverflowError, SyntaxError, ValueError, TypeError,
2772 except (OverflowError, SyntaxError, ValueError, TypeError,
2782 MemoryError):
2773 MemoryError):
2783 self.showsyntaxerror()
2774 self.showsyntaxerror()
2784 if store_history:
2775 if store_history:
2785 self.execution_count += 1
2776 self.execution_count += 1
2786 return None
2777 return None
2787
2778
2788 # Apply AST transformations
2779 # Apply AST transformations
2789 try:
2780 try:
2790 code_ast = self.transform_ast(code_ast)
2781 code_ast = self.transform_ast(code_ast)
2791 except InputRejected:
2782 except InputRejected:
2792 self.showtraceback()
2783 self.showtraceback()
2793 if store_history:
2784 if store_history:
2794 self.execution_count += 1
2785 self.execution_count += 1
2795 return None
2786 return None
2796
2787
2797 # Execute the user code
2788 # Execute the user code
2798 interactivity = "none" if silent else self.ast_node_interactivity
2789 interactivity = "none" if silent else self.ast_node_interactivity
2799 self.run_ast_nodes(code_ast.body, cell_name,
2790 self.run_ast_nodes(code_ast.body, cell_name,
2800 interactivity=interactivity, compiler=compiler)
2791 interactivity=interactivity, compiler=compiler)
2801
2792
2802 self.events.trigger('post_execute')
2793 self.events.trigger('post_execute')
2803 if not silent:
2794 if not silent:
2804 self.events.trigger('post_run_cell')
2795 self.events.trigger('post_run_cell')
2805
2796
2806 if store_history:
2797 if store_history:
2807 # Write output to the database. Does nothing unless
2798 # Write output to the database. Does nothing unless
2808 # history output logging is enabled.
2799 # history output logging is enabled.
2809 self.history_manager.store_output(self.execution_count)
2800 self.history_manager.store_output(self.execution_count)
2810 # Each cell is a *single* input, regardless of how many lines it has
2801 # Each cell is a *single* input, regardless of how many lines it has
2811 self.execution_count += 1
2802 self.execution_count += 1
2812
2803
2813 def transform_ast(self, node):
2804 def transform_ast(self, node):
2814 """Apply the AST transformations from self.ast_transformers
2805 """Apply the AST transformations from self.ast_transformers
2815
2806
2816 Parameters
2807 Parameters
2817 ----------
2808 ----------
2818 node : ast.Node
2809 node : ast.Node
2819 The root node to be transformed. Typically called with the ast.Module
2810 The root node to be transformed. Typically called with the ast.Module
2820 produced by parsing user input.
2811 produced by parsing user input.
2821
2812
2822 Returns
2813 Returns
2823 -------
2814 -------
2824 An ast.Node corresponding to the node it was called with. Note that it
2815 An ast.Node corresponding to the node it was called with. Note that it
2825 may also modify the passed object, so don't rely on references to the
2816 may also modify the passed object, so don't rely on references to the
2826 original AST.
2817 original AST.
2827 """
2818 """
2828 for transformer in self.ast_transformers:
2819 for transformer in self.ast_transformers:
2829 try:
2820 try:
2830 node = transformer.visit(node)
2821 node = transformer.visit(node)
2831 except InputRejected:
2822 except InputRejected:
2832 # User-supplied AST transformers can reject an input by raising
2823 # User-supplied AST transformers can reject an input by raising
2833 # an InputRejected. Short-circuit in this case so that we
2824 # an InputRejected. Short-circuit in this case so that we
2834 # don't unregister the transform.
2825 # don't unregister the transform.
2835 raise
2826 raise
2836 except Exception:
2827 except Exception:
2837 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2828 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2838 self.ast_transformers.remove(transformer)
2829 self.ast_transformers.remove(transformer)
2839
2830
2840 if self.ast_transformers:
2831 if self.ast_transformers:
2841 ast.fix_missing_locations(node)
2832 ast.fix_missing_locations(node)
2842 return node
2833 return node
2843
2834
2844
2835
2845 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2836 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2846 compiler=compile):
2837 compiler=compile):
2847 """Run a sequence of AST nodes. The execution mode depends on the
2838 """Run a sequence of AST nodes. The execution mode depends on the
2848 interactivity parameter.
2839 interactivity parameter.
2849
2840
2850 Parameters
2841 Parameters
2851 ----------
2842 ----------
2852 nodelist : list
2843 nodelist : list
2853 A sequence of AST nodes to run.
2844 A sequence of AST nodes to run.
2854 cell_name : str
2845 cell_name : str
2855 Will be passed to the compiler as the filename of the cell. Typically
2846 Will be passed to the compiler as the filename of the cell. Typically
2856 the value returned by ip.compile.cache(cell).
2847 the value returned by ip.compile.cache(cell).
2857 interactivity : str
2848 interactivity : str
2858 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2849 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2859 run interactively (displaying output from expressions). 'last_expr'
2850 run interactively (displaying output from expressions). 'last_expr'
2860 will run the last node interactively only if it is an expression (i.e.
2851 will run the last node interactively only if it is an expression (i.e.
2861 expressions in loops or other blocks are not displayed. Other values
2852 expressions in loops or other blocks are not displayed. Other values
2862 for this parameter will raise a ValueError.
2853 for this parameter will raise a ValueError.
2863 compiler : callable
2854 compiler : callable
2864 A function with the same interface as the built-in compile(), to turn
2855 A function with the same interface as the built-in compile(), to turn
2865 the AST nodes into code objects. Default is the built-in compile().
2856 the AST nodes into code objects. Default is the built-in compile().
2866 """
2857 """
2867 if not nodelist:
2858 if not nodelist:
2868 return
2859 return
2869
2860
2870 if interactivity == 'last_expr':
2861 if interactivity == 'last_expr':
2871 if isinstance(nodelist[-1], ast.Expr):
2862 if isinstance(nodelist[-1], ast.Expr):
2872 interactivity = "last"
2863 interactivity = "last"
2873 else:
2864 else:
2874 interactivity = "none"
2865 interactivity = "none"
2875
2866
2876 if interactivity == 'none':
2867 if interactivity == 'none':
2877 to_run_exec, to_run_interactive = nodelist, []
2868 to_run_exec, to_run_interactive = nodelist, []
2878 elif interactivity == 'last':
2869 elif interactivity == 'last':
2879 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2870 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2880 elif interactivity == 'all':
2871 elif interactivity == 'all':
2881 to_run_exec, to_run_interactive = [], nodelist
2872 to_run_exec, to_run_interactive = [], nodelist
2882 else:
2873 else:
2883 raise ValueError("Interactivity was %r" % interactivity)
2874 raise ValueError("Interactivity was %r" % interactivity)
2884
2875
2885 exec_count = self.execution_count
2876 exec_count = self.execution_count
2886
2877
2887 try:
2878 try:
2888 for i, node in enumerate(to_run_exec):
2879 for i, node in enumerate(to_run_exec):
2889 mod = ast.Module([node])
2880 mod = ast.Module([node])
2890 code = compiler(mod, cell_name, "exec")
2881 code = compiler(mod, cell_name, "exec")
2891 if self.run_code(code):
2882 if self.run_code(code):
2892 return True
2883 return True
2893
2884
2894 for i, node in enumerate(to_run_interactive):
2885 for i, node in enumerate(to_run_interactive):
2895 mod = ast.Interactive([node])
2886 mod = ast.Interactive([node])
2896 code = compiler(mod, cell_name, "single")
2887 code = compiler(mod, cell_name, "single")
2897 if self.run_code(code):
2888 if self.run_code(code):
2898 return True
2889 return True
2899
2890
2900 # Flush softspace
2891 # Flush softspace
2901 if softspace(sys.stdout, 0):
2892 if softspace(sys.stdout, 0):
2902 print()
2893 print()
2903
2894
2904 except:
2895 except:
2905 # It's possible to have exceptions raised here, typically by
2896 # It's possible to have exceptions raised here, typically by
2906 # compilation of odd code (such as a naked 'return' outside a
2897 # compilation of odd code (such as a naked 'return' outside a
2907 # function) that did parse but isn't valid. Typically the exception
2898 # function) that did parse but isn't valid. Typically the exception
2908 # is a SyntaxError, but it's safest just to catch anything and show
2899 # is a SyntaxError, but it's safest just to catch anything and show
2909 # the user a traceback.
2900 # the user a traceback.
2910
2901
2911 # We do only one try/except outside the loop to minimize the impact
2902 # We do only one try/except outside the loop to minimize the impact
2912 # on runtime, and also because if any node in the node list is
2903 # on runtime, and also because if any node in the node list is
2913 # broken, we should stop execution completely.
2904 # broken, we should stop execution completely.
2914 self.showtraceback()
2905 self.showtraceback()
2915
2906
2916 return False
2907 return False
2917
2908
2918 def run_code(self, code_obj):
2909 def run_code(self, code_obj):
2919 """Execute a code object.
2910 """Execute a code object.
2920
2911
2921 When an exception occurs, self.showtraceback() is called to display a
2912 When an exception occurs, self.showtraceback() is called to display a
2922 traceback.
2913 traceback.
2923
2914
2924 Parameters
2915 Parameters
2925 ----------
2916 ----------
2926 code_obj : code object
2917 code_obj : code object
2927 A compiled code object, to be executed
2918 A compiled code object, to be executed
2928
2919
2929 Returns
2920 Returns
2930 -------
2921 -------
2931 False : successful execution.
2922 False : successful execution.
2932 True : an error occurred.
2923 True : an error occurred.
2933 """
2924 """
2934 # Set our own excepthook in case the user code tries to call it
2925 # Set our own excepthook in case the user code tries to call it
2935 # directly, so that the IPython crash handler doesn't get triggered
2926 # directly, so that the IPython crash handler doesn't get triggered
2936 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2927 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2937
2928
2938 # we save the original sys.excepthook in the instance, in case config
2929 # we save the original sys.excepthook in the instance, in case config
2939 # code (such as magics) needs access to it.
2930 # code (such as magics) needs access to it.
2940 self.sys_excepthook = old_excepthook
2931 self.sys_excepthook = old_excepthook
2941 outflag = 1 # happens in more places, so it's easier as default
2932 outflag = 1 # happens in more places, so it's easier as default
2942 try:
2933 try:
2943 try:
2934 try:
2944 self.hooks.pre_run_code_hook()
2935 self.hooks.pre_run_code_hook()
2945 #rprint('Running code', repr(code_obj)) # dbg
2936 #rprint('Running code', repr(code_obj)) # dbg
2946 exec(code_obj, self.user_global_ns, self.user_ns)
2937 exec(code_obj, self.user_global_ns, self.user_ns)
2947 finally:
2938 finally:
2948 # Reset our crash handler in place
2939 # Reset our crash handler in place
2949 sys.excepthook = old_excepthook
2940 sys.excepthook = old_excepthook
2950 except SystemExit:
2941 except SystemExit:
2951 self.showtraceback(exception_only=True)
2942 self.showtraceback(exception_only=True)
2952 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2943 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2953 except self.custom_exceptions:
2944 except self.custom_exceptions:
2954 etype, value, tb = sys.exc_info()
2945 etype, value, tb = sys.exc_info()
2955 self.CustomTB(etype, value, tb)
2946 self.CustomTB(etype, value, tb)
2956 except:
2947 except:
2957 self.showtraceback()
2948 self.showtraceback()
2958 else:
2949 else:
2959 outflag = 0
2950 outflag = 0
2960 return outflag
2951 return outflag
2961
2952
2962 # For backwards compatibility
2953 # For backwards compatibility
2963 runcode = run_code
2954 runcode = run_code
2964
2955
2965 #-------------------------------------------------------------------------
2956 #-------------------------------------------------------------------------
2966 # Things related to GUI support and pylab
2957 # Things related to GUI support and pylab
2967 #-------------------------------------------------------------------------
2958 #-------------------------------------------------------------------------
2968
2959
2969 def enable_gui(self, gui=None):
2960 def enable_gui(self, gui=None):
2970 raise NotImplementedError('Implement enable_gui in a subclass')
2961 raise NotImplementedError('Implement enable_gui in a subclass')
2971
2962
2972 def enable_matplotlib(self, gui=None):
2963 def enable_matplotlib(self, gui=None):
2973 """Enable interactive matplotlib and inline figure support.
2964 """Enable interactive matplotlib and inline figure support.
2974
2965
2975 This takes the following steps:
2966 This takes the following steps:
2976
2967
2977 1. select the appropriate eventloop and matplotlib backend
2968 1. select the appropriate eventloop and matplotlib backend
2978 2. set up matplotlib for interactive use with that backend
2969 2. set up matplotlib for interactive use with that backend
2979 3. configure formatters for inline figure display
2970 3. configure formatters for inline figure display
2980 4. enable the selected gui eventloop
2971 4. enable the selected gui eventloop
2981
2972
2982 Parameters
2973 Parameters
2983 ----------
2974 ----------
2984 gui : optional, string
2975 gui : optional, string
2985 If given, dictates the choice of matplotlib GUI backend to use
2976 If given, dictates the choice of matplotlib GUI backend to use
2986 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2977 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2987 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2978 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2988 matplotlib (as dictated by the matplotlib build-time options plus the
2979 matplotlib (as dictated by the matplotlib build-time options plus the
2989 user's matplotlibrc configuration file). Note that not all backends
2980 user's matplotlibrc configuration file). Note that not all backends
2990 make sense in all contexts, for example a terminal ipython can't
2981 make sense in all contexts, for example a terminal ipython can't
2991 display figures inline.
2982 display figures inline.
2992 """
2983 """
2993 from IPython.core import pylabtools as pt
2984 from IPython.core import pylabtools as pt
2994 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2985 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2995
2986
2996 if gui != 'inline':
2987 if gui != 'inline':
2997 # If we have our first gui selection, store it
2988 # If we have our first gui selection, store it
2998 if self.pylab_gui_select is None:
2989 if self.pylab_gui_select is None:
2999 self.pylab_gui_select = gui
2990 self.pylab_gui_select = gui
3000 # Otherwise if they are different
2991 # Otherwise if they are different
3001 elif gui != self.pylab_gui_select:
2992 elif gui != self.pylab_gui_select:
3002 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2993 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3003 ' Using %s instead.' % (gui, self.pylab_gui_select))
2994 ' Using %s instead.' % (gui, self.pylab_gui_select))
3004 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2995 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3005
2996
3006 pt.activate_matplotlib(backend)
2997 pt.activate_matplotlib(backend)
3007 pt.configure_inline_support(self, backend)
2998 pt.configure_inline_support(self, backend)
3008
2999
3009 # Now we must activate the gui pylab wants to use, and fix %run to take
3000 # Now we must activate the gui pylab wants to use, and fix %run to take
3010 # plot updates into account
3001 # plot updates into account
3011 self.enable_gui(gui)
3002 self.enable_gui(gui)
3012 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3003 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3013 pt.mpl_runner(self.safe_execfile)
3004 pt.mpl_runner(self.safe_execfile)
3014
3005
3015 return gui, backend
3006 return gui, backend
3016
3007
3017 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3008 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3018 """Activate pylab support at runtime.
3009 """Activate pylab support at runtime.
3019
3010
3020 This turns on support for matplotlib, preloads into the interactive
3011 This turns on support for matplotlib, preloads into the interactive
3021 namespace all of numpy and pylab, and configures IPython to correctly
3012 namespace all of numpy and pylab, and configures IPython to correctly
3022 interact with the GUI event loop. The GUI backend to be used can be
3013 interact with the GUI event loop. The GUI backend to be used can be
3023 optionally selected with the optional ``gui`` argument.
3014 optionally selected with the optional ``gui`` argument.
3024
3015
3025 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3016 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3026
3017
3027 Parameters
3018 Parameters
3028 ----------
3019 ----------
3029 gui : optional, string
3020 gui : optional, string
3030 If given, dictates the choice of matplotlib GUI backend to use
3021 If given, dictates the choice of matplotlib GUI backend to use
3031 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3022 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3032 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3023 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3033 matplotlib (as dictated by the matplotlib build-time options plus the
3024 matplotlib (as dictated by the matplotlib build-time options plus the
3034 user's matplotlibrc configuration file). Note that not all backends
3025 user's matplotlibrc configuration file). Note that not all backends
3035 make sense in all contexts, for example a terminal ipython can't
3026 make sense in all contexts, for example a terminal ipython can't
3036 display figures inline.
3027 display figures inline.
3037 import_all : optional, bool, default: True
3028 import_all : optional, bool, default: True
3038 Whether to do `from numpy import *` and `from pylab import *`
3029 Whether to do `from numpy import *` and `from pylab import *`
3039 in addition to module imports.
3030 in addition to module imports.
3040 welcome_message : deprecated
3031 welcome_message : deprecated
3041 This argument is ignored, no welcome message will be displayed.
3032 This argument is ignored, no welcome message will be displayed.
3042 """
3033 """
3043 from IPython.core.pylabtools import import_pylab
3034 from IPython.core.pylabtools import import_pylab
3044
3035
3045 gui, backend = self.enable_matplotlib(gui)
3036 gui, backend = self.enable_matplotlib(gui)
3046
3037
3047 # We want to prevent the loading of pylab to pollute the user's
3038 # We want to prevent the loading of pylab to pollute the user's
3048 # namespace as shown by the %who* magics, so we execute the activation
3039 # namespace as shown by the %who* magics, so we execute the activation
3049 # code in an empty namespace, and we update *both* user_ns and
3040 # code in an empty namespace, and we update *both* user_ns and
3050 # user_ns_hidden with this information.
3041 # user_ns_hidden with this information.
3051 ns = {}
3042 ns = {}
3052 import_pylab(ns, import_all)
3043 import_pylab(ns, import_all)
3053 # warn about clobbered names
3044 # warn about clobbered names
3054 ignored = set(["__builtins__"])
3045 ignored = set(["__builtins__"])
3055 both = set(ns).intersection(self.user_ns).difference(ignored)
3046 both = set(ns).intersection(self.user_ns).difference(ignored)
3056 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3047 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3057 self.user_ns.update(ns)
3048 self.user_ns.update(ns)
3058 self.user_ns_hidden.update(ns)
3049 self.user_ns_hidden.update(ns)
3059 return gui, backend, clobbered
3050 return gui, backend, clobbered
3060
3051
3061 #-------------------------------------------------------------------------
3052 #-------------------------------------------------------------------------
3062 # Utilities
3053 # Utilities
3063 #-------------------------------------------------------------------------
3054 #-------------------------------------------------------------------------
3064
3055
3065 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3056 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3066 """Expand python variables in a string.
3057 """Expand python variables in a string.
3067
3058
3068 The depth argument indicates how many frames above the caller should
3059 The depth argument indicates how many frames above the caller should
3069 be walked to look for the local namespace where to expand variables.
3060 be walked to look for the local namespace where to expand variables.
3070
3061
3071 The global namespace for expansion is always the user's interactive
3062 The global namespace for expansion is always the user's interactive
3072 namespace.
3063 namespace.
3073 """
3064 """
3074 ns = self.user_ns.copy()
3065 ns = self.user_ns.copy()
3075 ns.update(sys._getframe(depth+1).f_locals)
3066 ns.update(sys._getframe(depth+1).f_locals)
3076 try:
3067 try:
3077 # We have to use .vformat() here, because 'self' is a valid and common
3068 # We have to use .vformat() here, because 'self' is a valid and common
3078 # name, and expanding **ns for .format() would make it collide with
3069 # name, and expanding **ns for .format() would make it collide with
3079 # the 'self' argument of the method.
3070 # the 'self' argument of the method.
3080 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3071 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3081 except Exception:
3072 except Exception:
3082 # if formatter couldn't format, just let it go untransformed
3073 # if formatter couldn't format, just let it go untransformed
3083 pass
3074 pass
3084 return cmd
3075 return cmd
3085
3076
3086 def mktempfile(self, data=None, prefix='ipython_edit_'):
3077 def mktempfile(self, data=None, prefix='ipython_edit_'):
3087 """Make a new tempfile and return its filename.
3078 """Make a new tempfile and return its filename.
3088
3079
3089 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3080 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3090 but it registers the created filename internally so ipython cleans it up
3081 but it registers the created filename internally so ipython cleans it up
3091 at exit time.
3082 at exit time.
3092
3083
3093 Optional inputs:
3084 Optional inputs:
3094
3085
3095 - data(None): if data is given, it gets written out to the temp file
3086 - data(None): if data is given, it gets written out to the temp file
3096 immediately, and the file is closed again."""
3087 immediately, and the file is closed again."""
3097
3088
3098 dirname = tempfile.mkdtemp(prefix=prefix)
3089 dirname = tempfile.mkdtemp(prefix=prefix)
3099 self.tempdirs.append(dirname)
3090 self.tempdirs.append(dirname)
3100
3091
3101 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3092 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3102 os.close(handle) # On Windows, there can only be one open handle on a file
3093 os.close(handle) # On Windows, there can only be one open handle on a file
3103 self.tempfiles.append(filename)
3094 self.tempfiles.append(filename)
3104
3095
3105 if data:
3096 if data:
3106 tmp_file = open(filename,'w')
3097 tmp_file = open(filename,'w')
3107 tmp_file.write(data)
3098 tmp_file.write(data)
3108 tmp_file.close()
3099 tmp_file.close()
3109 return filename
3100 return filename
3110
3101
3111 # TODO: This should be removed when Term is refactored.
3102 # TODO: This should be removed when Term is refactored.
3112 def write(self,data):
3103 def write(self,data):
3113 """Write a string to the default output"""
3104 """Write a string to the default output"""
3114 io.stdout.write(data)
3105 io.stdout.write(data)
3115
3106
3116 # TODO: This should be removed when Term is refactored.
3107 # TODO: This should be removed when Term is refactored.
3117 def write_err(self,data):
3108 def write_err(self,data):
3118 """Write a string to the default error output"""
3109 """Write a string to the default error output"""
3119 io.stderr.write(data)
3110 io.stderr.write(data)
3120
3111
3121 def ask_yes_no(self, prompt, default=None):
3112 def ask_yes_no(self, prompt, default=None):
3122 if self.quiet:
3113 if self.quiet:
3123 return True
3114 return True
3124 return ask_yes_no(prompt,default)
3115 return ask_yes_no(prompt,default)
3125
3116
3126 def show_usage(self):
3117 def show_usage(self):
3127 """Show a usage message"""
3118 """Show a usage message"""
3128 page.page(IPython.core.usage.interactive_usage)
3119 page.page(IPython.core.usage.interactive_usage)
3129
3120
3130 def extract_input_lines(self, range_str, raw=False):
3121 def extract_input_lines(self, range_str, raw=False):
3131 """Return as a string a set of input history slices.
3122 """Return as a string a set of input history slices.
3132
3123
3133 Parameters
3124 Parameters
3134 ----------
3125 ----------
3135 range_str : string
3126 range_str : string
3136 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3127 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3137 since this function is for use by magic functions which get their
3128 since this function is for use by magic functions which get their
3138 arguments as strings. The number before the / is the session
3129 arguments as strings. The number before the / is the session
3139 number: ~n goes n back from the current session.
3130 number: ~n goes n back from the current session.
3140
3131
3141 raw : bool, optional
3132 raw : bool, optional
3142 By default, the processed input is used. If this is true, the raw
3133 By default, the processed input is used. If this is true, the raw
3143 input history is used instead.
3134 input history is used instead.
3144
3135
3145 Notes
3136 Notes
3146 -----
3137 -----
3147
3138
3148 Slices can be described with two notations:
3139 Slices can be described with two notations:
3149
3140
3150 * ``N:M`` -> standard python form, means including items N...(M-1).
3141 * ``N:M`` -> standard python form, means including items N...(M-1).
3151 * ``N-M`` -> include items N..M (closed endpoint).
3142 * ``N-M`` -> include items N..M (closed endpoint).
3152 """
3143 """
3153 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3144 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3154 return "\n".join(x for _, _, x in lines)
3145 return "\n".join(x for _, _, x in lines)
3155
3146
3156 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3147 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3157 """Get a code string from history, file, url, or a string or macro.
3148 """Get a code string from history, file, url, or a string or macro.
3158
3149
3159 This is mainly used by magic functions.
3150 This is mainly used by magic functions.
3160
3151
3161 Parameters
3152 Parameters
3162 ----------
3153 ----------
3163
3154
3164 target : str
3155 target : str
3165
3156
3166 A string specifying code to retrieve. This will be tried respectively
3157 A string specifying code to retrieve. This will be tried respectively
3167 as: ranges of input history (see %history for syntax), url,
3158 as: ranges of input history (see %history for syntax), url,
3168 correspnding .py file, filename, or an expression evaluating to a
3159 correspnding .py file, filename, or an expression evaluating to a
3169 string or Macro in the user namespace.
3160 string or Macro in the user namespace.
3170
3161
3171 raw : bool
3162 raw : bool
3172 If true (default), retrieve raw history. Has no effect on the other
3163 If true (default), retrieve raw history. Has no effect on the other
3173 retrieval mechanisms.
3164 retrieval mechanisms.
3174
3165
3175 py_only : bool (default False)
3166 py_only : bool (default False)
3176 Only try to fetch python code, do not try alternative methods to decode file
3167 Only try to fetch python code, do not try alternative methods to decode file
3177 if unicode fails.
3168 if unicode fails.
3178
3169
3179 Returns
3170 Returns
3180 -------
3171 -------
3181 A string of code.
3172 A string of code.
3182
3173
3183 ValueError is raised if nothing is found, and TypeError if it evaluates
3174 ValueError is raised if nothing is found, and TypeError if it evaluates
3184 to an object of another type. In each case, .args[0] is a printable
3175 to an object of another type. In each case, .args[0] is a printable
3185 message.
3176 message.
3186 """
3177 """
3187 code = self.extract_input_lines(target, raw=raw) # Grab history
3178 code = self.extract_input_lines(target, raw=raw) # Grab history
3188 if code:
3179 if code:
3189 return code
3180 return code
3190 utarget = unquote_filename(target)
3181 utarget = unquote_filename(target)
3191 try:
3182 try:
3192 if utarget.startswith(('http://', 'https://')):
3183 if utarget.startswith(('http://', 'https://')):
3193 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3184 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3194 except UnicodeDecodeError:
3185 except UnicodeDecodeError:
3195 if not py_only :
3186 if not py_only :
3196 # Deferred import
3187 # Deferred import
3197 try:
3188 try:
3198 from urllib.request import urlopen # Py3
3189 from urllib.request import urlopen # Py3
3199 except ImportError:
3190 except ImportError:
3200 from urllib import urlopen
3191 from urllib import urlopen
3201 response = urlopen(target)
3192 response = urlopen(target)
3202 return response.read().decode('latin1')
3193 return response.read().decode('latin1')
3203 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3194 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3204
3195
3205 potential_target = [target]
3196 potential_target = [target]
3206 try :
3197 try :
3207 potential_target.insert(0,get_py_filename(target))
3198 potential_target.insert(0,get_py_filename(target))
3208 except IOError:
3199 except IOError:
3209 pass
3200 pass
3210
3201
3211 for tgt in potential_target :
3202 for tgt in potential_target :
3212 if os.path.isfile(tgt): # Read file
3203 if os.path.isfile(tgt): # Read file
3213 try :
3204 try :
3214 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3205 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3215 except UnicodeDecodeError :
3206 except UnicodeDecodeError :
3216 if not py_only :
3207 if not py_only :
3217 with io_open(tgt,'r', encoding='latin1') as f :
3208 with io_open(tgt,'r', encoding='latin1') as f :
3218 return f.read()
3209 return f.read()
3219 raise ValueError(("'%s' seem to be unreadable.") % target)
3210 raise ValueError(("'%s' seem to be unreadable.") % target)
3220 elif os.path.isdir(os.path.expanduser(tgt)):
3211 elif os.path.isdir(os.path.expanduser(tgt)):
3221 raise ValueError("'%s' is a directory, not a regular file." % target)
3212 raise ValueError("'%s' is a directory, not a regular file." % target)
3222
3213
3223 if search_ns:
3214 if search_ns:
3224 # Inspect namespace to load object source
3215 # Inspect namespace to load object source
3225 object_info = self.object_inspect(target, detail_level=1)
3216 object_info = self.object_inspect(target, detail_level=1)
3226 if object_info['found'] and object_info['source']:
3217 if object_info['found'] and object_info['source']:
3227 return object_info['source']
3218 return object_info['source']
3228
3219
3229 try: # User namespace
3220 try: # User namespace
3230 codeobj = eval(target, self.user_ns)
3221 codeobj = eval(target, self.user_ns)
3231 except Exception:
3222 except Exception:
3232 raise ValueError(("'%s' was not found in history, as a file, url, "
3223 raise ValueError(("'%s' was not found in history, as a file, url, "
3233 "nor in the user namespace.") % target)
3224 "nor in the user namespace.") % target)
3234
3225
3235 if isinstance(codeobj, string_types):
3226 if isinstance(codeobj, string_types):
3236 return codeobj
3227 return codeobj
3237 elif isinstance(codeobj, Macro):
3228 elif isinstance(codeobj, Macro):
3238 return codeobj.value
3229 return codeobj.value
3239
3230
3240 raise TypeError("%s is neither a string nor a macro." % target,
3231 raise TypeError("%s is neither a string nor a macro." % target,
3241 codeobj)
3232 codeobj)
3242
3233
3243 #-------------------------------------------------------------------------
3234 #-------------------------------------------------------------------------
3244 # Things related to IPython exiting
3235 # Things related to IPython exiting
3245 #-------------------------------------------------------------------------
3236 #-------------------------------------------------------------------------
3246 def atexit_operations(self):
3237 def atexit_operations(self):
3247 """This will be executed at the time of exit.
3238 """This will be executed at the time of exit.
3248
3239
3249 Cleanup operations and saving of persistent data that is done
3240 Cleanup operations and saving of persistent data that is done
3250 unconditionally by IPython should be performed here.
3241 unconditionally by IPython should be performed here.
3251
3242
3252 For things that may depend on startup flags or platform specifics (such
3243 For things that may depend on startup flags or platform specifics (such
3253 as having readline or not), register a separate atexit function in the
3244 as having readline or not), register a separate atexit function in the
3254 code that has the appropriate information, rather than trying to
3245 code that has the appropriate information, rather than trying to
3255 clutter
3246 clutter
3256 """
3247 """
3257 # Close the history session (this stores the end time and line count)
3248 # Close the history session (this stores the end time and line count)
3258 # this must be *before* the tempfile cleanup, in case of temporary
3249 # this must be *before* the tempfile cleanup, in case of temporary
3259 # history db
3250 # history db
3260 self.history_manager.end_session()
3251 self.history_manager.end_session()
3261
3252
3262 # Cleanup all tempfiles and folders left around
3253 # Cleanup all tempfiles and folders left around
3263 for tfile in self.tempfiles:
3254 for tfile in self.tempfiles:
3264 try:
3255 try:
3265 os.unlink(tfile)
3256 os.unlink(tfile)
3266 except OSError:
3257 except OSError:
3267 pass
3258 pass
3268
3259
3269 for tdir in self.tempdirs:
3260 for tdir in self.tempdirs:
3270 try:
3261 try:
3271 os.rmdir(tdir)
3262 os.rmdir(tdir)
3272 except OSError:
3263 except OSError:
3273 pass
3264 pass
3274
3265
3275 # Clear all user namespaces to release all references cleanly.
3266 # Clear all user namespaces to release all references cleanly.
3276 self.reset(new_session=False)
3267 self.reset(new_session=False)
3277
3268
3278 # Run user hooks
3269 # Run user hooks
3279 self.hooks.shutdown_hook()
3270 self.hooks.shutdown_hook()
3280
3271
3281 def cleanup(self):
3272 def cleanup(self):
3282 self.restore_sys_module_state()
3273 self.restore_sys_module_state()
3283
3274
3284
3275
3285 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3276 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3286 """An abstract base class for InteractiveShell."""
3277 """An abstract base class for InteractiveShell."""
3287
3278
3288 InteractiveShellABC.register(InteractiveShell)
3279 InteractiveShellABC.register(InteractiveShell)
@@ -1,609 +1,612 b''
1 """Test interact and interactive."""
1 """Test interact and interactive."""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 from __future__ import print_function
6 from __future__ import print_function
7
7
8 from collections import OrderedDict
8 from collections import OrderedDict
9
9
10 import nose.tools as nt
10 import nose.tools as nt
11 import IPython.testing.tools as tt
11 import IPython.testing.tools as tt
12
12
13 from IPython.kernel.comm import Comm
13 from IPython.kernel.comm import Comm
14 from IPython.html import widgets
14 from IPython.html import widgets
15 from IPython.html.widgets import interact, interactive, Widget, interaction
15 from IPython.html.widgets import interact, interactive, Widget, interaction
16 from IPython.utils.py3compat import annotate
16 from IPython.utils.py3compat import annotate
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Utility stuff
19 # Utility stuff
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 class DummyComm(Comm):
22 class DummyComm(Comm):
23 comm_id = 'a-b-c-d'
23 comm_id = 'a-b-c-d'
24
24
25 def open(self, *args, **kwargs):
26 pass
27
25 def send(self, *args, **kwargs):
28 def send(self, *args, **kwargs):
26 pass
29 pass
27
30
28 def close(self, *args, **kwargs):
31 def close(self, *args, **kwargs):
29 pass
32 pass
30
33
31 _widget_attrs = {}
34 _widget_attrs = {}
32 displayed = []
35 displayed = []
33 undefined = object()
36 undefined = object()
34
37
35 def setup():
38 def setup():
36 _widget_attrs['_comm_default'] = getattr(Widget, '_comm_default', undefined)
39 _widget_attrs['_comm_default'] = getattr(Widget, '_comm_default', undefined)
37 Widget._comm_default = lambda self: DummyComm()
40 Widget._comm_default = lambda self: DummyComm()
38 _widget_attrs['_ipython_display_'] = Widget._ipython_display_
41 _widget_attrs['_ipython_display_'] = Widget._ipython_display_
39 def raise_not_implemented(*args, **kwargs):
42 def raise_not_implemented(*args, **kwargs):
40 raise NotImplementedError()
43 raise NotImplementedError()
41 Widget._ipython_display_ = raise_not_implemented
44 Widget._ipython_display_ = raise_not_implemented
42
45
43 def teardown():
46 def teardown():
44 for attr, value in _widget_attrs.items():
47 for attr, value in _widget_attrs.items():
45 if value is undefined:
48 if value is undefined:
46 delattr(Widget, attr)
49 delattr(Widget, attr)
47 else:
50 else:
48 setattr(Widget, attr, value)
51 setattr(Widget, attr, value)
49
52
50 def f(**kwargs):
53 def f(**kwargs):
51 pass
54 pass
52
55
53 def clear_display():
56 def clear_display():
54 global displayed
57 global displayed
55 displayed = []
58 displayed = []
56
59
57 def record_display(*args):
60 def record_display(*args):
58 displayed.extend(args)
61 displayed.extend(args)
59
62
60 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
61 # Actual tests
64 # Actual tests
62 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
63
66
64 def check_widget(w, **d):
67 def check_widget(w, **d):
65 """Check a single widget against a dict"""
68 """Check a single widget against a dict"""
66 for attr, expected in d.items():
69 for attr, expected in d.items():
67 if attr == 'cls':
70 if attr == 'cls':
68 nt.assert_is(w.__class__, expected)
71 nt.assert_is(w.__class__, expected)
69 else:
72 else:
70 value = getattr(w, attr)
73 value = getattr(w, attr)
71 nt.assert_equal(value, expected,
74 nt.assert_equal(value, expected,
72 "%s.%s = %r != %r" % (w.__class__.__name__, attr, value, expected)
75 "%s.%s = %r != %r" % (w.__class__.__name__, attr, value, expected)
73 )
76 )
74
77
75 def check_widgets(container, **to_check):
78 def check_widgets(container, **to_check):
76 """Check that widgets are created as expected"""
79 """Check that widgets are created as expected"""
77 # build a widget dictionary, so it matches
80 # build a widget dictionary, so it matches
78 widgets = {}
81 widgets = {}
79 for w in container.children:
82 for w in container.children:
80 widgets[w.description] = w
83 widgets[w.description] = w
81
84
82 for key, d in to_check.items():
85 for key, d in to_check.items():
83 nt.assert_in(key, widgets)
86 nt.assert_in(key, widgets)
84 check_widget(widgets[key], **d)
87 check_widget(widgets[key], **d)
85
88
86
89
87 def test_single_value_string():
90 def test_single_value_string():
88 a = u'hello'
91 a = u'hello'
89 c = interactive(f, a=a)
92 c = interactive(f, a=a)
90 w = c.children[0]
93 w = c.children[0]
91 check_widget(w,
94 check_widget(w,
92 cls=widgets.Text,
95 cls=widgets.Text,
93 description='a',
96 description='a',
94 value=a,
97 value=a,
95 )
98 )
96
99
97 def test_single_value_bool():
100 def test_single_value_bool():
98 for a in (True, False):
101 for a in (True, False):
99 c = interactive(f, a=a)
102 c = interactive(f, a=a)
100 w = c.children[0]
103 w = c.children[0]
101 check_widget(w,
104 check_widget(w,
102 cls=widgets.Checkbox,
105 cls=widgets.Checkbox,
103 description='a',
106 description='a',
104 value=a,
107 value=a,
105 )
108 )
106
109
107 def test_single_value_dict():
110 def test_single_value_dict():
108 for d in [
111 for d in [
109 dict(a=5),
112 dict(a=5),
110 dict(a=5, b='b', c=dict),
113 dict(a=5, b='b', c=dict),
111 ]:
114 ]:
112 c = interactive(f, d=d)
115 c = interactive(f, d=d)
113 w = c.children[0]
116 w = c.children[0]
114 check_widget(w,
117 check_widget(w,
115 cls=widgets.Dropdown,
118 cls=widgets.Dropdown,
116 description='d',
119 description='d',
117 values=d,
120 values=d,
118 value=next(iter(d.values())),
121 value=next(iter(d.values())),
119 )
122 )
120
123
121 def test_single_value_float():
124 def test_single_value_float():
122 for a in (2.25, 1.0, -3.5):
125 for a in (2.25, 1.0, -3.5):
123 c = interactive(f, a=a)
126 c = interactive(f, a=a)
124 w = c.children[0]
127 w = c.children[0]
125 check_widget(w,
128 check_widget(w,
126 cls=widgets.FloatSlider,
129 cls=widgets.FloatSlider,
127 description='a',
130 description='a',
128 value=a,
131 value=a,
129 min= -a if a > 0 else 3*a,
132 min= -a if a > 0 else 3*a,
130 max= 3*a if a > 0 else -a,
133 max= 3*a if a > 0 else -a,
131 step=0.1,
134 step=0.1,
132 readout=True,
135 readout=True,
133 )
136 )
134
137
135 def test_single_value_int():
138 def test_single_value_int():
136 for a in (1, 5, -3):
139 for a in (1, 5, -3):
137 c = interactive(f, a=a)
140 c = interactive(f, a=a)
138 nt.assert_equal(len(c.children), 1)
141 nt.assert_equal(len(c.children), 1)
139 w = c.children[0]
142 w = c.children[0]
140 check_widget(w,
143 check_widget(w,
141 cls=widgets.IntSlider,
144 cls=widgets.IntSlider,
142 description='a',
145 description='a',
143 value=a,
146 value=a,
144 min= -a if a > 0 else 3*a,
147 min= -a if a > 0 else 3*a,
145 max= 3*a if a > 0 else -a,
148 max= 3*a if a > 0 else -a,
146 step=1,
149 step=1,
147 readout=True,
150 readout=True,
148 )
151 )
149
152
150 def test_list_tuple_2_int():
153 def test_list_tuple_2_int():
151 with nt.assert_raises(ValueError):
154 with nt.assert_raises(ValueError):
152 c = interactive(f, tup=(1,1))
155 c = interactive(f, tup=(1,1))
153 with nt.assert_raises(ValueError):
156 with nt.assert_raises(ValueError):
154 c = interactive(f, tup=(1,-1))
157 c = interactive(f, tup=(1,-1))
155 for min, max in [ (0,1), (1,10), (1,2), (-5,5), (-20,-19) ]:
158 for min, max in [ (0,1), (1,10), (1,2), (-5,5), (-20,-19) ]:
156 c = interactive(f, tup=(min, max), lis=[min, max])
159 c = interactive(f, tup=(min, max), lis=[min, max])
157 nt.assert_equal(len(c.children), 2)
160 nt.assert_equal(len(c.children), 2)
158 d = dict(
161 d = dict(
159 cls=widgets.IntSlider,
162 cls=widgets.IntSlider,
160 min=min,
163 min=min,
161 max=max,
164 max=max,
162 step=1,
165 step=1,
163 readout=True,
166 readout=True,
164 )
167 )
165 check_widgets(c, tup=d, lis=d)
168 check_widgets(c, tup=d, lis=d)
166
169
167 def test_list_tuple_3_int():
170 def test_list_tuple_3_int():
168 with nt.assert_raises(ValueError):
171 with nt.assert_raises(ValueError):
169 c = interactive(f, tup=(1,2,0))
172 c = interactive(f, tup=(1,2,0))
170 with nt.assert_raises(ValueError):
173 with nt.assert_raises(ValueError):
171 c = interactive(f, tup=(1,2,-1))
174 c = interactive(f, tup=(1,2,-1))
172 for min, max, step in [ (0,2,1), (1,10,2), (1,100,2), (-5,5,4), (-100,-20,4) ]:
175 for min, max, step in [ (0,2,1), (1,10,2), (1,100,2), (-5,5,4), (-100,-20,4) ]:
173 c = interactive(f, tup=(min, max, step), lis=[min, max, step])
176 c = interactive(f, tup=(min, max, step), lis=[min, max, step])
174 nt.assert_equal(len(c.children), 2)
177 nt.assert_equal(len(c.children), 2)
175 d = dict(
178 d = dict(
176 cls=widgets.IntSlider,
179 cls=widgets.IntSlider,
177 min=min,
180 min=min,
178 max=max,
181 max=max,
179 step=step,
182 step=step,
180 readout=True,
183 readout=True,
181 )
184 )
182 check_widgets(c, tup=d, lis=d)
185 check_widgets(c, tup=d, lis=d)
183
186
184 def test_list_tuple_2_float():
187 def test_list_tuple_2_float():
185 with nt.assert_raises(ValueError):
188 with nt.assert_raises(ValueError):
186 c = interactive(f, tup=(1.0,1.0))
189 c = interactive(f, tup=(1.0,1.0))
187 with nt.assert_raises(ValueError):
190 with nt.assert_raises(ValueError):
188 c = interactive(f, tup=(0.5,-0.5))
191 c = interactive(f, tup=(0.5,-0.5))
189 for min, max in [ (0.5, 1.5), (1.1,10.2), (1,2.2), (-5.,5), (-20,-19.) ]:
192 for min, max in [ (0.5, 1.5), (1.1,10.2), (1,2.2), (-5.,5), (-20,-19.) ]:
190 c = interactive(f, tup=(min, max), lis=[min, max])
193 c = interactive(f, tup=(min, max), lis=[min, max])
191 nt.assert_equal(len(c.children), 2)
194 nt.assert_equal(len(c.children), 2)
192 d = dict(
195 d = dict(
193 cls=widgets.FloatSlider,
196 cls=widgets.FloatSlider,
194 min=min,
197 min=min,
195 max=max,
198 max=max,
196 step=.1,
199 step=.1,
197 readout=True,
200 readout=True,
198 )
201 )
199 check_widgets(c, tup=d, lis=d)
202 check_widgets(c, tup=d, lis=d)
200
203
201 def test_list_tuple_3_float():
204 def test_list_tuple_3_float():
202 with nt.assert_raises(ValueError):
205 with nt.assert_raises(ValueError):
203 c = interactive(f, tup=(1,2,0.0))
206 c = interactive(f, tup=(1,2,0.0))
204 with nt.assert_raises(ValueError):
207 with nt.assert_raises(ValueError):
205 c = interactive(f, tup=(-1,-2,1.))
208 c = interactive(f, tup=(-1,-2,1.))
206 with nt.assert_raises(ValueError):
209 with nt.assert_raises(ValueError):
207 c = interactive(f, tup=(1,2.,-1.))
210 c = interactive(f, tup=(1,2.,-1.))
208 for min, max, step in [ (0.,2,1), (1,10.,2), (1,100,2.), (-5.,5.,4), (-100,-20.,4.) ]:
211 for min, max, step in [ (0.,2,1), (1,10.,2), (1,100,2.), (-5.,5.,4), (-100,-20.,4.) ]:
209 c = interactive(f, tup=(min, max, step), lis=[min, max, step])
212 c = interactive(f, tup=(min, max, step), lis=[min, max, step])
210 nt.assert_equal(len(c.children), 2)
213 nt.assert_equal(len(c.children), 2)
211 d = dict(
214 d = dict(
212 cls=widgets.FloatSlider,
215 cls=widgets.FloatSlider,
213 min=min,
216 min=min,
214 max=max,
217 max=max,
215 step=step,
218 step=step,
216 readout=True,
219 readout=True,
217 )
220 )
218 check_widgets(c, tup=d, lis=d)
221 check_widgets(c, tup=d, lis=d)
219
222
220 def test_list_tuple_str():
223 def test_list_tuple_str():
221 values = ['hello', 'there', 'guy']
224 values = ['hello', 'there', 'guy']
222 first = values[0]
225 first = values[0]
223 dvalues = OrderedDict((v,v) for v in values)
226 dvalues = OrderedDict((v,v) for v in values)
224 c = interactive(f, tup=tuple(values), lis=list(values))
227 c = interactive(f, tup=tuple(values), lis=list(values))
225 nt.assert_equal(len(c.children), 2)
228 nt.assert_equal(len(c.children), 2)
226 d = dict(
229 d = dict(
227 cls=widgets.Dropdown,
230 cls=widgets.Dropdown,
228 value=first,
231 value=first,
229 values=dvalues
232 values=dvalues
230 )
233 )
231 check_widgets(c, tup=d, lis=d)
234 check_widgets(c, tup=d, lis=d)
232
235
233 def test_list_tuple_invalid():
236 def test_list_tuple_invalid():
234 for bad in [
237 for bad in [
235 (),
238 (),
236 (5, 'hi'),
239 (5, 'hi'),
237 ('hi', 5),
240 ('hi', 5),
238 ({},),
241 ({},),
239 (None,),
242 (None,),
240 ]:
243 ]:
241 with nt.assert_raises(ValueError):
244 with nt.assert_raises(ValueError):
242 print(bad) # because there is no custom message in assert_raises
245 print(bad) # because there is no custom message in assert_raises
243 c = interactive(f, tup=bad)
246 c = interactive(f, tup=bad)
244
247
245 def test_defaults():
248 def test_defaults():
246 @annotate(n=10)
249 @annotate(n=10)
247 def f(n, f=4.5, g=1):
250 def f(n, f=4.5, g=1):
248 pass
251 pass
249
252
250 c = interactive(f)
253 c = interactive(f)
251 check_widgets(c,
254 check_widgets(c,
252 n=dict(
255 n=dict(
253 cls=widgets.IntSlider,
256 cls=widgets.IntSlider,
254 value=10,
257 value=10,
255 ),
258 ),
256 f=dict(
259 f=dict(
257 cls=widgets.FloatSlider,
260 cls=widgets.FloatSlider,
258 value=4.5,
261 value=4.5,
259 ),
262 ),
260 g=dict(
263 g=dict(
261 cls=widgets.IntSlider,
264 cls=widgets.IntSlider,
262 value=1,
265 value=1,
263 ),
266 ),
264 )
267 )
265
268
266 def test_default_values():
269 def test_default_values():
267 @annotate(n=10, f=(0, 10.), g=5, h={'a': 1, 'b': 2}, j=['hi', 'there'])
270 @annotate(n=10, f=(0, 10.), g=5, h={'a': 1, 'b': 2}, j=['hi', 'there'])
268 def f(n, f=4.5, g=1, h=2, j='there'):
271 def f(n, f=4.5, g=1, h=2, j='there'):
269 pass
272 pass
270
273
271 c = interactive(f)
274 c = interactive(f)
272 check_widgets(c,
275 check_widgets(c,
273 n=dict(
276 n=dict(
274 cls=widgets.IntSlider,
277 cls=widgets.IntSlider,
275 value=10,
278 value=10,
276 ),
279 ),
277 f=dict(
280 f=dict(
278 cls=widgets.FloatSlider,
281 cls=widgets.FloatSlider,
279 value=4.5,
282 value=4.5,
280 ),
283 ),
281 g=dict(
284 g=dict(
282 cls=widgets.IntSlider,
285 cls=widgets.IntSlider,
283 value=5,
286 value=5,
284 ),
287 ),
285 h=dict(
288 h=dict(
286 cls=widgets.Dropdown,
289 cls=widgets.Dropdown,
287 values={'a': 1, 'b': 2},
290 values={'a': 1, 'b': 2},
288 value=2
291 value=2
289 ),
292 ),
290 j=dict(
293 j=dict(
291 cls=widgets.Dropdown,
294 cls=widgets.Dropdown,
292 values={'hi':'hi', 'there':'there'},
295 values={'hi':'hi', 'there':'there'},
293 value='there'
296 value='there'
294 ),
297 ),
295 )
298 )
296
299
297 def test_default_out_of_bounds():
300 def test_default_out_of_bounds():
298 @annotate(f=(0, 10.), h={'a': 1}, j=['hi', 'there'])
301 @annotate(f=(0, 10.), h={'a': 1}, j=['hi', 'there'])
299 def f(f='hi', h=5, j='other'):
302 def f(f='hi', h=5, j='other'):
300 pass
303 pass
301
304
302 c = interactive(f)
305 c = interactive(f)
303 check_widgets(c,
306 check_widgets(c,
304 f=dict(
307 f=dict(
305 cls=widgets.FloatSlider,
308 cls=widgets.FloatSlider,
306 value=5.,
309 value=5.,
307 ),
310 ),
308 h=dict(
311 h=dict(
309 cls=widgets.Dropdown,
312 cls=widgets.Dropdown,
310 values={'a': 1},
313 values={'a': 1},
311 value=1,
314 value=1,
312 ),
315 ),
313 j=dict(
316 j=dict(
314 cls=widgets.Dropdown,
317 cls=widgets.Dropdown,
315 values={'hi':'hi', 'there':'there'},
318 values={'hi':'hi', 'there':'there'},
316 value='hi',
319 value='hi',
317 ),
320 ),
318 )
321 )
319
322
320 def test_annotations():
323 def test_annotations():
321 @annotate(n=10, f=widgets.FloatText())
324 @annotate(n=10, f=widgets.FloatText())
322 def f(n, f):
325 def f(n, f):
323 pass
326 pass
324
327
325 c = interactive(f)
328 c = interactive(f)
326 check_widgets(c,
329 check_widgets(c,
327 n=dict(
330 n=dict(
328 cls=widgets.IntSlider,
331 cls=widgets.IntSlider,
329 value=10,
332 value=10,
330 ),
333 ),
331 f=dict(
334 f=dict(
332 cls=widgets.FloatText,
335 cls=widgets.FloatText,
333 ),
336 ),
334 )
337 )
335
338
336 def test_priority():
339 def test_priority():
337 @annotate(annotate='annotate', kwarg='annotate')
340 @annotate(annotate='annotate', kwarg='annotate')
338 def f(kwarg='default', annotate='default', default='default'):
341 def f(kwarg='default', annotate='default', default='default'):
339 pass
342 pass
340
343
341 c = interactive(f, kwarg='kwarg')
344 c = interactive(f, kwarg='kwarg')
342 check_widgets(c,
345 check_widgets(c,
343 kwarg=dict(
346 kwarg=dict(
344 cls=widgets.Text,
347 cls=widgets.Text,
345 value='kwarg',
348 value='kwarg',
346 ),
349 ),
347 annotate=dict(
350 annotate=dict(
348 cls=widgets.Text,
351 cls=widgets.Text,
349 value='annotate',
352 value='annotate',
350 ),
353 ),
351 )
354 )
352
355
353 @nt.with_setup(clear_display)
356 @nt.with_setup(clear_display)
354 def test_decorator_kwarg():
357 def test_decorator_kwarg():
355 with tt.monkeypatch(interaction, 'display', record_display):
358 with tt.monkeypatch(interaction, 'display', record_display):
356 @interact(a=5)
359 @interact(a=5)
357 def foo(a):
360 def foo(a):
358 pass
361 pass
359 nt.assert_equal(len(displayed), 1)
362 nt.assert_equal(len(displayed), 1)
360 w = displayed[0].children[0]
363 w = displayed[0].children[0]
361 check_widget(w,
364 check_widget(w,
362 cls=widgets.IntSlider,
365 cls=widgets.IntSlider,
363 value=5,
366 value=5,
364 )
367 )
365
368
366 @nt.with_setup(clear_display)
369 @nt.with_setup(clear_display)
367 def test_decorator_no_call():
370 def test_decorator_no_call():
368 with tt.monkeypatch(interaction, 'display', record_display):
371 with tt.monkeypatch(interaction, 'display', record_display):
369 @interact
372 @interact
370 def foo(a='default'):
373 def foo(a='default'):
371 pass
374 pass
372 nt.assert_equal(len(displayed), 1)
375 nt.assert_equal(len(displayed), 1)
373 w = displayed[0].children[0]
376 w = displayed[0].children[0]
374 check_widget(w,
377 check_widget(w,
375 cls=widgets.Text,
378 cls=widgets.Text,
376 value='default',
379 value='default',
377 )
380 )
378
381
379 @nt.with_setup(clear_display)
382 @nt.with_setup(clear_display)
380 def test_call_interact():
383 def test_call_interact():
381 def foo(a='default'):
384 def foo(a='default'):
382 pass
385 pass
383 with tt.monkeypatch(interaction, 'display', record_display):
386 with tt.monkeypatch(interaction, 'display', record_display):
384 ifoo = interact(foo)
387 ifoo = interact(foo)
385 nt.assert_equal(len(displayed), 1)
388 nt.assert_equal(len(displayed), 1)
386 w = displayed[0].children[0]
389 w = displayed[0].children[0]
387 check_widget(w,
390 check_widget(w,
388 cls=widgets.Text,
391 cls=widgets.Text,
389 value='default',
392 value='default',
390 )
393 )
391
394
392 @nt.with_setup(clear_display)
395 @nt.with_setup(clear_display)
393 def test_call_interact_kwargs():
396 def test_call_interact_kwargs():
394 def foo(a='default'):
397 def foo(a='default'):
395 pass
398 pass
396 with tt.monkeypatch(interaction, 'display', record_display):
399 with tt.monkeypatch(interaction, 'display', record_display):
397 ifoo = interact(foo, a=10)
400 ifoo = interact(foo, a=10)
398 nt.assert_equal(len(displayed), 1)
401 nt.assert_equal(len(displayed), 1)
399 w = displayed[0].children[0]
402 w = displayed[0].children[0]
400 check_widget(w,
403 check_widget(w,
401 cls=widgets.IntSlider,
404 cls=widgets.IntSlider,
402 value=10,
405 value=10,
403 )
406 )
404
407
405 @nt.with_setup(clear_display)
408 @nt.with_setup(clear_display)
406 def test_call_decorated_on_trait_change():
409 def test_call_decorated_on_trait_change():
407 """test calling @interact decorated functions"""
410 """test calling @interact decorated functions"""
408 d = {}
411 d = {}
409 with tt.monkeypatch(interaction, 'display', record_display):
412 with tt.monkeypatch(interaction, 'display', record_display):
410 @interact
413 @interact
411 def foo(a='default'):
414 def foo(a='default'):
412 d['a'] = a
415 d['a'] = a
413 return a
416 return a
414 nt.assert_equal(len(displayed), 1)
417 nt.assert_equal(len(displayed), 1)
415 w = displayed[0].children[0]
418 w = displayed[0].children[0]
416 check_widget(w,
419 check_widget(w,
417 cls=widgets.Text,
420 cls=widgets.Text,
418 value='default',
421 value='default',
419 )
422 )
420 # test calling the function directly
423 # test calling the function directly
421 a = foo('hello')
424 a = foo('hello')
422 nt.assert_equal(a, 'hello')
425 nt.assert_equal(a, 'hello')
423 nt.assert_equal(d['a'], 'hello')
426 nt.assert_equal(d['a'], 'hello')
424
427
425 # test that setting trait values calls the function
428 # test that setting trait values calls the function
426 w.value = 'called'
429 w.value = 'called'
427 nt.assert_equal(d['a'], 'called')
430 nt.assert_equal(d['a'], 'called')
428
431
429 @nt.with_setup(clear_display)
432 @nt.with_setup(clear_display)
430 def test_call_decorated_kwargs_on_trait_change():
433 def test_call_decorated_kwargs_on_trait_change():
431 """test calling @interact(foo=bar) decorated functions"""
434 """test calling @interact(foo=bar) decorated functions"""
432 d = {}
435 d = {}
433 with tt.monkeypatch(interaction, 'display', record_display):
436 with tt.monkeypatch(interaction, 'display', record_display):
434 @interact(a='kwarg')
437 @interact(a='kwarg')
435 def foo(a='default'):
438 def foo(a='default'):
436 d['a'] = a
439 d['a'] = a
437 return a
440 return a
438 nt.assert_equal(len(displayed), 1)
441 nt.assert_equal(len(displayed), 1)
439 w = displayed[0].children[0]
442 w = displayed[0].children[0]
440 check_widget(w,
443 check_widget(w,
441 cls=widgets.Text,
444 cls=widgets.Text,
442 value='kwarg',
445 value='kwarg',
443 )
446 )
444 # test calling the function directly
447 # test calling the function directly
445 a = foo('hello')
448 a = foo('hello')
446 nt.assert_equal(a, 'hello')
449 nt.assert_equal(a, 'hello')
447 nt.assert_equal(d['a'], 'hello')
450 nt.assert_equal(d['a'], 'hello')
448
451
449 # test that setting trait values calls the function
452 # test that setting trait values calls the function
450 w.value = 'called'
453 w.value = 'called'
451 nt.assert_equal(d['a'], 'called')
454 nt.assert_equal(d['a'], 'called')
452
455
453 def test_fixed():
456 def test_fixed():
454 c = interactive(f, a=widgets.fixed(5), b='text')
457 c = interactive(f, a=widgets.fixed(5), b='text')
455 nt.assert_equal(len(c.children), 1)
458 nt.assert_equal(len(c.children), 1)
456 w = c.children[0]
459 w = c.children[0]
457 check_widget(w,
460 check_widget(w,
458 cls=widgets.Text,
461 cls=widgets.Text,
459 value='text',
462 value='text',
460 description='b',
463 description='b',
461 )
464 )
462
465
463 def test_default_description():
466 def test_default_description():
464 c = interactive(f, b='text')
467 c = interactive(f, b='text')
465 w = c.children[0]
468 w = c.children[0]
466 check_widget(w,
469 check_widget(w,
467 cls=widgets.Text,
470 cls=widgets.Text,
468 value='text',
471 value='text',
469 description='b',
472 description='b',
470 )
473 )
471
474
472 def test_custom_description():
475 def test_custom_description():
473 c = interactive(f, b=widgets.Text(value='text', description='foo'))
476 c = interactive(f, b=widgets.Text(value='text', description='foo'))
474 w = c.children[0]
477 w = c.children[0]
475 check_widget(w,
478 check_widget(w,
476 cls=widgets.Text,
479 cls=widgets.Text,
477 value='text',
480 value='text',
478 description='foo',
481 description='foo',
479 )
482 )
480
483
481 def test_interact_manual_button():
484 def test_interact_manual_button():
482 c = interactive(f, __manual=True)
485 c = interactive(f, __manual=True)
483 w = c.children[0]
486 w = c.children[0]
484 check_widget(w, cls=widgets.Button)
487 check_widget(w, cls=widgets.Button)
485
488
486 def test_interact_manual_nocall():
489 def test_interact_manual_nocall():
487 callcount = 0
490 callcount = 0
488 def calltest(testarg):
491 def calltest(testarg):
489 callcount += 1
492 callcount += 1
490 c = interactive(calltest, testarg=5, __manual=True)
493 c = interactive(calltest, testarg=5, __manual=True)
491 c.children[0].value = 10
494 c.children[0].value = 10
492 nt.assert_equal(callcount, 0)
495 nt.assert_equal(callcount, 0)
493
496
494 def test_int_range_logic():
497 def test_int_range_logic():
495 irsw = widgets.IntRangeSlider
498 irsw = widgets.IntRangeSlider
496 w = irsw(value=(2, 4), min=0, max=6)
499 w = irsw(value=(2, 4), min=0, max=6)
497 check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
500 check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
498 w.value = (4, 2)
501 w.value = (4, 2)
499 check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
502 check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
500 w.value = (-1, 7)
503 w.value = (-1, 7)
501 check_widget(w, cls=irsw, value=(0, 6), min=0, max=6)
504 check_widget(w, cls=irsw, value=(0, 6), min=0, max=6)
502 w.min = 3
505 w.min = 3
503 check_widget(w, cls=irsw, value=(3, 6), min=3, max=6)
506 check_widget(w, cls=irsw, value=(3, 6), min=3, max=6)
504 w.max = 3
507 w.max = 3
505 check_widget(w, cls=irsw, value=(3, 3), min=3, max=3)
508 check_widget(w, cls=irsw, value=(3, 3), min=3, max=3)
506
509
507 w.min = 0
510 w.min = 0
508 w.max = 6
511 w.max = 6
509 w.lower = 2
512 w.lower = 2
510 w.upper = 4
513 w.upper = 4
511 check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
514 check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
512 w.value = (0, 1) #lower non-overlapping range
515 w.value = (0, 1) #lower non-overlapping range
513 check_widget(w, cls=irsw, value=(0, 1), min=0, max=6)
516 check_widget(w, cls=irsw, value=(0, 1), min=0, max=6)
514 w.value = (5, 6) #upper non-overlapping range
517 w.value = (5, 6) #upper non-overlapping range
515 check_widget(w, cls=irsw, value=(5, 6), min=0, max=6)
518 check_widget(w, cls=irsw, value=(5, 6), min=0, max=6)
516 w.value = (-1, 4) #semi out-of-range
519 w.value = (-1, 4) #semi out-of-range
517 check_widget(w, cls=irsw, value=(0, 4), min=0, max=6)
520 check_widget(w, cls=irsw, value=(0, 4), min=0, max=6)
518 w.lower = 2
521 w.lower = 2
519 check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
522 check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
520 w.value = (-2, -1) #wholly out of range
523 w.value = (-2, -1) #wholly out of range
521 check_widget(w, cls=irsw, value=(0, 0), min=0, max=6)
524 check_widget(w, cls=irsw, value=(0, 0), min=0, max=6)
522 w.value = (7, 8)
525 w.value = (7, 8)
523 check_widget(w, cls=irsw, value=(6, 6), min=0, max=6)
526 check_widget(w, cls=irsw, value=(6, 6), min=0, max=6)
524
527
525 with nt.assert_raises(ValueError):
528 with nt.assert_raises(ValueError):
526 w.min = 7
529 w.min = 7
527 with nt.assert_raises(ValueError):
530 with nt.assert_raises(ValueError):
528 w.max = -1
531 w.max = -1
529 with nt.assert_raises(ValueError):
532 with nt.assert_raises(ValueError):
530 w.lower = 5
533 w.lower = 5
531 with nt.assert_raises(ValueError):
534 with nt.assert_raises(ValueError):
532 w.upper = 1
535 w.upper = 1
533
536
534 w = irsw(min=2, max=3)
537 w = irsw(min=2, max=3)
535 check_widget(w, min=2, max=3)
538 check_widget(w, min=2, max=3)
536 w = irsw(min=100, max=200)
539 w = irsw(min=100, max=200)
537 check_widget(w, lower=125, upper=175, value=(125, 175))
540 check_widget(w, lower=125, upper=175, value=(125, 175))
538
541
539 with nt.assert_raises(ValueError):
542 with nt.assert_raises(ValueError):
540 irsw(value=(2, 4), lower=3)
543 irsw(value=(2, 4), lower=3)
541 with nt.assert_raises(ValueError):
544 with nt.assert_raises(ValueError):
542 irsw(value=(2, 4), upper=3)
545 irsw(value=(2, 4), upper=3)
543 with nt.assert_raises(ValueError):
546 with nt.assert_raises(ValueError):
544 irsw(value=(2, 4), lower=3, upper=3)
547 irsw(value=(2, 4), lower=3, upper=3)
545 with nt.assert_raises(ValueError):
548 with nt.assert_raises(ValueError):
546 irsw(min=2, max=1)
549 irsw(min=2, max=1)
547 with nt.assert_raises(ValueError):
550 with nt.assert_raises(ValueError):
548 irsw(lower=5)
551 irsw(lower=5)
549 with nt.assert_raises(ValueError):
552 with nt.assert_raises(ValueError):
550 irsw(upper=5)
553 irsw(upper=5)
551
554
552
555
553 def test_float_range_logic():
556 def test_float_range_logic():
554 frsw = widgets.FloatRangeSlider
557 frsw = widgets.FloatRangeSlider
555 w = frsw(value=(.2, .4), min=0., max=.6)
558 w = frsw(value=(.2, .4), min=0., max=.6)
556 check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)
559 check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)
557 w.value = (.4, .2)
560 w.value = (.4, .2)
558 check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)
561 check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)
559 w.value = (-.1, .7)
562 w.value = (-.1, .7)
560 check_widget(w, cls=frsw, value=(0., .6), min=0., max=.6)
563 check_widget(w, cls=frsw, value=(0., .6), min=0., max=.6)
561 w.min = .3
564 w.min = .3
562 check_widget(w, cls=frsw, value=(.3, .6), min=.3, max=.6)
565 check_widget(w, cls=frsw, value=(.3, .6), min=.3, max=.6)
563 w.max = .3
566 w.max = .3
564 check_widget(w, cls=frsw, value=(.3, .3), min=.3, max=.3)
567 check_widget(w, cls=frsw, value=(.3, .3), min=.3, max=.3)
565
568
566 w.min = 0.
569 w.min = 0.
567 w.max = .6
570 w.max = .6
568 w.lower = .2
571 w.lower = .2
569 w.upper = .4
572 w.upper = .4
570 check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)
573 check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)
571 w.value = (0., .1) #lower non-overlapping range
574 w.value = (0., .1) #lower non-overlapping range
572 check_widget(w, cls=frsw, value=(0., .1), min=0., max=.6)
575 check_widget(w, cls=frsw, value=(0., .1), min=0., max=.6)
573 w.value = (.5, .6) #upper non-overlapping range
576 w.value = (.5, .6) #upper non-overlapping range
574 check_widget(w, cls=frsw, value=(.5, .6), min=0., max=.6)
577 check_widget(w, cls=frsw, value=(.5, .6), min=0., max=.6)
575 w.value = (-.1, .4) #semi out-of-range
578 w.value = (-.1, .4) #semi out-of-range
576 check_widget(w, cls=frsw, value=(0., .4), min=0., max=.6)
579 check_widget(w, cls=frsw, value=(0., .4), min=0., max=.6)
577 w.lower = .2
580 w.lower = .2
578 check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)
581 check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)
579 w.value = (-.2, -.1) #wholly out of range
582 w.value = (-.2, -.1) #wholly out of range
580 check_widget(w, cls=frsw, value=(0., 0.), min=0., max=.6)
583 check_widget(w, cls=frsw, value=(0., 0.), min=0., max=.6)
581 w.value = (.7, .8)
584 w.value = (.7, .8)
582 check_widget(w, cls=frsw, value=(.6, .6), min=.0, max=.6)
585 check_widget(w, cls=frsw, value=(.6, .6), min=.0, max=.6)
583
586
584 with nt.assert_raises(ValueError):
587 with nt.assert_raises(ValueError):
585 w.min = .7
588 w.min = .7
586 with nt.assert_raises(ValueError):
589 with nt.assert_raises(ValueError):
587 w.max = -.1
590 w.max = -.1
588 with nt.assert_raises(ValueError):
591 with nt.assert_raises(ValueError):
589 w.lower = .5
592 w.lower = .5
590 with nt.assert_raises(ValueError):
593 with nt.assert_raises(ValueError):
591 w.upper = .1
594 w.upper = .1
592
595
593 w = frsw(min=2, max=3)
596 w = frsw(min=2, max=3)
594 check_widget(w, min=2, max=3)
597 check_widget(w, min=2, max=3)
595 w = frsw(min=1., max=2.)
598 w = frsw(min=1., max=2.)
596 check_widget(w, lower=1.25, upper=1.75, value=(1.25, 1.75))
599 check_widget(w, lower=1.25, upper=1.75, value=(1.25, 1.75))
597
600
598 with nt.assert_raises(ValueError):
601 with nt.assert_raises(ValueError):
599 frsw(value=(2, 4), lower=3)
602 frsw(value=(2, 4), lower=3)
600 with nt.assert_raises(ValueError):
603 with nt.assert_raises(ValueError):
601 frsw(value=(2, 4), upper=3)
604 frsw(value=(2, 4), upper=3)
602 with nt.assert_raises(ValueError):
605 with nt.assert_raises(ValueError):
603 frsw(value=(2, 4), lower=3, upper=3)
606 frsw(value=(2, 4), lower=3, upper=3)
604 with nt.assert_raises(ValueError):
607 with nt.assert_raises(ValueError):
605 frsw(min=.2, max=.1)
608 frsw(min=.2, max=.1)
606 with nt.assert_raises(ValueError):
609 with nt.assert_raises(ValueError):
607 frsw(lower=5)
610 frsw(lower=5)
608 with nt.assert_raises(ValueError):
611 with nt.assert_raises(ValueError):
609 frsw(upper=5)
612 frsw(upper=5)
@@ -1,141 +1,144 b''
1 """Base class for a Comm"""
1 """Base class for a Comm"""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 import uuid
6 import uuid
7
7
8 from IPython.config import LoggingConfigurable
8 from IPython.config import LoggingConfigurable
9 from IPython.core.getipython import get_ipython
9 from IPython.kernel.zmq.kernelbase import Kernel
10
10
11 from IPython.utils.jsonutil import json_clean
11 from IPython.utils.jsonutil import json_clean
12 from IPython.utils.traitlets import Instance, Unicode, Bytes, Bool, Dict, Any
12 from IPython.utils.traitlets import Instance, Unicode, Bytes, Bool, Dict, Any
13
13
14
14
15 class Comm(LoggingConfigurable):
15 class Comm(LoggingConfigurable):
16
16
17 # If this is instantiated by a non-IPython kernel, shell will be None
17 # If this is instantiated by a non-IPython kernel, shell will be None
18 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
18 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
19 allow_none=True)
19 allow_none=True)
20 kernel = Instance('IPython.kernel.zmq.kernelbase.Kernel')
20 kernel = Instance('IPython.kernel.zmq.kernelbase.Kernel')
21 def _kernel_default(self):
22 if Kernel.initialized():
23 return Kernel.instance()
21
24
22 iopub_socket = Any()
25 iopub_socket = Any()
23 def _iopub_socket_default(self):
26 def _iopub_socket_default(self):
24 return self.kernel.iopub_socket
27 return self.kernel.iopub_socket
25 session = Instance('IPython.kernel.zmq.session.Session')
28 session = Instance('IPython.kernel.zmq.session.Session')
26 def _session_default(self):
29 def _session_default(self):
27 return self.kernel.session
30 return self.kernel.session
28
31
29 target_name = Unicode('comm')
32 target_name = Unicode('comm')
30
33
31 topic = Bytes()
34 topic = Bytes()
32 def _topic_default(self):
35 def _topic_default(self):
33 return ('comm-%s' % self.comm_id).encode('ascii')
36 return ('comm-%s' % self.comm_id).encode('ascii')
34
37
35 _open_data = Dict(help="data dict, if any, to be included in comm_open")
38 _open_data = Dict(help="data dict, if any, to be included in comm_open")
36 _close_data = Dict(help="data dict, if any, to be included in comm_close")
39 _close_data = Dict(help="data dict, if any, to be included in comm_close")
37
40
38 _msg_callback = Any()
41 _msg_callback = Any()
39 _close_callback = Any()
42 _close_callback = Any()
40
43
41 _closed = Bool(False)
44 _closed = Bool(False)
42 comm_id = Unicode()
45 comm_id = Unicode()
43 def _comm_id_default(self):
46 def _comm_id_default(self):
44 return uuid.uuid4().hex
47 return uuid.uuid4().hex
45
48
46 primary = Bool(True, help="Am I the primary or secondary Comm?")
49 primary = Bool(True, help="Am I the primary or secondary Comm?")
47
50
48 def __init__(self, target_name='', data=None, **kwargs):
51 def __init__(self, target_name='', data=None, **kwargs):
49 if target_name:
52 if target_name:
50 kwargs['target_name'] = target_name
53 kwargs['target_name'] = target_name
51 super(Comm, self).__init__(**kwargs)
54 super(Comm, self).__init__(**kwargs)
52 if self.primary:
55 if self.primary:
53 # I am primary, open my peer.
56 # I am primary, open my peer.
54 self.open(data)
57 self.open(data)
55
58
56 def _publish_msg(self, msg_type, data=None, metadata=None, **keys):
59 def _publish_msg(self, msg_type, data=None, metadata=None, **keys):
57 """Helper for sending a comm message on IOPub"""
60 """Helper for sending a comm message on IOPub"""
58 if self.session is not None:
59 data = {} if data is None else data
61 data = {} if data is None else data
60 metadata = {} if metadata is None else metadata
62 metadata = {} if metadata is None else metadata
61 content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))
63 content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))
62 self.session.send(self.iopub_socket, msg_type,
64 self.session.send(self.iopub_socket, msg_type,
63 content,
65 content,
64 metadata=json_clean(metadata),
66 metadata=json_clean(metadata),
65 parent=self.kernel._parent_header,
67 parent=self.kernel._parent_header,
66 ident=self.topic,
68 ident=self.topic,
67 )
69 )
68
70
69 def __del__(self):
71 def __del__(self):
70 """trigger close on gc"""
72 """trigger close on gc"""
71 self.close()
73 self.close()
72
74
73 # publishing messages
75 # publishing messages
74
76
75 def open(self, data=None, metadata=None):
77 def open(self, data=None, metadata=None):
76 """Open the frontend-side version of this comm"""
78 """Open the frontend-side version of this comm"""
77 if data is None:
79 if data is None:
78 data = self._open_data
80 data = self._open_data
81 comm_manager = getattr(self.kernel, 'comm_manager', None)
82 if comm_manager is None:
83 raise RuntimeError("Comms cannot be opened without a kernel "
84 "and a comm_manager attached to that kernel.")
85
86 comm_manager.register_comm(self)
79 self._closed = False
87 self._closed = False
80 ip = get_ipython()
81 if hasattr(ip, 'comm_manager'):
82 ip.comm_manager.register_comm(self)
83 self._publish_msg('comm_open', data, metadata, target_name=self.target_name)
88 self._publish_msg('comm_open', data, metadata, target_name=self.target_name)
84
89
85 def close(self, data=None, metadata=None):
90 def close(self, data=None, metadata=None):
86 """Close the frontend-side version of this comm"""
91 """Close the frontend-side version of this comm"""
87 if self._closed:
92 if self._closed:
88 # only close once
93 # only close once
89 return
94 return
90 if data is None:
95 if data is None:
91 data = self._close_data
96 data = self._close_data
92 self._publish_msg('comm_close', data, metadata)
97 self._publish_msg('comm_close', data, metadata)
93 ip = get_ipython()
98 self.kernel.comm_manager.unregister_comm(self)
94 if hasattr(ip, 'comm_manager'):
95 ip.comm_manager.unregister_comm(self)
96 self._closed = True
99 self._closed = True
97
100
98 def send(self, data=None, metadata=None):
101 def send(self, data=None, metadata=None):
99 """Send a message to the frontend-side version of this comm"""
102 """Send a message to the frontend-side version of this comm"""
100 self._publish_msg('comm_msg', data, metadata)
103 self._publish_msg('comm_msg', data, metadata)
101
104
102 # registering callbacks
105 # registering callbacks
103
106
104 def on_close(self, callback):
107 def on_close(self, callback):
105 """Register a callback for comm_close
108 """Register a callback for comm_close
106
109
107 Will be called with the `data` of the close message.
110 Will be called with the `data` of the close message.
108
111
109 Call `on_close(None)` to disable an existing callback.
112 Call `on_close(None)` to disable an existing callback.
110 """
113 """
111 self._close_callback = callback
114 self._close_callback = callback
112
115
113 def on_msg(self, callback):
116 def on_msg(self, callback):
114 """Register a callback for comm_msg
117 """Register a callback for comm_msg
115
118
116 Will be called with the `data` of any comm_msg messages.
119 Will be called with the `data` of any comm_msg messages.
117
120
118 Call `on_msg(None)` to disable an existing callback.
121 Call `on_msg(None)` to disable an existing callback.
119 """
122 """
120 self._msg_callback = callback
123 self._msg_callback = callback
121
124
122 # handling of incoming messages
125 # handling of incoming messages
123
126
124 def handle_close(self, msg):
127 def handle_close(self, msg):
125 """Handle a comm_close message"""
128 """Handle a comm_close message"""
126 self.log.debug("handle_close[%s](%s)", self.comm_id, msg)
129 self.log.debug("handle_close[%s](%s)", self.comm_id, msg)
127 if self._close_callback:
130 if self._close_callback:
128 self._close_callback(msg)
131 self._close_callback(msg)
129
132
130 def handle_msg(self, msg):
133 def handle_msg(self, msg):
131 """Handle a comm_msg message"""
134 """Handle a comm_msg message"""
132 self.log.debug("handle_msg[%s](%s)", self.comm_id, msg)
135 self.log.debug("handle_msg[%s](%s)", self.comm_id, msg)
133 if self._msg_callback:
136 if self._msg_callback:
134 if self.shell:
137 if self.shell:
135 self.shell.events.trigger('pre_execute')
138 self.shell.events.trigger('pre_execute')
136 self._msg_callback(msg)
139 self._msg_callback(msg)
137 if self.shell:
140 if self.shell:
138 self.shell.events.trigger('post_execute')
141 self.shell.events.trigger('post_execute')
139
142
140
143
141 __all__ = ['Comm']
144 __all__ = ['Comm']
@@ -1,302 +1,305 b''
1 """The IPython kernel implementation"""
1 """The IPython kernel implementation"""
2
2
3 import getpass
3 import getpass
4 import sys
4 import sys
5 import traceback
5 import traceback
6
6
7 from IPython.core import release
7 from IPython.core import release
8 from IPython.utils.py3compat import builtin_mod, PY3
8 from IPython.utils.py3compat import builtin_mod, PY3
9 from IPython.utils.tokenutil import token_at_cursor
9 from IPython.utils.tokenutil import token_at_cursor
10 from IPython.utils.traitlets import Instance, Type, Any
10 from IPython.utils.traitlets import Instance, Type, Any
11 from IPython.utils.decorators import undoc
11 from IPython.utils.decorators import undoc
12
12
13 from ..comm import CommManager
13 from .kernelbase import Kernel as KernelBase
14 from .kernelbase import Kernel as KernelBase
14 from .serialize import serialize_object, unpack_apply_message
15 from .serialize import serialize_object, unpack_apply_message
15 from .zmqshell import ZMQInteractiveShell
16 from .zmqshell import ZMQInteractiveShell
16
17
17 class IPythonKernel(KernelBase):
18 class IPythonKernel(KernelBase):
18 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
19 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
19 shell_class = Type(ZMQInteractiveShell)
20 shell_class = Type(ZMQInteractiveShell)
20
21
21 user_module = Any()
22 user_module = Any()
22 def _user_module_changed(self, name, old, new):
23 def _user_module_changed(self, name, old, new):
23 if self.shell is not None:
24 if self.shell is not None:
24 self.shell.user_module = new
25 self.shell.user_module = new
25
26
26 user_ns = Instance(dict, args=None, allow_none=True)
27 user_ns = Instance(dict, args=None, allow_none=True)
27 def _user_ns_changed(self, name, old, new):
28 def _user_ns_changed(self, name, old, new):
28 if self.shell is not None:
29 if self.shell is not None:
29 self.shell.user_ns = new
30 self.shell.user_ns = new
30 self.shell.init_user_ns()
31 self.shell.init_user_ns()
31
32
32 # A reference to the Python builtin 'raw_input' function.
33 # A reference to the Python builtin 'raw_input' function.
33 # (i.e., __builtin__.raw_input for Python 2.7, builtins.input for Python 3)
34 # (i.e., __builtin__.raw_input for Python 2.7, builtins.input for Python 3)
34 _sys_raw_input = Any()
35 _sys_raw_input = Any()
35 _sys_eval_input = Any()
36 _sys_eval_input = Any()
36
37
37 def __init__(self, **kwargs):
38 def __init__(self, **kwargs):
38 super(IPythonKernel, self).__init__(**kwargs)
39 super(IPythonKernel, self).__init__(**kwargs)
39
40
40 # Initialize the InteractiveShell subclass
41 # Initialize the InteractiveShell subclass
41 self.shell = self.shell_class.instance(parent=self,
42 self.shell = self.shell_class.instance(parent=self,
42 profile_dir = self.profile_dir,
43 profile_dir = self.profile_dir,
43 user_module = self.user_module,
44 user_module = self.user_module,
44 user_ns = self.user_ns,
45 user_ns = self.user_ns,
45 kernel = self,
46 kernel = self,
46 )
47 )
47 self.shell.displayhook.session = self.session
48 self.shell.displayhook.session = self.session
48 self.shell.displayhook.pub_socket = self.iopub_socket
49 self.shell.displayhook.pub_socket = self.iopub_socket
49 self.shell.displayhook.topic = self._topic('execute_result')
50 self.shell.displayhook.topic = self._topic('execute_result')
50 self.shell.display_pub.session = self.session
51 self.shell.display_pub.session = self.session
51 self.shell.display_pub.pub_socket = self.iopub_socket
52 self.shell.display_pub.pub_socket = self.iopub_socket
52 self.shell.data_pub.session = self.session
53 self.shell.data_pub.session = self.session
53 self.shell.data_pub.pub_socket = self.iopub_socket
54 self.shell.data_pub.pub_socket = self.iopub_socket
54
55
55 # TMP - hack while developing
56 # TMP - hack while developing
56 self.shell._reply_content = None
57 self.shell._reply_content = None
57
58
59 self.comm_manager = CommManager(shell=self.shell, parent=self,
60 kernel=self)
61 self.shell.configurables.append(self.comm_manager)
58 comm_msg_types = [ 'comm_open', 'comm_msg', 'comm_close' ]
62 comm_msg_types = [ 'comm_open', 'comm_msg', 'comm_close' ]
59 comm_manager = self.shell.comm_manager
60 for msg_type in comm_msg_types:
63 for msg_type in comm_msg_types:
61 self.shell_handlers[msg_type] = getattr(comm_manager, msg_type)
64 self.shell_handlers[msg_type] = getattr(self.comm_manager, msg_type)
62
65
63 # Kernel info fields
66 # Kernel info fields
64 implementation = 'ipython'
67 implementation = 'ipython'
65 implementation_version = release.version
68 implementation_version = release.version
66 language = 'python'
69 language = 'python'
67 language_version = sys.version.split()[0]
70 language_version = sys.version.split()[0]
68 @property
71 @property
69 def banner(self):
72 def banner(self):
70 return self.shell.banner
73 return self.shell.banner
71
74
72 def start(self):
75 def start(self):
73 self.shell.exit_now = False
76 self.shell.exit_now = False
74 super(IPythonKernel, self).start()
77 super(IPythonKernel, self).start()
75
78
76 def set_parent(self, ident, parent):
79 def set_parent(self, ident, parent):
77 """Overridden from parent to tell the display hook and output streams
80 """Overridden from parent to tell the display hook and output streams
78 about the parent message.
81 about the parent message.
79 """
82 """
80 super(IPythonKernel, self).set_parent(ident, parent)
83 super(IPythonKernel, self).set_parent(ident, parent)
81 self.shell.set_parent(parent)
84 self.shell.set_parent(parent)
82
85
83 def _forward_input(self, allow_stdin=False):
86 def _forward_input(self, allow_stdin=False):
84 """Forward raw_input and getpass to the current frontend.
87 """Forward raw_input and getpass to the current frontend.
85
88
86 via input_request
89 via input_request
87 """
90 """
88 self._allow_stdin = allow_stdin
91 self._allow_stdin = allow_stdin
89
92
90 if PY3:
93 if PY3:
91 self._sys_raw_input = builtin_mod.input
94 self._sys_raw_input = builtin_mod.input
92 builtin_mod.input = self.raw_input
95 builtin_mod.input = self.raw_input
93 else:
96 else:
94 self._sys_raw_input = builtin_mod.raw_input
97 self._sys_raw_input = builtin_mod.raw_input
95 self._sys_eval_input = builtin_mod.input
98 self._sys_eval_input = builtin_mod.input
96 builtin_mod.raw_input = self.raw_input
99 builtin_mod.raw_input = self.raw_input
97 builtin_mod.input = lambda prompt='': eval(self.raw_input(prompt))
100 builtin_mod.input = lambda prompt='': eval(self.raw_input(prompt))
98 self._save_getpass = getpass.getpass
101 self._save_getpass = getpass.getpass
99 getpass.getpass = self.getpass
102 getpass.getpass = self.getpass
100
103
101 def _restore_input(self):
104 def _restore_input(self):
102 """Restore raw_input, getpass"""
105 """Restore raw_input, getpass"""
103 if PY3:
106 if PY3:
104 builtin_mod.input = self._sys_raw_input
107 builtin_mod.input = self._sys_raw_input
105 else:
108 else:
106 builtin_mod.raw_input = self._sys_raw_input
109 builtin_mod.raw_input = self._sys_raw_input
107 builtin_mod.input = self._sys_eval_input
110 builtin_mod.input = self._sys_eval_input
108
111
109 getpass.getpass = self._save_getpass
112 getpass.getpass = self._save_getpass
110
113
111 @property
114 @property
112 def execution_count(self):
115 def execution_count(self):
113 return self.shell.execution_count
116 return self.shell.execution_count
114
117
115 @execution_count.setter
118 @execution_count.setter
116 def execution_count(self, value):
119 def execution_count(self, value):
117 # Ignore the incrememnting done by KernelBase, in favour of our shell's
120 # Ignore the incrememnting done by KernelBase, in favour of our shell's
118 # execution counter.
121 # execution counter.
119 pass
122 pass
120
123
121 def do_execute(self, code, silent, store_history=True,
124 def do_execute(self, code, silent, store_history=True,
122 user_expressions=None, allow_stdin=False):
125 user_expressions=None, allow_stdin=False):
123 shell = self.shell # we'll need this a lot here
126 shell = self.shell # we'll need this a lot here
124
127
125 self._forward_input(allow_stdin)
128 self._forward_input(allow_stdin)
126
129
127 reply_content = {}
130 reply_content = {}
128 # FIXME: the shell calls the exception handler itself.
131 # FIXME: the shell calls the exception handler itself.
129 shell._reply_content = None
132 shell._reply_content = None
130 try:
133 try:
131 shell.run_cell(code, store_history=store_history, silent=silent)
134 shell.run_cell(code, store_history=store_history, silent=silent)
132 except:
135 except:
133 status = u'error'
136 status = u'error'
134 # FIXME: this code right now isn't being used yet by default,
137 # FIXME: this code right now isn't being used yet by default,
135 # because the run_cell() call above directly fires off exception
138 # because the run_cell() call above directly fires off exception
136 # reporting. This code, therefore, is only active in the scenario
139 # reporting. This code, therefore, is only active in the scenario
137 # where runlines itself has an unhandled exception. We need to
140 # where runlines itself has an unhandled exception. We need to
138 # uniformize this, for all exception construction to come from a
141 # uniformize this, for all exception construction to come from a
139 # single location in the codbase.
142 # single location in the codbase.
140 etype, evalue, tb = sys.exc_info()
143 etype, evalue, tb = sys.exc_info()
141 tb_list = traceback.format_exception(etype, evalue, tb)
144 tb_list = traceback.format_exception(etype, evalue, tb)
142 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
145 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
143 else:
146 else:
144 status = u'ok'
147 status = u'ok'
145 finally:
148 finally:
146 self._restore_input()
149 self._restore_input()
147
150
148 reply_content[u'status'] = status
151 reply_content[u'status'] = status
149
152
150 # Return the execution counter so clients can display prompts
153 # Return the execution counter so clients can display prompts
151 reply_content['execution_count'] = shell.execution_count - 1
154 reply_content['execution_count'] = shell.execution_count - 1
152
155
153 # FIXME - fish exception info out of shell, possibly left there by
156 # FIXME - fish exception info out of shell, possibly left there by
154 # runlines. We'll need to clean up this logic later.
157 # runlines. We'll need to clean up this logic later.
155 if shell._reply_content is not None:
158 if shell._reply_content is not None:
156 reply_content.update(shell._reply_content)
159 reply_content.update(shell._reply_content)
157 e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='execute')
160 e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='execute')
158 reply_content['engine_info'] = e_info
161 reply_content['engine_info'] = e_info
159 # reset after use
162 # reset after use
160 shell._reply_content = None
163 shell._reply_content = None
161
164
162 if 'traceback' in reply_content:
165 if 'traceback' in reply_content:
163 self.log.info("Exception in execute request:\n%s", '\n'.join(reply_content['traceback']))
166 self.log.info("Exception in execute request:\n%s", '\n'.join(reply_content['traceback']))
164
167
165
168
166 # At this point, we can tell whether the main code execution succeeded
169 # At this point, we can tell whether the main code execution succeeded
167 # or not. If it did, we proceed to evaluate user_expressions
170 # or not. If it did, we proceed to evaluate user_expressions
168 if reply_content['status'] == 'ok':
171 if reply_content['status'] == 'ok':
169 reply_content[u'user_expressions'] = \
172 reply_content[u'user_expressions'] = \
170 shell.user_expressions(user_expressions or {})
173 shell.user_expressions(user_expressions or {})
171 else:
174 else:
172 # If there was an error, don't even try to compute expressions
175 # If there was an error, don't even try to compute expressions
173 reply_content[u'user_expressions'] = {}
176 reply_content[u'user_expressions'] = {}
174
177
175 # Payloads should be retrieved regardless of outcome, so we can both
178 # Payloads should be retrieved regardless of outcome, so we can both
176 # recover partial output (that could have been generated early in a
179 # recover partial output (that could have been generated early in a
177 # block, before an error) and clear the payload system always.
180 # block, before an error) and clear the payload system always.
178 reply_content[u'payload'] = shell.payload_manager.read_payload()
181 reply_content[u'payload'] = shell.payload_manager.read_payload()
179 # Be agressive about clearing the payload because we don't want
182 # Be agressive about clearing the payload because we don't want
180 # it to sit in memory until the next execute_request comes in.
183 # it to sit in memory until the next execute_request comes in.
181 shell.payload_manager.clear_payload()
184 shell.payload_manager.clear_payload()
182
185
183 return reply_content
186 return reply_content
184
187
185 def do_complete(self, code, cursor_pos):
188 def do_complete(self, code, cursor_pos):
186 txt, matches = self.shell.complete('', code, cursor_pos)
189 txt, matches = self.shell.complete('', code, cursor_pos)
187 return {'matches' : matches,
190 return {'matches' : matches,
188 'cursor_end' : cursor_pos,
191 'cursor_end' : cursor_pos,
189 'cursor_start' : cursor_pos - len(txt),
192 'cursor_start' : cursor_pos - len(txt),
190 'metadata' : {},
193 'metadata' : {},
191 'status' : 'ok'}
194 'status' : 'ok'}
192
195
193 def do_inspect(self, code, cursor_pos, detail_level=0):
196 def do_inspect(self, code, cursor_pos, detail_level=0):
194 name = token_at_cursor(code, cursor_pos)
197 name = token_at_cursor(code, cursor_pos)
195 info = self.shell.object_inspect(name)
198 info = self.shell.object_inspect(name)
196
199
197 reply_content = {'status' : 'ok'}
200 reply_content = {'status' : 'ok'}
198 reply_content['data'] = data = {}
201 reply_content['data'] = data = {}
199 reply_content['metadata'] = {}
202 reply_content['metadata'] = {}
200 reply_content['found'] = info['found']
203 reply_content['found'] = info['found']
201 if info['found']:
204 if info['found']:
202 info_text = self.shell.object_inspect_text(
205 info_text = self.shell.object_inspect_text(
203 name,
206 name,
204 detail_level=detail_level,
207 detail_level=detail_level,
205 )
208 )
206 data['text/plain'] = info_text
209 data['text/plain'] = info_text
207
210
208 return reply_content
211 return reply_content
209
212
210 def do_history(self, hist_access_type, output, raw, session=None, start=None,
213 def do_history(self, hist_access_type, output, raw, session=None, start=None,
211 stop=None, n=None, pattern=None, unique=False):
214 stop=None, n=None, pattern=None, unique=False):
212 if hist_access_type == 'tail':
215 if hist_access_type == 'tail':
213 hist = self.shell.history_manager.get_tail(n, raw=raw, output=output,
216 hist = self.shell.history_manager.get_tail(n, raw=raw, output=output,
214 include_latest=True)
217 include_latest=True)
215
218
216 elif hist_access_type == 'range':
219 elif hist_access_type == 'range':
217 hist = self.shell.history_manager.get_range(session, start, stop,
220 hist = self.shell.history_manager.get_range(session, start, stop,
218 raw=raw, output=output)
221 raw=raw, output=output)
219
222
220 elif hist_access_type == 'search':
223 elif hist_access_type == 'search':
221 hist = self.shell.history_manager.search(
224 hist = self.shell.history_manager.search(
222 pattern, raw=raw, output=output, n=n, unique=unique)
225 pattern, raw=raw, output=output, n=n, unique=unique)
223 else:
226 else:
224 hist = []
227 hist = []
225
228
226 return {'history' : list(hist)}
229 return {'history' : list(hist)}
227
230
228 def do_shutdown(self, restart):
231 def do_shutdown(self, restart):
229 self.shell.exit_now = True
232 self.shell.exit_now = True
230 return dict(status='ok', restart=restart)
233 return dict(status='ok', restart=restart)
231
234
232 def do_apply(self, content, bufs, msg_id, reply_metadata):
235 def do_apply(self, content, bufs, msg_id, reply_metadata):
233 shell = self.shell
236 shell = self.shell
234 try:
237 try:
235 working = shell.user_ns
238 working = shell.user_ns
236
239
237 prefix = "_"+str(msg_id).replace("-","")+"_"
240 prefix = "_"+str(msg_id).replace("-","")+"_"
238
241
239 f,args,kwargs = unpack_apply_message(bufs, working, copy=False)
242 f,args,kwargs = unpack_apply_message(bufs, working, copy=False)
240
243
241 fname = getattr(f, '__name__', 'f')
244 fname = getattr(f, '__name__', 'f')
242
245
243 fname = prefix+"f"
246 fname = prefix+"f"
244 argname = prefix+"args"
247 argname = prefix+"args"
245 kwargname = prefix+"kwargs"
248 kwargname = prefix+"kwargs"
246 resultname = prefix+"result"
249 resultname = prefix+"result"
247
250
248 ns = { fname : f, argname : args, kwargname : kwargs , resultname : None }
251 ns = { fname : f, argname : args, kwargname : kwargs , resultname : None }
249 # print ns
252 # print ns
250 working.update(ns)
253 working.update(ns)
251 code = "%s = %s(*%s,**%s)" % (resultname, fname, argname, kwargname)
254 code = "%s = %s(*%s,**%s)" % (resultname, fname, argname, kwargname)
252 try:
255 try:
253 exec(code, shell.user_global_ns, shell.user_ns)
256 exec(code, shell.user_global_ns, shell.user_ns)
254 result = working.get(resultname)
257 result = working.get(resultname)
255 finally:
258 finally:
256 for key in ns:
259 for key in ns:
257 working.pop(key)
260 working.pop(key)
258
261
259 result_buf = serialize_object(result,
262 result_buf = serialize_object(result,
260 buffer_threshold=self.session.buffer_threshold,
263 buffer_threshold=self.session.buffer_threshold,
261 item_threshold=self.session.item_threshold,
264 item_threshold=self.session.item_threshold,
262 )
265 )
263
266
264 except:
267 except:
265 # invoke IPython traceback formatting
268 # invoke IPython traceback formatting
266 shell.showtraceback()
269 shell.showtraceback()
267 # FIXME - fish exception info out of shell, possibly left there by
270 # FIXME - fish exception info out of shell, possibly left there by
268 # run_code. We'll need to clean up this logic later.
271 # run_code. We'll need to clean up this logic later.
269 reply_content = {}
272 reply_content = {}
270 if shell._reply_content is not None:
273 if shell._reply_content is not None:
271 reply_content.update(shell._reply_content)
274 reply_content.update(shell._reply_content)
272 e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='apply')
275 e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='apply')
273 reply_content['engine_info'] = e_info
276 reply_content['engine_info'] = e_info
274 # reset after use
277 # reset after use
275 shell._reply_content = None
278 shell._reply_content = None
276
279
277 self.send_response(self.iopub_socket, u'error', reply_content,
280 self.send_response(self.iopub_socket, u'error', reply_content,
278 ident=self._topic('error'))
281 ident=self._topic('error'))
279 self.log.info("Exception in apply request:\n%s", '\n'.join(reply_content['traceback']))
282 self.log.info("Exception in apply request:\n%s", '\n'.join(reply_content['traceback']))
280 result_buf = []
283 result_buf = []
281
284
282 if reply_content['ename'] == 'UnmetDependency':
285 if reply_content['ename'] == 'UnmetDependency':
283 reply_metadata['dependencies_met'] = False
286 reply_metadata['dependencies_met'] = False
284 else:
287 else:
285 reply_content = {'status' : 'ok'}
288 reply_content = {'status' : 'ok'}
286
289
287 return reply_content, result_buf
290 return reply_content, result_buf
288
291
289 def do_clear(self):
292 def do_clear(self):
290 self.shell.reset(False)
293 self.shell.reset(False)
291 return dict(status='ok')
294 return dict(status='ok')
292
295
293
296
294 # This exists only for backwards compatibility - use IPythonKernel instead
297 # This exists only for backwards compatibility - use IPythonKernel instead
295
298
296 @undoc
299 @undoc
297 class Kernel(IPythonKernel):
300 class Kernel(IPythonKernel):
298 def __init__(self, *args, **kwargs):
301 def __init__(self, *args, **kwargs):
299 import warnings
302 import warnings
300 warnings.warn('Kernel is a deprecated alias of IPython.kernel.zmq.ipkernel.IPythonKernel',
303 warnings.warn('Kernel is a deprecated alias of IPython.kernel.zmq.ipkernel.IPythonKernel',
301 DeprecationWarning)
304 DeprecationWarning)
302 super(Kernel, self).__init__(*args, **kwargs) No newline at end of file
305 super(Kernel, self).__init__(*args, **kwargs)
@@ -1,395 +1,395 b''
1 """An Application for launching a kernel"""
1 """An Application for launching a kernel"""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 from __future__ import print_function
6 from __future__ import print_function
7
7
8 import atexit
8 import atexit
9 import os
9 import os
10 import sys
10 import sys
11 import signal
11 import signal
12
12
13 import zmq
13 import zmq
14 from zmq.eventloop import ioloop
14 from zmq.eventloop import ioloop
15 from zmq.eventloop.zmqstream import ZMQStream
15 from zmq.eventloop.zmqstream import ZMQStream
16
16
17 from IPython.core.ultratb import FormattedTB
17 from IPython.core.ultratb import FormattedTB
18 from IPython.core.application import (
18 from IPython.core.application import (
19 BaseIPythonApplication, base_flags, base_aliases, catch_config_error
19 BaseIPythonApplication, base_flags, base_aliases, catch_config_error
20 )
20 )
21 from IPython.core.profiledir import ProfileDir
21 from IPython.core.profiledir import ProfileDir
22 from IPython.core.shellapp import (
22 from IPython.core.shellapp import (
23 InteractiveShellApp, shell_flags, shell_aliases
23 InteractiveShellApp, shell_flags, shell_aliases
24 )
24 )
25 from IPython.utils import io
25 from IPython.utils import io
26 from IPython.utils.path import filefind
26 from IPython.utils.path import filefind
27 from IPython.utils.traitlets import (
27 from IPython.utils.traitlets import (
28 Any, Instance, Dict, Unicode, Integer, Bool, DottedObjectName, Type,
28 Any, Instance, Dict, Unicode, Integer, Bool, DottedObjectName, Type,
29 )
29 )
30 from IPython.utils.importstring import import_item
30 from IPython.utils.importstring import import_item
31 from IPython.kernel import write_connection_file
31 from IPython.kernel import write_connection_file
32 from IPython.kernel.connect import ConnectionFileMixin
32 from IPython.kernel.connect import ConnectionFileMixin
33
33
34 # local imports
34 # local imports
35 from .heartbeat import Heartbeat
35 from .heartbeat import Heartbeat
36 from .ipkernel import IPythonKernel
36 from .ipkernel import IPythonKernel
37 from .parentpoller import ParentPollerUnix, ParentPollerWindows
37 from .parentpoller import ParentPollerUnix, ParentPollerWindows
38 from .session import (
38 from .session import (
39 Session, session_flags, session_aliases, default_secure,
39 Session, session_flags, session_aliases, default_secure,
40 )
40 )
41 from .zmqshell import ZMQInteractiveShell
41 from .zmqshell import ZMQInteractiveShell
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Flags and Aliases
44 # Flags and Aliases
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 kernel_aliases = dict(base_aliases)
47 kernel_aliases = dict(base_aliases)
48 kernel_aliases.update({
48 kernel_aliases.update({
49 'ip' : 'IPKernelApp.ip',
49 'ip' : 'IPKernelApp.ip',
50 'hb' : 'IPKernelApp.hb_port',
50 'hb' : 'IPKernelApp.hb_port',
51 'shell' : 'IPKernelApp.shell_port',
51 'shell' : 'IPKernelApp.shell_port',
52 'iopub' : 'IPKernelApp.iopub_port',
52 'iopub' : 'IPKernelApp.iopub_port',
53 'stdin' : 'IPKernelApp.stdin_port',
53 'stdin' : 'IPKernelApp.stdin_port',
54 'control' : 'IPKernelApp.control_port',
54 'control' : 'IPKernelApp.control_port',
55 'f' : 'IPKernelApp.connection_file',
55 'f' : 'IPKernelApp.connection_file',
56 'parent': 'IPKernelApp.parent_handle',
56 'parent': 'IPKernelApp.parent_handle',
57 'transport': 'IPKernelApp.transport',
57 'transport': 'IPKernelApp.transport',
58 })
58 })
59 if sys.platform.startswith('win'):
59 if sys.platform.startswith('win'):
60 kernel_aliases['interrupt'] = 'IPKernelApp.interrupt'
60 kernel_aliases['interrupt'] = 'IPKernelApp.interrupt'
61
61
62 kernel_flags = dict(base_flags)
62 kernel_flags = dict(base_flags)
63 kernel_flags.update({
63 kernel_flags.update({
64 'no-stdout' : (
64 'no-stdout' : (
65 {'IPKernelApp' : {'no_stdout' : True}},
65 {'IPKernelApp' : {'no_stdout' : True}},
66 "redirect stdout to the null device"),
66 "redirect stdout to the null device"),
67 'no-stderr' : (
67 'no-stderr' : (
68 {'IPKernelApp' : {'no_stderr' : True}},
68 {'IPKernelApp' : {'no_stderr' : True}},
69 "redirect stderr to the null device"),
69 "redirect stderr to the null device"),
70 'pylab' : (
70 'pylab' : (
71 {'IPKernelApp' : {'pylab' : 'auto'}},
71 {'IPKernelApp' : {'pylab' : 'auto'}},
72 """Pre-load matplotlib and numpy for interactive use with
72 """Pre-load matplotlib and numpy for interactive use with
73 the default matplotlib backend."""),
73 the default matplotlib backend."""),
74 })
74 })
75
75
76 # inherit flags&aliases for any IPython shell apps
76 # inherit flags&aliases for any IPython shell apps
77 kernel_aliases.update(shell_aliases)
77 kernel_aliases.update(shell_aliases)
78 kernel_flags.update(shell_flags)
78 kernel_flags.update(shell_flags)
79
79
80 # inherit flags&aliases for Sessions
80 # inherit flags&aliases for Sessions
81 kernel_aliases.update(session_aliases)
81 kernel_aliases.update(session_aliases)
82 kernel_flags.update(session_flags)
82 kernel_flags.update(session_flags)
83
83
84 _ctrl_c_message = """\
84 _ctrl_c_message = """\
85 NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.
85 NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.
86
86
87 To exit, you will have to explicitly quit this process, by either sending
87 To exit, you will have to explicitly quit this process, by either sending
88 "quit" from a client, or using Ctrl-\\ in UNIX-like environments.
88 "quit" from a client, or using Ctrl-\\ in UNIX-like environments.
89
89
90 To read more about this, see https://github.com/ipython/ipython/issues/2049
90 To read more about this, see https://github.com/ipython/ipython/issues/2049
91
91
92 """
92 """
93
93
94 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
95 # Application class for starting an IPython Kernel
95 # Application class for starting an IPython Kernel
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97
97
98 class IPKernelApp(BaseIPythonApplication, InteractiveShellApp,
98 class IPKernelApp(BaseIPythonApplication, InteractiveShellApp,
99 ConnectionFileMixin):
99 ConnectionFileMixin):
100 name='ipkernel'
100 name='ipkernel'
101 aliases = Dict(kernel_aliases)
101 aliases = Dict(kernel_aliases)
102 flags = Dict(kernel_flags)
102 flags = Dict(kernel_flags)
103 classes = [IPythonKernel, ZMQInteractiveShell, ProfileDir, Session]
103 classes = [IPythonKernel, ZMQInteractiveShell, ProfileDir, Session]
104 # the kernel class, as an importstring
104 # the kernel class, as an importstring
105 kernel_class = Type('IPython.kernel.zmq.ipkernel.IPythonKernel', config=True,
105 kernel_class = Type('IPython.kernel.zmq.ipkernel.IPythonKernel', config=True,
106 klass='IPython.kernel.zmq.kernelbase.Kernel',
106 klass='IPython.kernel.zmq.kernelbase.Kernel',
107 help="""The Kernel subclass to be used.
107 help="""The Kernel subclass to be used.
108
108
109 This should allow easy re-use of the IPKernelApp entry point
109 This should allow easy re-use of the IPKernelApp entry point
110 to configure and launch kernels other than IPython's own.
110 to configure and launch kernels other than IPython's own.
111 """)
111 """)
112 kernel = Any()
112 kernel = Any()
113 poller = Any() # don't restrict this even though current pollers are all Threads
113 poller = Any() # don't restrict this even though current pollers are all Threads
114 heartbeat = Instance(Heartbeat)
114 heartbeat = Instance(Heartbeat)
115 ports = Dict()
115 ports = Dict()
116
116
117 # ipkernel doesn't get its own config file
117 # ipkernel doesn't get its own config file
118 def _config_file_name_default(self):
118 def _config_file_name_default(self):
119 return 'ipython_config.py'
119 return 'ipython_config.py'
120
120
121 # connection info:
121 # connection info:
122
122
123 @property
123 @property
124 def abs_connection_file(self):
124 def abs_connection_file(self):
125 if os.path.basename(self.connection_file) == self.connection_file:
125 if os.path.basename(self.connection_file) == self.connection_file:
126 return os.path.join(self.profile_dir.security_dir, self.connection_file)
126 return os.path.join(self.profile_dir.security_dir, self.connection_file)
127 else:
127 else:
128 return self.connection_file
128 return self.connection_file
129
129
130
130
131 # streams, etc.
131 # streams, etc.
132 no_stdout = Bool(False, config=True, help="redirect stdout to the null device")
132 no_stdout = Bool(False, config=True, help="redirect stdout to the null device")
133 no_stderr = Bool(False, config=True, help="redirect stderr to the null device")
133 no_stderr = Bool(False, config=True, help="redirect stderr to the null device")
134 outstream_class = DottedObjectName('IPython.kernel.zmq.iostream.OutStream',
134 outstream_class = DottedObjectName('IPython.kernel.zmq.iostream.OutStream',
135 config=True, help="The importstring for the OutStream factory")
135 config=True, help="The importstring for the OutStream factory")
136 displayhook_class = DottedObjectName('IPython.kernel.zmq.displayhook.ZMQDisplayHook',
136 displayhook_class = DottedObjectName('IPython.kernel.zmq.displayhook.ZMQDisplayHook',
137 config=True, help="The importstring for the DisplayHook factory")
137 config=True, help="The importstring for the DisplayHook factory")
138
138
139 # polling
139 # polling
140 parent_handle = Integer(0, config=True,
140 parent_handle = Integer(0, config=True,
141 help="""kill this process if its parent dies. On Windows, the argument
141 help="""kill this process if its parent dies. On Windows, the argument
142 specifies the HANDLE of the parent process, otherwise it is simply boolean.
142 specifies the HANDLE of the parent process, otherwise it is simply boolean.
143 """)
143 """)
144 interrupt = Integer(0, config=True,
144 interrupt = Integer(0, config=True,
145 help="""ONLY USED ON WINDOWS
145 help="""ONLY USED ON WINDOWS
146 Interrupt this process when the parent is signaled.
146 Interrupt this process when the parent is signaled.
147 """)
147 """)
148
148
149 def init_crash_handler(self):
149 def init_crash_handler(self):
150 # Install minimal exception handling
150 # Install minimal exception handling
151 sys.excepthook = FormattedTB(mode='Verbose', color_scheme='NoColor',
151 sys.excepthook = FormattedTB(mode='Verbose', color_scheme='NoColor',
152 ostream=sys.__stdout__)
152 ostream=sys.__stdout__)
153
153
154 def init_poller(self):
154 def init_poller(self):
155 if sys.platform == 'win32':
155 if sys.platform == 'win32':
156 if self.interrupt or self.parent_handle:
156 if self.interrupt or self.parent_handle:
157 self.poller = ParentPollerWindows(self.interrupt, self.parent_handle)
157 self.poller = ParentPollerWindows(self.interrupt, self.parent_handle)
158 elif self.parent_handle:
158 elif self.parent_handle:
159 self.poller = ParentPollerUnix()
159 self.poller = ParentPollerUnix()
160
160
161 def _bind_socket(self, s, port):
161 def _bind_socket(self, s, port):
162 iface = '%s://%s' % (self.transport, self.ip)
162 iface = '%s://%s' % (self.transport, self.ip)
163 if self.transport == 'tcp':
163 if self.transport == 'tcp':
164 if port <= 0:
164 if port <= 0:
165 port = s.bind_to_random_port(iface)
165 port = s.bind_to_random_port(iface)
166 else:
166 else:
167 s.bind("tcp://%s:%i" % (self.ip, port))
167 s.bind("tcp://%s:%i" % (self.ip, port))
168 elif self.transport == 'ipc':
168 elif self.transport == 'ipc':
169 if port <= 0:
169 if port <= 0:
170 port = 1
170 port = 1
171 path = "%s-%i" % (self.ip, port)
171 path = "%s-%i" % (self.ip, port)
172 while os.path.exists(path):
172 while os.path.exists(path):
173 port = port + 1
173 port = port + 1
174 path = "%s-%i" % (self.ip, port)
174 path = "%s-%i" % (self.ip, port)
175 else:
175 else:
176 path = "%s-%i" % (self.ip, port)
176 path = "%s-%i" % (self.ip, port)
177 s.bind("ipc://%s" % path)
177 s.bind("ipc://%s" % path)
178 return port
178 return port
179
179
180 def write_connection_file(self):
180 def write_connection_file(self):
181 """write connection info to JSON file"""
181 """write connection info to JSON file"""
182 cf = self.abs_connection_file
182 cf = self.abs_connection_file
183 self.log.debug("Writing connection file: %s", cf)
183 self.log.debug("Writing connection file: %s", cf)
184 write_connection_file(cf, ip=self.ip, key=self.session.key, transport=self.transport,
184 write_connection_file(cf, ip=self.ip, key=self.session.key, transport=self.transport,
185 shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port,
185 shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port,
186 iopub_port=self.iopub_port, control_port=self.control_port)
186 iopub_port=self.iopub_port, control_port=self.control_port)
187
187
188 def cleanup_connection_file(self):
188 def cleanup_connection_file(self):
189 cf = self.abs_connection_file
189 cf = self.abs_connection_file
190 self.log.debug("Cleaning up connection file: %s", cf)
190 self.log.debug("Cleaning up connection file: %s", cf)
191 try:
191 try:
192 os.remove(cf)
192 os.remove(cf)
193 except (IOError, OSError):
193 except (IOError, OSError):
194 pass
194 pass
195
195
196 self.cleanup_ipc_files()
196 self.cleanup_ipc_files()
197
197
198 def init_connection_file(self):
198 def init_connection_file(self):
199 if not self.connection_file:
199 if not self.connection_file:
200 self.connection_file = "kernel-%s.json"%os.getpid()
200 self.connection_file = "kernel-%s.json"%os.getpid()
201 try:
201 try:
202 self.connection_file = filefind(self.connection_file, ['.', self.profile_dir.security_dir])
202 self.connection_file = filefind(self.connection_file, ['.', self.profile_dir.security_dir])
203 except IOError:
203 except IOError:
204 self.log.debug("Connection file not found: %s", self.connection_file)
204 self.log.debug("Connection file not found: %s", self.connection_file)
205 # This means I own it, so I will clean it up:
205 # This means I own it, so I will clean it up:
206 atexit.register(self.cleanup_connection_file)
206 atexit.register(self.cleanup_connection_file)
207 return
207 return
208 try:
208 try:
209 self.load_connection_file()
209 self.load_connection_file()
210 except Exception:
210 except Exception:
211 self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True)
211 self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True)
212 self.exit(1)
212 self.exit(1)
213
213
214 def init_sockets(self):
214 def init_sockets(self):
215 # Create a context, a session, and the kernel sockets.
215 # Create a context, a session, and the kernel sockets.
216 self.log.info("Starting the kernel at pid: %i", os.getpid())
216 self.log.info("Starting the kernel at pid: %i", os.getpid())
217 context = zmq.Context.instance()
217 context = zmq.Context.instance()
218 # Uncomment this to try closing the context.
218 # Uncomment this to try closing the context.
219 # atexit.register(context.term)
219 # atexit.register(context.term)
220
220
221 self.shell_socket = context.socket(zmq.ROUTER)
221 self.shell_socket = context.socket(zmq.ROUTER)
222 self.shell_socket.linger = 1000
222 self.shell_socket.linger = 1000
223 self.shell_port = self._bind_socket(self.shell_socket, self.shell_port)
223 self.shell_port = self._bind_socket(self.shell_socket, self.shell_port)
224 self.log.debug("shell ROUTER Channel on port: %i" % self.shell_port)
224 self.log.debug("shell ROUTER Channel on port: %i" % self.shell_port)
225
225
226 self.iopub_socket = context.socket(zmq.PUB)
226 self.iopub_socket = context.socket(zmq.PUB)
227 self.iopub_socket.linger = 1000
227 self.iopub_socket.linger = 1000
228 self.iopub_port = self._bind_socket(self.iopub_socket, self.iopub_port)
228 self.iopub_port = self._bind_socket(self.iopub_socket, self.iopub_port)
229 self.log.debug("iopub PUB Channel on port: %i" % self.iopub_port)
229 self.log.debug("iopub PUB Channel on port: %i" % self.iopub_port)
230
230
231 self.stdin_socket = context.socket(zmq.ROUTER)
231 self.stdin_socket = context.socket(zmq.ROUTER)
232 self.stdin_socket.linger = 1000
232 self.stdin_socket.linger = 1000
233 self.stdin_port = self._bind_socket(self.stdin_socket, self.stdin_port)
233 self.stdin_port = self._bind_socket(self.stdin_socket, self.stdin_port)
234 self.log.debug("stdin ROUTER Channel on port: %i" % self.stdin_port)
234 self.log.debug("stdin ROUTER Channel on port: %i" % self.stdin_port)
235
235
236 self.control_socket = context.socket(zmq.ROUTER)
236 self.control_socket = context.socket(zmq.ROUTER)
237 self.control_socket.linger = 1000
237 self.control_socket.linger = 1000
238 self.control_port = self._bind_socket(self.control_socket, self.control_port)
238 self.control_port = self._bind_socket(self.control_socket, self.control_port)
239 self.log.debug("control ROUTER Channel on port: %i" % self.control_port)
239 self.log.debug("control ROUTER Channel on port: %i" % self.control_port)
240
240
241 def init_heartbeat(self):
241 def init_heartbeat(self):
242 """start the heart beating"""
242 """start the heart beating"""
243 # heartbeat doesn't share context, because it mustn't be blocked
243 # heartbeat doesn't share context, because it mustn't be blocked
244 # by the GIL, which is accessed by libzmq when freeing zero-copy messages
244 # by the GIL, which is accessed by libzmq when freeing zero-copy messages
245 hb_ctx = zmq.Context()
245 hb_ctx = zmq.Context()
246 self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port))
246 self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port))
247 self.hb_port = self.heartbeat.port
247 self.hb_port = self.heartbeat.port
248 self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port)
248 self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port)
249 self.heartbeat.start()
249 self.heartbeat.start()
250
250
251 def log_connection_info(self):
251 def log_connection_info(self):
252 """display connection info, and store ports"""
252 """display connection info, and store ports"""
253 basename = os.path.basename(self.connection_file)
253 basename = os.path.basename(self.connection_file)
254 if basename == self.connection_file or \
254 if basename == self.connection_file or \
255 os.path.dirname(self.connection_file) == self.profile_dir.security_dir:
255 os.path.dirname(self.connection_file) == self.profile_dir.security_dir:
256 # use shortname
256 # use shortname
257 tail = basename
257 tail = basename
258 if self.profile != 'default':
258 if self.profile != 'default':
259 tail += " --profile %s" % self.profile
259 tail += " --profile %s" % self.profile
260 else:
260 else:
261 tail = self.connection_file
261 tail = self.connection_file
262 lines = [
262 lines = [
263 "To connect another client to this kernel, use:",
263 "To connect another client to this kernel, use:",
264 " --existing %s" % tail,
264 " --existing %s" % tail,
265 ]
265 ]
266 # log connection info
266 # log connection info
267 # info-level, so often not shown.
267 # info-level, so often not shown.
268 # frontends should use the %connect_info magic
268 # frontends should use the %connect_info magic
269 # to see the connection info
269 # to see the connection info
270 for line in lines:
270 for line in lines:
271 self.log.info(line)
271 self.log.info(line)
272 # also raw print to the terminal if no parent_handle (`ipython kernel`)
272 # also raw print to the terminal if no parent_handle (`ipython kernel`)
273 if not self.parent_handle:
273 if not self.parent_handle:
274 io.rprint(_ctrl_c_message)
274 io.rprint(_ctrl_c_message)
275 for line in lines:
275 for line in lines:
276 io.rprint(line)
276 io.rprint(line)
277
277
278 self.ports = dict(shell=self.shell_port, iopub=self.iopub_port,
278 self.ports = dict(shell=self.shell_port, iopub=self.iopub_port,
279 stdin=self.stdin_port, hb=self.hb_port,
279 stdin=self.stdin_port, hb=self.hb_port,
280 control=self.control_port)
280 control=self.control_port)
281
281
282 def init_blackhole(self):
282 def init_blackhole(self):
283 """redirects stdout/stderr to devnull if necessary"""
283 """redirects stdout/stderr to devnull if necessary"""
284 if self.no_stdout or self.no_stderr:
284 if self.no_stdout or self.no_stderr:
285 blackhole = open(os.devnull, 'w')
285 blackhole = open(os.devnull, 'w')
286 if self.no_stdout:
286 if self.no_stdout:
287 sys.stdout = sys.__stdout__ = blackhole
287 sys.stdout = sys.__stdout__ = blackhole
288 if self.no_stderr:
288 if self.no_stderr:
289 sys.stderr = sys.__stderr__ = blackhole
289 sys.stderr = sys.__stderr__ = blackhole
290
290
291 def init_io(self):
291 def init_io(self):
292 """Redirect input streams and set a display hook."""
292 """Redirect input streams and set a display hook."""
293 if self.outstream_class:
293 if self.outstream_class:
294 outstream_factory = import_item(str(self.outstream_class))
294 outstream_factory = import_item(str(self.outstream_class))
295 sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout')
295 sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout')
296 sys.stderr = outstream_factory(self.session, self.iopub_socket, u'stderr')
296 sys.stderr = outstream_factory(self.session, self.iopub_socket, u'stderr')
297 if self.displayhook_class:
297 if self.displayhook_class:
298 displayhook_factory = import_item(str(self.displayhook_class))
298 displayhook_factory = import_item(str(self.displayhook_class))
299 sys.displayhook = displayhook_factory(self.session, self.iopub_socket)
299 sys.displayhook = displayhook_factory(self.session, self.iopub_socket)
300
300
301 def init_signal(self):
301 def init_signal(self):
302 signal.signal(signal.SIGINT, signal.SIG_IGN)
302 signal.signal(signal.SIGINT, signal.SIG_IGN)
303
303
304 def init_kernel(self):
304 def init_kernel(self):
305 """Create the Kernel object itself"""
305 """Create the Kernel object itself"""
306 shell_stream = ZMQStream(self.shell_socket)
306 shell_stream = ZMQStream(self.shell_socket)
307 control_stream = ZMQStream(self.control_socket)
307 control_stream = ZMQStream(self.control_socket)
308
308
309 kernel_factory = self.kernel_class
309 kernel_factory = self.kernel_class.instance
310
310
311 kernel = kernel_factory(parent=self, session=self.session,
311 kernel = kernel_factory(parent=self, session=self.session,
312 shell_streams=[shell_stream, control_stream],
312 shell_streams=[shell_stream, control_stream],
313 iopub_socket=self.iopub_socket,
313 iopub_socket=self.iopub_socket,
314 stdin_socket=self.stdin_socket,
314 stdin_socket=self.stdin_socket,
315 log=self.log,
315 log=self.log,
316 profile_dir=self.profile_dir,
316 profile_dir=self.profile_dir,
317 user_ns=self.user_ns,
317 user_ns=self.user_ns,
318 )
318 )
319 kernel.record_ports(self.ports)
319 kernel.record_ports(self.ports)
320 self.kernel = kernel
320 self.kernel = kernel
321
321
322 def init_gui_pylab(self):
322 def init_gui_pylab(self):
323 """Enable GUI event loop integration, taking pylab into account."""
323 """Enable GUI event loop integration, taking pylab into account."""
324
324
325 # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`
325 # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`
326 # to ensure that any exception is printed straight to stderr.
326 # to ensure that any exception is printed straight to stderr.
327 # Normally _showtraceback associates the reply with an execution,
327 # Normally _showtraceback associates the reply with an execution,
328 # which means frontends will never draw it, as this exception
328 # which means frontends will never draw it, as this exception
329 # is not associated with any execute request.
329 # is not associated with any execute request.
330
330
331 shell = self.shell
331 shell = self.shell
332 _showtraceback = shell._showtraceback
332 _showtraceback = shell._showtraceback
333 try:
333 try:
334 # replace error-sending traceback with stderr
334 # replace error-sending traceback with stderr
335 def print_tb(etype, evalue, stb):
335 def print_tb(etype, evalue, stb):
336 print ("GUI event loop or pylab initialization failed",
336 print ("GUI event loop or pylab initialization failed",
337 file=io.stderr)
337 file=io.stderr)
338 print (shell.InteractiveTB.stb2text(stb), file=io.stderr)
338 print (shell.InteractiveTB.stb2text(stb), file=io.stderr)
339 shell._showtraceback = print_tb
339 shell._showtraceback = print_tb
340 InteractiveShellApp.init_gui_pylab(self)
340 InteractiveShellApp.init_gui_pylab(self)
341 finally:
341 finally:
342 shell._showtraceback = _showtraceback
342 shell._showtraceback = _showtraceback
343
343
344 def init_shell(self):
344 def init_shell(self):
345 self.shell = getattr(self.kernel, 'shell', None)
345 self.shell = getattr(self.kernel, 'shell', None)
346 if self.shell:
346 if self.shell:
347 self.shell.configurables.append(self)
347 self.shell.configurables.append(self)
348
348
349 @catch_config_error
349 @catch_config_error
350 def initialize(self, argv=None):
350 def initialize(self, argv=None):
351 super(IPKernelApp, self).initialize(argv)
351 super(IPKernelApp, self).initialize(argv)
352 default_secure(self.config)
352 default_secure(self.config)
353 self.init_blackhole()
353 self.init_blackhole()
354 self.init_connection_file()
354 self.init_connection_file()
355 self.init_poller()
355 self.init_poller()
356 self.init_sockets()
356 self.init_sockets()
357 self.init_heartbeat()
357 self.init_heartbeat()
358 # writing/displaying connection info must be *after* init_sockets/heartbeat
358 # writing/displaying connection info must be *after* init_sockets/heartbeat
359 self.log_connection_info()
359 self.log_connection_info()
360 self.write_connection_file()
360 self.write_connection_file()
361 self.init_io()
361 self.init_io()
362 self.init_signal()
362 self.init_signal()
363 self.init_kernel()
363 self.init_kernel()
364 # shell init steps
364 # shell init steps
365 self.init_path()
365 self.init_path()
366 self.init_shell()
366 self.init_shell()
367 if self.shell:
367 if self.shell:
368 self.init_gui_pylab()
368 self.init_gui_pylab()
369 self.init_extensions()
369 self.init_extensions()
370 self.init_code()
370 self.init_code()
371 # flush stdout/stderr, so that anything written to these streams during
371 # flush stdout/stderr, so that anything written to these streams during
372 # initialization do not get associated with the first execution request
372 # initialization do not get associated with the first execution request
373 sys.stdout.flush()
373 sys.stdout.flush()
374 sys.stderr.flush()
374 sys.stderr.flush()
375
375
376 def start(self):
376 def start(self):
377 if self.poller is not None:
377 if self.poller is not None:
378 self.poller.start()
378 self.poller.start()
379 self.kernel.start()
379 self.kernel.start()
380 try:
380 try:
381 ioloop.IOLoop.instance().start()
381 ioloop.IOLoop.instance().start()
382 except KeyboardInterrupt:
382 except KeyboardInterrupt:
383 pass
383 pass
384
384
385 launch_new_instance = IPKernelApp.launch_instance
385 launch_new_instance = IPKernelApp.launch_instance
386
386
387 def main():
387 def main():
388 """Run an IPKernel as an application"""
388 """Run an IPKernel as an application"""
389 app = IPKernelApp.instance()
389 app = IPKernelApp.instance()
390 app.initialize()
390 app.initialize()
391 app.start()
391 app.start()
392
392
393
393
394 if __name__ == '__main__':
394 if __name__ == '__main__':
395 main()
395 main()
@@ -1,676 +1,676 b''
1 """Base class for a kernel that talks to frontends over 0MQ."""
1 """Base class for a kernel that talks to frontends over 0MQ."""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 from __future__ import print_function
6 from __future__ import print_function
7
7
8 import sys
8 import sys
9 import time
9 import time
10 import logging
10 import logging
11 import uuid
11 import uuid
12
12
13 from datetime import datetime
13 from datetime import datetime
14 from signal import (
14 from signal import (
15 signal, default_int_handler, SIGINT
15 signal, default_int_handler, SIGINT
16 )
16 )
17
17
18 import zmq
18 import zmq
19 from zmq.eventloop import ioloop
19 from zmq.eventloop import ioloop
20 from zmq.eventloop.zmqstream import ZMQStream
20 from zmq.eventloop.zmqstream import ZMQStream
21
21
22 from IPython.config.configurable import Configurable
22 from IPython.config.configurable import SingletonConfigurable
23 from IPython.core.error import StdinNotImplementedError
23 from IPython.core.error import StdinNotImplementedError
24 from IPython.core import release
24 from IPython.core import release
25 from IPython.utils import py3compat
25 from IPython.utils import py3compat
26 from IPython.utils.py3compat import unicode_type, string_types
26 from IPython.utils.py3compat import unicode_type, string_types
27 from IPython.utils.jsonutil import json_clean
27 from IPython.utils.jsonutil import json_clean
28 from IPython.utils.traitlets import (
28 from IPython.utils.traitlets import (
29 Any, Instance, Float, Dict, List, Set, Integer, Unicode, Bool,
29 Any, Instance, Float, Dict, List, Set, Integer, Unicode, Bool,
30 )
30 )
31
31
32 from .session import Session
32 from .session import Session
33
33
34
34
35 class Kernel(Configurable):
35 class Kernel(SingletonConfigurable):
36
36
37 #---------------------------------------------------------------------------
37 #---------------------------------------------------------------------------
38 # Kernel interface
38 # Kernel interface
39 #---------------------------------------------------------------------------
39 #---------------------------------------------------------------------------
40
40
41 # attribute to override with a GUI
41 # attribute to override with a GUI
42 eventloop = Any(None)
42 eventloop = Any(None)
43 def _eventloop_changed(self, name, old, new):
43 def _eventloop_changed(self, name, old, new):
44 """schedule call to eventloop from IOLoop"""
44 """schedule call to eventloop from IOLoop"""
45 loop = ioloop.IOLoop.instance()
45 loop = ioloop.IOLoop.instance()
46 loop.add_callback(self.enter_eventloop)
46 loop.add_callback(self.enter_eventloop)
47
47
48 session = Instance(Session)
48 session = Instance(Session)
49 profile_dir = Instance('IPython.core.profiledir.ProfileDir')
49 profile_dir = Instance('IPython.core.profiledir.ProfileDir')
50 shell_streams = List()
50 shell_streams = List()
51 control_stream = Instance(ZMQStream)
51 control_stream = Instance(ZMQStream)
52 iopub_socket = Instance(zmq.Socket)
52 iopub_socket = Instance(zmq.Socket)
53 stdin_socket = Instance(zmq.Socket)
53 stdin_socket = Instance(zmq.Socket)
54 log = Instance(logging.Logger)
54 log = Instance(logging.Logger)
55
55
56 # identities:
56 # identities:
57 int_id = Integer(-1)
57 int_id = Integer(-1)
58 ident = Unicode()
58 ident = Unicode()
59
59
60 def _ident_default(self):
60 def _ident_default(self):
61 return unicode_type(uuid.uuid4())
61 return unicode_type(uuid.uuid4())
62
62
63 # Private interface
63 # Private interface
64
64
65 _darwin_app_nap = Bool(True, config=True,
65 _darwin_app_nap = Bool(True, config=True,
66 help="""Whether to use appnope for compatiblity with OS X App Nap.
66 help="""Whether to use appnope for compatiblity with OS X App Nap.
67
67
68 Only affects OS X >= 10.9.
68 Only affects OS X >= 10.9.
69 """
69 """
70 )
70 )
71
71
72 # track associations with current request
72 # track associations with current request
73 _allow_stdin = Bool(False)
73 _allow_stdin = Bool(False)
74 _parent_header = Dict()
74 _parent_header = Dict()
75 _parent_ident = Any(b'')
75 _parent_ident = Any(b'')
76 # Time to sleep after flushing the stdout/err buffers in each execute
76 # Time to sleep after flushing the stdout/err buffers in each execute
77 # cycle. While this introduces a hard limit on the minimal latency of the
77 # cycle. While this introduces a hard limit on the minimal latency of the
78 # execute cycle, it helps prevent output synchronization problems for
78 # execute cycle, it helps prevent output synchronization problems for
79 # clients.
79 # clients.
80 # Units are in seconds. The minimum zmq latency on local host is probably
80 # Units are in seconds. The minimum zmq latency on local host is probably
81 # ~150 microseconds, set this to 500us for now. We may need to increase it
81 # ~150 microseconds, set this to 500us for now. We may need to increase it
82 # a little if it's not enough after more interactive testing.
82 # a little if it's not enough after more interactive testing.
83 _execute_sleep = Float(0.0005, config=True)
83 _execute_sleep = Float(0.0005, config=True)
84
84
85 # Frequency of the kernel's event loop.
85 # Frequency of the kernel's event loop.
86 # Units are in seconds, kernel subclasses for GUI toolkits may need to
86 # Units are in seconds, kernel subclasses for GUI toolkits may need to
87 # adapt to milliseconds.
87 # adapt to milliseconds.
88 _poll_interval = Float(0.05, config=True)
88 _poll_interval = Float(0.05, config=True)
89
89
90 # If the shutdown was requested over the network, we leave here the
90 # If the shutdown was requested over the network, we leave here the
91 # necessary reply message so it can be sent by our registered atexit
91 # necessary reply message so it can be sent by our registered atexit
92 # handler. This ensures that the reply is only sent to clients truly at
92 # handler. This ensures that the reply is only sent to clients truly at
93 # the end of our shutdown process (which happens after the underlying
93 # the end of our shutdown process (which happens after the underlying
94 # IPython shell's own shutdown).
94 # IPython shell's own shutdown).
95 _shutdown_message = None
95 _shutdown_message = None
96
96
97 # This is a dict of port number that the kernel is listening on. It is set
97 # This is a dict of port number that the kernel is listening on. It is set
98 # by record_ports and used by connect_request.
98 # by record_ports and used by connect_request.
99 _recorded_ports = Dict()
99 _recorded_ports = Dict()
100
100
101 # set of aborted msg_ids
101 # set of aborted msg_ids
102 aborted = Set()
102 aborted = Set()
103
103
104 # Track execution count here. For IPython, we override this to use the
104 # Track execution count here. For IPython, we override this to use the
105 # execution count we store in the shell.
105 # execution count we store in the shell.
106 execution_count = 0
106 execution_count = 0
107
107
108
108
109 def __init__(self, **kwargs):
109 def __init__(self, **kwargs):
110 super(Kernel, self).__init__(**kwargs)
110 super(Kernel, self).__init__(**kwargs)
111
111
112 # Build dict of handlers for message types
112 # Build dict of handlers for message types
113 msg_types = [ 'execute_request', 'complete_request',
113 msg_types = [ 'execute_request', 'complete_request',
114 'inspect_request', 'history_request',
114 'inspect_request', 'history_request',
115 'kernel_info_request',
115 'kernel_info_request',
116 'connect_request', 'shutdown_request',
116 'connect_request', 'shutdown_request',
117 'apply_request',
117 'apply_request',
118 ]
118 ]
119 self.shell_handlers = {}
119 self.shell_handlers = {}
120 for msg_type in msg_types:
120 for msg_type in msg_types:
121 self.shell_handlers[msg_type] = getattr(self, msg_type)
121 self.shell_handlers[msg_type] = getattr(self, msg_type)
122
122
123 control_msg_types = msg_types + [ 'clear_request', 'abort_request' ]
123 control_msg_types = msg_types + [ 'clear_request', 'abort_request' ]
124 self.control_handlers = {}
124 self.control_handlers = {}
125 for msg_type in control_msg_types:
125 for msg_type in control_msg_types:
126 self.control_handlers[msg_type] = getattr(self, msg_type)
126 self.control_handlers[msg_type] = getattr(self, msg_type)
127
127
128
128
129 def dispatch_control(self, msg):
129 def dispatch_control(self, msg):
130 """dispatch control requests"""
130 """dispatch control requests"""
131 idents,msg = self.session.feed_identities(msg, copy=False)
131 idents,msg = self.session.feed_identities(msg, copy=False)
132 try:
132 try:
133 msg = self.session.unserialize(msg, content=True, copy=False)
133 msg = self.session.unserialize(msg, content=True, copy=False)
134 except:
134 except:
135 self.log.error("Invalid Control Message", exc_info=True)
135 self.log.error("Invalid Control Message", exc_info=True)
136 return
136 return
137
137
138 self.log.debug("Control received: %s", msg)
138 self.log.debug("Control received: %s", msg)
139
139
140 # Set the parent message for side effects.
140 # Set the parent message for side effects.
141 self.set_parent(idents, msg)
141 self.set_parent(idents, msg)
142 self._publish_status(u'busy')
142 self._publish_status(u'busy')
143
143
144 header = msg['header']
144 header = msg['header']
145 msg_type = header['msg_type']
145 msg_type = header['msg_type']
146
146
147 handler = self.control_handlers.get(msg_type, None)
147 handler = self.control_handlers.get(msg_type, None)
148 if handler is None:
148 if handler is None:
149 self.log.error("UNKNOWN CONTROL MESSAGE TYPE: %r", msg_type)
149 self.log.error("UNKNOWN CONTROL MESSAGE TYPE: %r", msg_type)
150 else:
150 else:
151 try:
151 try:
152 handler(self.control_stream, idents, msg)
152 handler(self.control_stream, idents, msg)
153 except Exception:
153 except Exception:
154 self.log.error("Exception in control handler:", exc_info=True)
154 self.log.error("Exception in control handler:", exc_info=True)
155
155
156 sys.stdout.flush()
156 sys.stdout.flush()
157 sys.stderr.flush()
157 sys.stderr.flush()
158 self._publish_status(u'idle')
158 self._publish_status(u'idle')
159
159
160 def dispatch_shell(self, stream, msg):
160 def dispatch_shell(self, stream, msg):
161 """dispatch shell requests"""
161 """dispatch shell requests"""
162 # flush control requests first
162 # flush control requests first
163 if self.control_stream:
163 if self.control_stream:
164 self.control_stream.flush()
164 self.control_stream.flush()
165
165
166 idents,msg = self.session.feed_identities(msg, copy=False)
166 idents,msg = self.session.feed_identities(msg, copy=False)
167 try:
167 try:
168 msg = self.session.unserialize(msg, content=True, copy=False)
168 msg = self.session.unserialize(msg, content=True, copy=False)
169 except:
169 except:
170 self.log.error("Invalid Message", exc_info=True)
170 self.log.error("Invalid Message", exc_info=True)
171 return
171 return
172
172
173 # Set the parent message for side effects.
173 # Set the parent message for side effects.
174 self.set_parent(idents, msg)
174 self.set_parent(idents, msg)
175 self._publish_status(u'busy')
175 self._publish_status(u'busy')
176
176
177 header = msg['header']
177 header = msg['header']
178 msg_id = header['msg_id']
178 msg_id = header['msg_id']
179 msg_type = msg['header']['msg_type']
179 msg_type = msg['header']['msg_type']
180
180
181 # Print some info about this message and leave a '--->' marker, so it's
181 # Print some info about this message and leave a '--->' marker, so it's
182 # easier to trace visually the message chain when debugging. Each
182 # easier to trace visually the message chain when debugging. Each
183 # handler prints its message at the end.
183 # handler prints its message at the end.
184 self.log.debug('\n*** MESSAGE TYPE:%s***', msg_type)
184 self.log.debug('\n*** MESSAGE TYPE:%s***', msg_type)
185 self.log.debug(' Content: %s\n --->\n ', msg['content'])
185 self.log.debug(' Content: %s\n --->\n ', msg['content'])
186
186
187 if msg_id in self.aborted:
187 if msg_id in self.aborted:
188 self.aborted.remove(msg_id)
188 self.aborted.remove(msg_id)
189 # is it safe to assume a msg_id will not be resubmitted?
189 # is it safe to assume a msg_id will not be resubmitted?
190 reply_type = msg_type.split('_')[0] + '_reply'
190 reply_type = msg_type.split('_')[0] + '_reply'
191 status = {'status' : 'aborted'}
191 status = {'status' : 'aborted'}
192 md = {'engine' : self.ident}
192 md = {'engine' : self.ident}
193 md.update(status)
193 md.update(status)
194 self.session.send(stream, reply_type, metadata=md,
194 self.session.send(stream, reply_type, metadata=md,
195 content=status, parent=msg, ident=idents)
195 content=status, parent=msg, ident=idents)
196 return
196 return
197
197
198 handler = self.shell_handlers.get(msg_type, None)
198 handler = self.shell_handlers.get(msg_type, None)
199 if handler is None:
199 if handler is None:
200 self.log.error("UNKNOWN MESSAGE TYPE: %r", msg_type)
200 self.log.error("UNKNOWN MESSAGE TYPE: %r", msg_type)
201 else:
201 else:
202 # ensure default_int_handler during handler call
202 # ensure default_int_handler during handler call
203 sig = signal(SIGINT, default_int_handler)
203 sig = signal(SIGINT, default_int_handler)
204 self.log.debug("%s: %s", msg_type, msg)
204 self.log.debug("%s: %s", msg_type, msg)
205 try:
205 try:
206 handler(stream, idents, msg)
206 handler(stream, idents, msg)
207 except Exception:
207 except Exception:
208 self.log.error("Exception in message handler:", exc_info=True)
208 self.log.error("Exception in message handler:", exc_info=True)
209 finally:
209 finally:
210 signal(SIGINT, sig)
210 signal(SIGINT, sig)
211
211
212 sys.stdout.flush()
212 sys.stdout.flush()
213 sys.stderr.flush()
213 sys.stderr.flush()
214 self._publish_status(u'idle')
214 self._publish_status(u'idle')
215
215
216 def enter_eventloop(self):
216 def enter_eventloop(self):
217 """enter eventloop"""
217 """enter eventloop"""
218 self.log.info("entering eventloop %s", self.eventloop)
218 self.log.info("entering eventloop %s", self.eventloop)
219 for stream in self.shell_streams:
219 for stream in self.shell_streams:
220 # flush any pending replies,
220 # flush any pending replies,
221 # which may be skipped by entering the eventloop
221 # which may be skipped by entering the eventloop
222 stream.flush(zmq.POLLOUT)
222 stream.flush(zmq.POLLOUT)
223 # restore default_int_handler
223 # restore default_int_handler
224 signal(SIGINT, default_int_handler)
224 signal(SIGINT, default_int_handler)
225 while self.eventloop is not None:
225 while self.eventloop is not None:
226 try:
226 try:
227 self.eventloop(self)
227 self.eventloop(self)
228 except KeyboardInterrupt:
228 except KeyboardInterrupt:
229 # Ctrl-C shouldn't crash the kernel
229 # Ctrl-C shouldn't crash the kernel
230 self.log.error("KeyboardInterrupt caught in kernel")
230 self.log.error("KeyboardInterrupt caught in kernel")
231 continue
231 continue
232 else:
232 else:
233 # eventloop exited cleanly, this means we should stop (right?)
233 # eventloop exited cleanly, this means we should stop (right?)
234 self.eventloop = None
234 self.eventloop = None
235 break
235 break
236 self.log.info("exiting eventloop")
236 self.log.info("exiting eventloop")
237
237
238 def start(self):
238 def start(self):
239 """register dispatchers for streams"""
239 """register dispatchers for streams"""
240 if self.control_stream:
240 if self.control_stream:
241 self.control_stream.on_recv(self.dispatch_control, copy=False)
241 self.control_stream.on_recv(self.dispatch_control, copy=False)
242
242
243 def make_dispatcher(stream):
243 def make_dispatcher(stream):
244 def dispatcher(msg):
244 def dispatcher(msg):
245 return self.dispatch_shell(stream, msg)
245 return self.dispatch_shell(stream, msg)
246 return dispatcher
246 return dispatcher
247
247
248 for s in self.shell_streams:
248 for s in self.shell_streams:
249 s.on_recv(make_dispatcher(s), copy=False)
249 s.on_recv(make_dispatcher(s), copy=False)
250
250
251 # publish idle status
251 # publish idle status
252 self._publish_status('starting')
252 self._publish_status('starting')
253
253
254 def do_one_iteration(self):
254 def do_one_iteration(self):
255 """step eventloop just once"""
255 """step eventloop just once"""
256 if self.control_stream:
256 if self.control_stream:
257 self.control_stream.flush()
257 self.control_stream.flush()
258 for stream in self.shell_streams:
258 for stream in self.shell_streams:
259 # handle at most one request per iteration
259 # handle at most one request per iteration
260 stream.flush(zmq.POLLIN, 1)
260 stream.flush(zmq.POLLIN, 1)
261 stream.flush(zmq.POLLOUT)
261 stream.flush(zmq.POLLOUT)
262
262
263
263
264 def record_ports(self, ports):
264 def record_ports(self, ports):
265 """Record the ports that this kernel is using.
265 """Record the ports that this kernel is using.
266
266
267 The creator of the Kernel instance must call this methods if they
267 The creator of the Kernel instance must call this methods if they
268 want the :meth:`connect_request` method to return the port numbers.
268 want the :meth:`connect_request` method to return the port numbers.
269 """
269 """
270 self._recorded_ports = ports
270 self._recorded_ports = ports
271
271
272 #---------------------------------------------------------------------------
272 #---------------------------------------------------------------------------
273 # Kernel request handlers
273 # Kernel request handlers
274 #---------------------------------------------------------------------------
274 #---------------------------------------------------------------------------
275
275
276 def _make_metadata(self, other=None):
276 def _make_metadata(self, other=None):
277 """init metadata dict, for execute/apply_reply"""
277 """init metadata dict, for execute/apply_reply"""
278 new_md = {
278 new_md = {
279 'dependencies_met' : True,
279 'dependencies_met' : True,
280 'engine' : self.ident,
280 'engine' : self.ident,
281 'started': datetime.now(),
281 'started': datetime.now(),
282 }
282 }
283 if other:
283 if other:
284 new_md.update(other)
284 new_md.update(other)
285 return new_md
285 return new_md
286
286
287 def _publish_execute_input(self, code, parent, execution_count):
287 def _publish_execute_input(self, code, parent, execution_count):
288 """Publish the code request on the iopub stream."""
288 """Publish the code request on the iopub stream."""
289
289
290 self.session.send(self.iopub_socket, u'execute_input',
290 self.session.send(self.iopub_socket, u'execute_input',
291 {u'code':code, u'execution_count': execution_count},
291 {u'code':code, u'execution_count': execution_count},
292 parent=parent, ident=self._topic('execute_input')
292 parent=parent, ident=self._topic('execute_input')
293 )
293 )
294
294
295 def _publish_status(self, status, parent=None):
295 def _publish_status(self, status, parent=None):
296 """send status (busy/idle) on IOPub"""
296 """send status (busy/idle) on IOPub"""
297 self.session.send(self.iopub_socket,
297 self.session.send(self.iopub_socket,
298 u'status',
298 u'status',
299 {u'execution_state': status},
299 {u'execution_state': status},
300 parent=parent or self._parent_header,
300 parent=parent or self._parent_header,
301 ident=self._topic('status'),
301 ident=self._topic('status'),
302 )
302 )
303
303
304 def set_parent(self, ident, parent):
304 def set_parent(self, ident, parent):
305 """Set the current parent_header
305 """Set the current parent_header
306
306
307 Side effects (IOPub messages) and replies are associated with
307 Side effects (IOPub messages) and replies are associated with
308 the request that caused them via the parent_header.
308 the request that caused them via the parent_header.
309
309
310 The parent identity is used to route input_request messages
310 The parent identity is used to route input_request messages
311 on the stdin channel.
311 on the stdin channel.
312 """
312 """
313 self._parent_ident = ident
313 self._parent_ident = ident
314 self._parent_header = parent
314 self._parent_header = parent
315
315
316 def send_response(self, stream, msg_or_type, content=None, ident=None,
316 def send_response(self, stream, msg_or_type, content=None, ident=None,
317 buffers=None, track=False, header=None, metadata=None):
317 buffers=None, track=False, header=None, metadata=None):
318 """Send a response to the message we're currently processing.
318 """Send a response to the message we're currently processing.
319
319
320 This accepts all the parameters of :meth:`IPython.kernel.zmq.session.Session.send`
320 This accepts all the parameters of :meth:`IPython.kernel.zmq.session.Session.send`
321 except ``parent``.
321 except ``parent``.
322
322
323 This relies on :meth:`set_parent` having been called for the current
323 This relies on :meth:`set_parent` having been called for the current
324 message.
324 message.
325 """
325 """
326 return self.session.send(stream, msg_or_type, content, self._parent_header,
326 return self.session.send(stream, msg_or_type, content, self._parent_header,
327 ident, buffers, track, header, metadata)
327 ident, buffers, track, header, metadata)
328
328
329 def execute_request(self, stream, ident, parent):
329 def execute_request(self, stream, ident, parent):
330 """handle an execute_request"""
330 """handle an execute_request"""
331
331
332 try:
332 try:
333 content = parent[u'content']
333 content = parent[u'content']
334 code = py3compat.cast_unicode_py2(content[u'code'])
334 code = py3compat.cast_unicode_py2(content[u'code'])
335 silent = content[u'silent']
335 silent = content[u'silent']
336 store_history = content.get(u'store_history', not silent)
336 store_history = content.get(u'store_history', not silent)
337 user_expressions = content.get('user_expressions', {})
337 user_expressions = content.get('user_expressions', {})
338 allow_stdin = content.get('allow_stdin', False)
338 allow_stdin = content.get('allow_stdin', False)
339 except:
339 except:
340 self.log.error("Got bad msg: ")
340 self.log.error("Got bad msg: ")
341 self.log.error("%s", parent)
341 self.log.error("%s", parent)
342 return
342 return
343
343
344 md = self._make_metadata(parent['metadata'])
344 md = self._make_metadata(parent['metadata'])
345
345
346 # Re-broadcast our input for the benefit of listening clients, and
346 # Re-broadcast our input for the benefit of listening clients, and
347 # start computing output
347 # start computing output
348 if not silent:
348 if not silent:
349 self.execution_count += 1
349 self.execution_count += 1
350 self._publish_execute_input(code, parent, self.execution_count)
350 self._publish_execute_input(code, parent, self.execution_count)
351
351
352 reply_content = self.do_execute(code, silent, store_history,
352 reply_content = self.do_execute(code, silent, store_history,
353 user_expressions, allow_stdin)
353 user_expressions, allow_stdin)
354
354
355 # Flush output before sending the reply.
355 # Flush output before sending the reply.
356 sys.stdout.flush()
356 sys.stdout.flush()
357 sys.stderr.flush()
357 sys.stderr.flush()
358 # FIXME: on rare occasions, the flush doesn't seem to make it to the
358 # FIXME: on rare occasions, the flush doesn't seem to make it to the
359 # clients... This seems to mitigate the problem, but we definitely need
359 # clients... This seems to mitigate the problem, but we definitely need
360 # to better understand what's going on.
360 # to better understand what's going on.
361 if self._execute_sleep:
361 if self._execute_sleep:
362 time.sleep(self._execute_sleep)
362 time.sleep(self._execute_sleep)
363
363
364 # Send the reply.
364 # Send the reply.
365 reply_content = json_clean(reply_content)
365 reply_content = json_clean(reply_content)
366
366
367 md['status'] = reply_content['status']
367 md['status'] = reply_content['status']
368 if reply_content['status'] == 'error' and \
368 if reply_content['status'] == 'error' and \
369 reply_content['ename'] == 'UnmetDependency':
369 reply_content['ename'] == 'UnmetDependency':
370 md['dependencies_met'] = False
370 md['dependencies_met'] = False
371
371
372 reply_msg = self.session.send(stream, u'execute_reply',
372 reply_msg = self.session.send(stream, u'execute_reply',
373 reply_content, parent, metadata=md,
373 reply_content, parent, metadata=md,
374 ident=ident)
374 ident=ident)
375
375
376 self.log.debug("%s", reply_msg)
376 self.log.debug("%s", reply_msg)
377
377
378 if not silent and reply_msg['content']['status'] == u'error':
378 if not silent and reply_msg['content']['status'] == u'error':
379 self._abort_queues()
379 self._abort_queues()
380
380
381 def do_execute(self, code, silent, store_history=True,
381 def do_execute(self, code, silent, store_history=True,
382 user_experssions=None, allow_stdin=False):
382 user_experssions=None, allow_stdin=False):
383 """Execute user code. Must be overridden by subclasses.
383 """Execute user code. Must be overridden by subclasses.
384 """
384 """
385 raise NotImplementedError
385 raise NotImplementedError
386
386
387 def complete_request(self, stream, ident, parent):
387 def complete_request(self, stream, ident, parent):
388 content = parent['content']
388 content = parent['content']
389 code = content['code']
389 code = content['code']
390 cursor_pos = content['cursor_pos']
390 cursor_pos = content['cursor_pos']
391
391
392 matches = self.do_complete(code, cursor_pos)
392 matches = self.do_complete(code, cursor_pos)
393 matches = json_clean(matches)
393 matches = json_clean(matches)
394 completion_msg = self.session.send(stream, 'complete_reply',
394 completion_msg = self.session.send(stream, 'complete_reply',
395 matches, parent, ident)
395 matches, parent, ident)
396 self.log.debug("%s", completion_msg)
396 self.log.debug("%s", completion_msg)
397
397
398 def do_complete(self, code, cursor_pos):
398 def do_complete(self, code, cursor_pos):
399 """Override in subclasses to find completions.
399 """Override in subclasses to find completions.
400 """
400 """
401 return {'matches' : [],
401 return {'matches' : [],
402 'cursor_end' : cursor_pos,
402 'cursor_end' : cursor_pos,
403 'cursor_start' : cursor_pos,
403 'cursor_start' : cursor_pos,
404 'metadata' : {},
404 'metadata' : {},
405 'status' : 'ok'}
405 'status' : 'ok'}
406
406
407 def inspect_request(self, stream, ident, parent):
407 def inspect_request(self, stream, ident, parent):
408 content = parent['content']
408 content = parent['content']
409
409
410 reply_content = self.do_inspect(content['code'], content['cursor_pos'],
410 reply_content = self.do_inspect(content['code'], content['cursor_pos'],
411 content.get('detail_level', 0))
411 content.get('detail_level', 0))
412 # Before we send this object over, we scrub it for JSON usage
412 # Before we send this object over, we scrub it for JSON usage
413 reply_content = json_clean(reply_content)
413 reply_content = json_clean(reply_content)
414 msg = self.session.send(stream, 'inspect_reply',
414 msg = self.session.send(stream, 'inspect_reply',
415 reply_content, parent, ident)
415 reply_content, parent, ident)
416 self.log.debug("%s", msg)
416 self.log.debug("%s", msg)
417
417
418 def do_inspect(self, code, cursor_pos, detail_level=0):
418 def do_inspect(self, code, cursor_pos, detail_level=0):
419 """Override in subclasses to allow introspection.
419 """Override in subclasses to allow introspection.
420 """
420 """
421 return {'status': 'ok', 'data':{}, 'metadata':{}, 'found':False}
421 return {'status': 'ok', 'data':{}, 'metadata':{}, 'found':False}
422
422
423 def history_request(self, stream, ident, parent):
423 def history_request(self, stream, ident, parent):
424 content = parent['content']
424 content = parent['content']
425
425
426 reply_content = self.do_history(**content)
426 reply_content = self.do_history(**content)
427
427
428 reply_content = json_clean(reply_content)
428 reply_content = json_clean(reply_content)
429 msg = self.session.send(stream, 'history_reply',
429 msg = self.session.send(stream, 'history_reply',
430 reply_content, parent, ident)
430 reply_content, parent, ident)
431 self.log.debug("%s", msg)
431 self.log.debug("%s", msg)
432
432
433 def do_history(self, hist_access_type, output, raw, session=None, start=None,
433 def do_history(self, hist_access_type, output, raw, session=None, start=None,
434 stop=None, n=None, pattern=None, unique=False):
434 stop=None, n=None, pattern=None, unique=False):
435 """Override in subclasses to access history.
435 """Override in subclasses to access history.
436 """
436 """
437 return {'history': []}
437 return {'history': []}
438
438
439 def connect_request(self, stream, ident, parent):
439 def connect_request(self, stream, ident, parent):
440 if self._recorded_ports is not None:
440 if self._recorded_ports is not None:
441 content = self._recorded_ports.copy()
441 content = self._recorded_ports.copy()
442 else:
442 else:
443 content = {}
443 content = {}
444 msg = self.session.send(stream, 'connect_reply',
444 msg = self.session.send(stream, 'connect_reply',
445 content, parent, ident)
445 content, parent, ident)
446 self.log.debug("%s", msg)
446 self.log.debug("%s", msg)
447
447
448 @property
448 @property
449 def kernel_info(self):
449 def kernel_info(self):
450 return {
450 return {
451 'protocol_version': release.kernel_protocol_version,
451 'protocol_version': release.kernel_protocol_version,
452 'implementation': self.implementation,
452 'implementation': self.implementation,
453 'implementation_version': self.implementation_version,
453 'implementation_version': self.implementation_version,
454 'language': self.language,
454 'language': self.language,
455 'language_version': self.language_version,
455 'language_version': self.language_version,
456 'banner': self.banner,
456 'banner': self.banner,
457 }
457 }
458
458
459 def kernel_info_request(self, stream, ident, parent):
459 def kernel_info_request(self, stream, ident, parent):
460 msg = self.session.send(stream, 'kernel_info_reply',
460 msg = self.session.send(stream, 'kernel_info_reply',
461 self.kernel_info, parent, ident)
461 self.kernel_info, parent, ident)
462 self.log.debug("%s", msg)
462 self.log.debug("%s", msg)
463
463
464 def shutdown_request(self, stream, ident, parent):
464 def shutdown_request(self, stream, ident, parent):
465 content = self.do_shutdown(parent['content']['restart'])
465 content = self.do_shutdown(parent['content']['restart'])
466 self.session.send(stream, u'shutdown_reply', content, parent, ident=ident)
466 self.session.send(stream, u'shutdown_reply', content, parent, ident=ident)
467 # same content, but different msg_id for broadcasting on IOPub
467 # same content, but different msg_id for broadcasting on IOPub
468 self._shutdown_message = self.session.msg(u'shutdown_reply',
468 self._shutdown_message = self.session.msg(u'shutdown_reply',
469 content, parent
469 content, parent
470 )
470 )
471
471
472 self._at_shutdown()
472 self._at_shutdown()
473 # call sys.exit after a short delay
473 # call sys.exit after a short delay
474 loop = ioloop.IOLoop.instance()
474 loop = ioloop.IOLoop.instance()
475 loop.add_timeout(time.time()+0.1, loop.stop)
475 loop.add_timeout(time.time()+0.1, loop.stop)
476
476
477 def do_shutdown(self, restart):
477 def do_shutdown(self, restart):
478 """Override in subclasses to do things when the frontend shuts down the
478 """Override in subclasses to do things when the frontend shuts down the
479 kernel.
479 kernel.
480 """
480 """
481 return {'status': 'ok', 'restart': restart}
481 return {'status': 'ok', 'restart': restart}
482
482
483 #---------------------------------------------------------------------------
483 #---------------------------------------------------------------------------
484 # Engine methods
484 # Engine methods
485 #---------------------------------------------------------------------------
485 #---------------------------------------------------------------------------
486
486
487 def apply_request(self, stream, ident, parent):
487 def apply_request(self, stream, ident, parent):
488 try:
488 try:
489 content = parent[u'content']
489 content = parent[u'content']
490 bufs = parent[u'buffers']
490 bufs = parent[u'buffers']
491 msg_id = parent['header']['msg_id']
491 msg_id = parent['header']['msg_id']
492 except:
492 except:
493 self.log.error("Got bad msg: %s", parent, exc_info=True)
493 self.log.error("Got bad msg: %s", parent, exc_info=True)
494 return
494 return
495
495
496 md = self._make_metadata(parent['metadata'])
496 md = self._make_metadata(parent['metadata'])
497
497
498 reply_content, result_buf = self.do_apply(content, bufs, msg_id, md)
498 reply_content, result_buf = self.do_apply(content, bufs, msg_id, md)
499
499
500 # put 'ok'/'error' status in header, for scheduler introspection:
500 # put 'ok'/'error' status in header, for scheduler introspection:
501 md['status'] = reply_content['status']
501 md['status'] = reply_content['status']
502
502
503 # flush i/o
503 # flush i/o
504 sys.stdout.flush()
504 sys.stdout.flush()
505 sys.stderr.flush()
505 sys.stderr.flush()
506
506
507 self.session.send(stream, u'apply_reply', reply_content,
507 self.session.send(stream, u'apply_reply', reply_content,
508 parent=parent, ident=ident,buffers=result_buf, metadata=md)
508 parent=parent, ident=ident,buffers=result_buf, metadata=md)
509
509
510 def do_apply(self, content, bufs, msg_id, reply_metadata):
510 def do_apply(self, content, bufs, msg_id, reply_metadata):
511 """Override in subclasses to support the IPython parallel framework.
511 """Override in subclasses to support the IPython parallel framework.
512 """
512 """
513 raise NotImplementedError
513 raise NotImplementedError
514
514
515 #---------------------------------------------------------------------------
515 #---------------------------------------------------------------------------
516 # Control messages
516 # Control messages
517 #---------------------------------------------------------------------------
517 #---------------------------------------------------------------------------
518
518
519 def abort_request(self, stream, ident, parent):
519 def abort_request(self, stream, ident, parent):
520 """abort a specific msg by id"""
520 """abort a specific msg by id"""
521 msg_ids = parent['content'].get('msg_ids', None)
521 msg_ids = parent['content'].get('msg_ids', None)
522 if isinstance(msg_ids, string_types):
522 if isinstance(msg_ids, string_types):
523 msg_ids = [msg_ids]
523 msg_ids = [msg_ids]
524 if not msg_ids:
524 if not msg_ids:
525 self._abort_queues()
525 self._abort_queues()
526 for mid in msg_ids:
526 for mid in msg_ids:
527 self.aborted.add(str(mid))
527 self.aborted.add(str(mid))
528
528
529 content = dict(status='ok')
529 content = dict(status='ok')
530 reply_msg = self.session.send(stream, 'abort_reply', content=content,
530 reply_msg = self.session.send(stream, 'abort_reply', content=content,
531 parent=parent, ident=ident)
531 parent=parent, ident=ident)
532 self.log.debug("%s", reply_msg)
532 self.log.debug("%s", reply_msg)
533
533
534 def clear_request(self, stream, idents, parent):
534 def clear_request(self, stream, idents, parent):
535 """Clear our namespace."""
535 """Clear our namespace."""
536 content = self.do_clear()
536 content = self.do_clear()
537 self.session.send(stream, 'clear_reply', ident=idents, parent=parent,
537 self.session.send(stream, 'clear_reply', ident=idents, parent=parent,
538 content = content)
538 content = content)
539
539
540 def do_clear(self):
540 def do_clear(self):
541 """Override in subclasses to clear the namespace
541 """Override in subclasses to clear the namespace
542
542
543 This is only required for IPython.parallel.
543 This is only required for IPython.parallel.
544 """
544 """
545 raise NotImplementedError
545 raise NotImplementedError
546
546
547 #---------------------------------------------------------------------------
547 #---------------------------------------------------------------------------
548 # Protected interface
548 # Protected interface
549 #---------------------------------------------------------------------------
549 #---------------------------------------------------------------------------
550
550
551 def _topic(self, topic):
551 def _topic(self, topic):
552 """prefixed topic for IOPub messages"""
552 """prefixed topic for IOPub messages"""
553 if self.int_id >= 0:
553 if self.int_id >= 0:
554 base = "engine.%i" % self.int_id
554 base = "engine.%i" % self.int_id
555 else:
555 else:
556 base = "kernel.%s" % self.ident
556 base = "kernel.%s" % self.ident
557
557
558 return py3compat.cast_bytes("%s.%s" % (base, topic))
558 return py3compat.cast_bytes("%s.%s" % (base, topic))
559
559
560 def _abort_queues(self):
560 def _abort_queues(self):
561 for stream in self.shell_streams:
561 for stream in self.shell_streams:
562 if stream:
562 if stream:
563 self._abort_queue(stream)
563 self._abort_queue(stream)
564
564
565 def _abort_queue(self, stream):
565 def _abort_queue(self, stream):
566 poller = zmq.Poller()
566 poller = zmq.Poller()
567 poller.register(stream.socket, zmq.POLLIN)
567 poller.register(stream.socket, zmq.POLLIN)
568 while True:
568 while True:
569 idents,msg = self.session.recv(stream, zmq.NOBLOCK, content=True)
569 idents,msg = self.session.recv(stream, zmq.NOBLOCK, content=True)
570 if msg is None:
570 if msg is None:
571 return
571 return
572
572
573 self.log.info("Aborting:")
573 self.log.info("Aborting:")
574 self.log.info("%s", msg)
574 self.log.info("%s", msg)
575 msg_type = msg['header']['msg_type']
575 msg_type = msg['header']['msg_type']
576 reply_type = msg_type.split('_')[0] + '_reply'
576 reply_type = msg_type.split('_')[0] + '_reply'
577
577
578 status = {'status' : 'aborted'}
578 status = {'status' : 'aborted'}
579 md = {'engine' : self.ident}
579 md = {'engine' : self.ident}
580 md.update(status)
580 md.update(status)
581 reply_msg = self.session.send(stream, reply_type, metadata=md,
581 reply_msg = self.session.send(stream, reply_type, metadata=md,
582 content=status, parent=msg, ident=idents)
582 content=status, parent=msg, ident=idents)
583 self.log.debug("%s", reply_msg)
583 self.log.debug("%s", reply_msg)
584 # We need to wait a bit for requests to come in. This can probably
584 # We need to wait a bit for requests to come in. This can probably
585 # be set shorter for true asynchronous clients.
585 # be set shorter for true asynchronous clients.
586 poller.poll(50)
586 poller.poll(50)
587
587
588
588
589 def _no_raw_input(self):
589 def _no_raw_input(self):
590 """Raise StdinNotImplentedError if active frontend doesn't support
590 """Raise StdinNotImplentedError if active frontend doesn't support
591 stdin."""
591 stdin."""
592 raise StdinNotImplementedError("raw_input was called, but this "
592 raise StdinNotImplementedError("raw_input was called, but this "
593 "frontend does not support stdin.")
593 "frontend does not support stdin.")
594
594
595 def getpass(self, prompt=''):
595 def getpass(self, prompt=''):
596 """Forward getpass to frontends
596 """Forward getpass to frontends
597
597
598 Raises
598 Raises
599 ------
599 ------
600 StdinNotImplentedError if active frontend doesn't support stdin.
600 StdinNotImplentedError if active frontend doesn't support stdin.
601 """
601 """
602 if not self._allow_stdin:
602 if not self._allow_stdin:
603 raise StdinNotImplementedError(
603 raise StdinNotImplementedError(
604 "getpass was called, but this frontend does not support input requests."
604 "getpass was called, but this frontend does not support input requests."
605 )
605 )
606 return self._input_request(prompt,
606 return self._input_request(prompt,
607 self._parent_ident,
607 self._parent_ident,
608 self._parent_header,
608 self._parent_header,
609 password=True,
609 password=True,
610 )
610 )
611
611
612 def raw_input(self, prompt=''):
612 def raw_input(self, prompt=''):
613 """Forward raw_input to frontends
613 """Forward raw_input to frontends
614
614
615 Raises
615 Raises
616 ------
616 ------
617 StdinNotImplentedError if active frontend doesn't support stdin.
617 StdinNotImplentedError if active frontend doesn't support stdin.
618 """
618 """
619 if not self._allow_stdin:
619 if not self._allow_stdin:
620 raise StdinNotImplementedError(
620 raise StdinNotImplementedError(
621 "raw_input was called, but this frontend does not support input requests."
621 "raw_input was called, but this frontend does not support input requests."
622 )
622 )
623 return self._input_request(prompt,
623 return self._input_request(prompt,
624 self._parent_ident,
624 self._parent_ident,
625 self._parent_header,
625 self._parent_header,
626 password=False,
626 password=False,
627 )
627 )
628
628
629 def _input_request(self, prompt, ident, parent, password=False):
629 def _input_request(self, prompt, ident, parent, password=False):
630 # Flush output before making the request.
630 # Flush output before making the request.
631 sys.stderr.flush()
631 sys.stderr.flush()
632 sys.stdout.flush()
632 sys.stdout.flush()
633 # flush the stdin socket, to purge stale replies
633 # flush the stdin socket, to purge stale replies
634 while True:
634 while True:
635 try:
635 try:
636 self.stdin_socket.recv_multipart(zmq.NOBLOCK)
636 self.stdin_socket.recv_multipart(zmq.NOBLOCK)
637 except zmq.ZMQError as e:
637 except zmq.ZMQError as e:
638 if e.errno == zmq.EAGAIN:
638 if e.errno == zmq.EAGAIN:
639 break
639 break
640 else:
640 else:
641 raise
641 raise
642
642
643 # Send the input request.
643 # Send the input request.
644 content = json_clean(dict(prompt=prompt, password=password))
644 content = json_clean(dict(prompt=prompt, password=password))
645 self.session.send(self.stdin_socket, u'input_request', content, parent,
645 self.session.send(self.stdin_socket, u'input_request', content, parent,
646 ident=ident)
646 ident=ident)
647
647
648 # Await a response.
648 # Await a response.
649 while True:
649 while True:
650 try:
650 try:
651 ident, reply = self.session.recv(self.stdin_socket, 0)
651 ident, reply = self.session.recv(self.stdin_socket, 0)
652 except Exception:
652 except Exception:
653 self.log.warn("Invalid Message:", exc_info=True)
653 self.log.warn("Invalid Message:", exc_info=True)
654 except KeyboardInterrupt:
654 except KeyboardInterrupt:
655 # re-raise KeyboardInterrupt, to truncate traceback
655 # re-raise KeyboardInterrupt, to truncate traceback
656 raise KeyboardInterrupt
656 raise KeyboardInterrupt
657 else:
657 else:
658 break
658 break
659 try:
659 try:
660 value = py3compat.unicode_to_str(reply['content']['value'])
660 value = py3compat.unicode_to_str(reply['content']['value'])
661 except:
661 except:
662 self.log.error("Bad input_reply: %s", parent)
662 self.log.error("Bad input_reply: %s", parent)
663 value = ''
663 value = ''
664 if value == '\x04':
664 if value == '\x04':
665 # EOF
665 # EOF
666 raise EOFError
666 raise EOFError
667 return value
667 return value
668
668
669 def _at_shutdown(self):
669 def _at_shutdown(self):
670 """Actions taken at shutdown by the kernel, called by python's atexit.
670 """Actions taken at shutdown by the kernel, called by python's atexit.
671 """
671 """
672 # io.rprint("Kernel at_shutdown") # dbg
672 # io.rprint("Kernel at_shutdown") # dbg
673 if self._shutdown_message is not None:
673 if self._shutdown_message is not None:
674 self.session.send(self.iopub_socket, self._shutdown_message, ident=self._topic('shutdown'))
674 self.session.send(self.iopub_socket, self._shutdown_message, ident=self._topic('shutdown'))
675 self.log.debug("%s", self._shutdown_message)
675 self.log.debug("%s", self._shutdown_message)
676 [ s.flush(zmq.POLLOUT) for s in self.shell_streams ]
676 [ s.flush(zmq.POLLOUT) for s in self.shell_streams ]
@@ -1,573 +1,567 b''
1 """A ZMQ-based subclass of InteractiveShell.
1 """A ZMQ-based subclass of InteractiveShell.
2
2
3 This code is meant to ease the refactoring of the base InteractiveShell into
3 This code is meant to ease the refactoring of the base InteractiveShell into
4 something with a cleaner architecture for 2-process use, without actually
4 something with a cleaner architecture for 2-process use, without actually
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 we subclass and override what we want to fix. Once this is working well, we
6 we subclass and override what we want to fix. Once this is working well, we
7 can go back to the base class and refactor the code for a cleaner inheritance
7 can go back to the base class and refactor the code for a cleaner inheritance
8 implementation that doesn't rely on so much monkeypatching.
8 implementation that doesn't rely on so much monkeypatching.
9
9
10 But this lets us maintain a fully working IPython as we develop the new
10 But this lets us maintain a fully working IPython as we develop the new
11 machinery. This should thus be thought of as scaffolding.
11 machinery. This should thus be thought of as scaffolding.
12 """
12 """
13
13
14 # Copyright (c) IPython Development Team.
14 # Copyright (c) IPython Development Team.
15 # Distributed under the terms of the Modified BSD License.
15 # Distributed under the terms of the Modified BSD License.
16
16
17 from __future__ import print_function
17 from __future__ import print_function
18
18
19 import os
19 import os
20 import sys
20 import sys
21 import time
21 import time
22
22
23 from zmq.eventloop import ioloop
23 from zmq.eventloop import ioloop
24
24
25 from IPython.core.interactiveshell import (
25 from IPython.core.interactiveshell import (
26 InteractiveShell, InteractiveShellABC
26 InteractiveShell, InteractiveShellABC
27 )
27 )
28 from IPython.core import page
28 from IPython.core import page
29 from IPython.core.autocall import ZMQExitAutocall
29 from IPython.core.autocall import ZMQExitAutocall
30 from IPython.core.displaypub import DisplayPublisher
30 from IPython.core.displaypub import DisplayPublisher
31 from IPython.core.error import UsageError
31 from IPython.core.error import UsageError
32 from IPython.core.magics import MacroToEdit, CodeMagics
32 from IPython.core.magics import MacroToEdit, CodeMagics
33 from IPython.core.magic import magics_class, line_magic, Magics
33 from IPython.core.magic import magics_class, line_magic, Magics
34 from IPython.core.payloadpage import install_payload_page
34 from IPython.core.payloadpage import install_payload_page
35 from IPython.core.usage import default_gui_banner
35 from IPython.core.usage import default_gui_banner
36 from IPython.display import display, Javascript
36 from IPython.display import display, Javascript
37 from IPython.kernel.inprocess.socket import SocketABC
37 from IPython.kernel.inprocess.socket import SocketABC
38 from IPython.kernel import (
38 from IPython.kernel import (
39 get_connection_file, get_connection_info, connect_qtconsole
39 get_connection_file, get_connection_info, connect_qtconsole
40 )
40 )
41 from IPython.testing.skipdoctest import skip_doctest
41 from IPython.testing.skipdoctest import skip_doctest
42 from IPython.utils import openpy
42 from IPython.utils import openpy
43 from IPython.utils.jsonutil import json_clean, encode_images
43 from IPython.utils.jsonutil import json_clean, encode_images
44 from IPython.utils.process import arg_split
44 from IPython.utils.process import arg_split
45 from IPython.utils import py3compat
45 from IPython.utils import py3compat
46 from IPython.utils.py3compat import unicode_type
46 from IPython.utils.py3compat import unicode_type
47 from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes, Any
47 from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes, Any
48 from IPython.utils.warn import error
48 from IPython.utils.warn import error
49 from IPython.kernel.zmq.displayhook import ZMQShellDisplayHook
49 from IPython.kernel.zmq.displayhook import ZMQShellDisplayHook
50 from IPython.kernel.zmq.datapub import ZMQDataPublisher
50 from IPython.kernel.zmq.datapub import ZMQDataPublisher
51 from IPython.kernel.zmq.session import extract_header
51 from IPython.kernel.zmq.session import extract_header
52 from IPython.kernel.comm import CommManager
53 from .session import Session
52 from .session import Session
54
53
55 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
56 # Functions and classes
55 # Functions and classes
57 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
58
57
59 class ZMQDisplayPublisher(DisplayPublisher):
58 class ZMQDisplayPublisher(DisplayPublisher):
60 """A display publisher that publishes data using a ZeroMQ PUB socket."""
59 """A display publisher that publishes data using a ZeroMQ PUB socket."""
61
60
62 session = Instance(Session)
61 session = Instance(Session)
63 pub_socket = Instance(SocketABC)
62 pub_socket = Instance(SocketABC)
64 parent_header = Dict({})
63 parent_header = Dict({})
65 topic = CBytes(b'display_data')
64 topic = CBytes(b'display_data')
66
65
67 def set_parent(self, parent):
66 def set_parent(self, parent):
68 """Set the parent for outbound messages."""
67 """Set the parent for outbound messages."""
69 self.parent_header = extract_header(parent)
68 self.parent_header = extract_header(parent)
70
69
71 def _flush_streams(self):
70 def _flush_streams(self):
72 """flush IO Streams prior to display"""
71 """flush IO Streams prior to display"""
73 sys.stdout.flush()
72 sys.stdout.flush()
74 sys.stderr.flush()
73 sys.stderr.flush()
75
74
76 def publish(self, data, metadata=None, source=None):
75 def publish(self, data, metadata=None, source=None):
77 self._flush_streams()
76 self._flush_streams()
78 if metadata is None:
77 if metadata is None:
79 metadata = {}
78 metadata = {}
80 self._validate_data(data, metadata)
79 self._validate_data(data, metadata)
81 content = {}
80 content = {}
82 content['data'] = encode_images(data)
81 content['data'] = encode_images(data)
83 content['metadata'] = metadata
82 content['metadata'] = metadata
84 self.session.send(
83 self.session.send(
85 self.pub_socket, u'display_data', json_clean(content),
84 self.pub_socket, u'display_data', json_clean(content),
86 parent=self.parent_header, ident=self.topic,
85 parent=self.parent_header, ident=self.topic,
87 )
86 )
88
87
89 def clear_output(self, wait=False):
88 def clear_output(self, wait=False):
90 content = dict(wait=wait)
89 content = dict(wait=wait)
91 self._flush_streams()
90 self._flush_streams()
92 self.session.send(
91 self.session.send(
93 self.pub_socket, u'clear_output', content,
92 self.pub_socket, u'clear_output', content,
94 parent=self.parent_header, ident=self.topic,
93 parent=self.parent_header, ident=self.topic,
95 )
94 )
96
95
97 @magics_class
96 @magics_class
98 class KernelMagics(Magics):
97 class KernelMagics(Magics):
99 #------------------------------------------------------------------------
98 #------------------------------------------------------------------------
100 # Magic overrides
99 # Magic overrides
101 #------------------------------------------------------------------------
100 #------------------------------------------------------------------------
102 # Once the base class stops inheriting from magic, this code needs to be
101 # Once the base class stops inheriting from magic, this code needs to be
103 # moved into a separate machinery as well. For now, at least isolate here
102 # moved into a separate machinery as well. For now, at least isolate here
104 # the magics which this class needs to implement differently from the base
103 # the magics which this class needs to implement differently from the base
105 # class, or that are unique to it.
104 # class, or that are unique to it.
106
105
107 @line_magic
106 @line_magic
108 def doctest_mode(self, parameter_s=''):
107 def doctest_mode(self, parameter_s=''):
109 """Toggle doctest mode on and off.
108 """Toggle doctest mode on and off.
110
109
111 This mode is intended to make IPython behave as much as possible like a
110 This mode is intended to make IPython behave as much as possible like a
112 plain Python shell, from the perspective of how its prompts, exceptions
111 plain Python shell, from the perspective of how its prompts, exceptions
113 and output look. This makes it easy to copy and paste parts of a
112 and output look. This makes it easy to copy and paste parts of a
114 session into doctests. It does so by:
113 session into doctests. It does so by:
115
114
116 - Changing the prompts to the classic ``>>>`` ones.
115 - Changing the prompts to the classic ``>>>`` ones.
117 - Changing the exception reporting mode to 'Plain'.
116 - Changing the exception reporting mode to 'Plain'.
118 - Disabling pretty-printing of output.
117 - Disabling pretty-printing of output.
119
118
120 Note that IPython also supports the pasting of code snippets that have
119 Note that IPython also supports the pasting of code snippets that have
121 leading '>>>' and '...' prompts in them. This means that you can paste
120 leading '>>>' and '...' prompts in them. This means that you can paste
122 doctests from files or docstrings (even if they have leading
121 doctests from files or docstrings (even if they have leading
123 whitespace), and the code will execute correctly. You can then use
122 whitespace), and the code will execute correctly. You can then use
124 '%history -t' to see the translated history; this will give you the
123 '%history -t' to see the translated history; this will give you the
125 input after removal of all the leading prompts and whitespace, which
124 input after removal of all the leading prompts and whitespace, which
126 can be pasted back into an editor.
125 can be pasted back into an editor.
127
126
128 With these features, you can switch into this mode easily whenever you
127 With these features, you can switch into this mode easily whenever you
129 need to do testing and changes to doctests, without having to leave
128 need to do testing and changes to doctests, without having to leave
130 your existing IPython session.
129 your existing IPython session.
131 """
130 """
132
131
133 from IPython.utils.ipstruct import Struct
132 from IPython.utils.ipstruct import Struct
134
133
135 # Shorthands
134 # Shorthands
136 shell = self.shell
135 shell = self.shell
137 disp_formatter = self.shell.display_formatter
136 disp_formatter = self.shell.display_formatter
138 ptformatter = disp_formatter.formatters['text/plain']
137 ptformatter = disp_formatter.formatters['text/plain']
139 # dstore is a data store kept in the instance metadata bag to track any
138 # dstore is a data store kept in the instance metadata bag to track any
140 # changes we make, so we can undo them later.
139 # changes we make, so we can undo them later.
141 dstore = shell.meta.setdefault('doctest_mode', Struct())
140 dstore = shell.meta.setdefault('doctest_mode', Struct())
142 save_dstore = dstore.setdefault
141 save_dstore = dstore.setdefault
143
142
144 # save a few values we'll need to recover later
143 # save a few values we'll need to recover later
145 mode = save_dstore('mode', False)
144 mode = save_dstore('mode', False)
146 save_dstore('rc_pprint', ptformatter.pprint)
145 save_dstore('rc_pprint', ptformatter.pprint)
147 save_dstore('rc_active_types',disp_formatter.active_types)
146 save_dstore('rc_active_types',disp_formatter.active_types)
148 save_dstore('xmode', shell.InteractiveTB.mode)
147 save_dstore('xmode', shell.InteractiveTB.mode)
149
148
150 if mode == False:
149 if mode == False:
151 # turn on
150 # turn on
152 ptformatter.pprint = False
151 ptformatter.pprint = False
153 disp_formatter.active_types = ['text/plain']
152 disp_formatter.active_types = ['text/plain']
154 shell.magic('xmode Plain')
153 shell.magic('xmode Plain')
155 else:
154 else:
156 # turn off
155 # turn off
157 ptformatter.pprint = dstore.rc_pprint
156 ptformatter.pprint = dstore.rc_pprint
158 disp_formatter.active_types = dstore.rc_active_types
157 disp_formatter.active_types = dstore.rc_active_types
159 shell.magic("xmode " + dstore.xmode)
158 shell.magic("xmode " + dstore.xmode)
160
159
161 # Store new mode and inform on console
160 # Store new mode and inform on console
162 dstore.mode = bool(1-int(mode))
161 dstore.mode = bool(1-int(mode))
163 mode_label = ['OFF','ON'][dstore.mode]
162 mode_label = ['OFF','ON'][dstore.mode]
164 print('Doctest mode is:', mode_label)
163 print('Doctest mode is:', mode_label)
165
164
166 # Send the payload back so that clients can modify their prompt display
165 # Send the payload back so that clients can modify their prompt display
167 payload = dict(
166 payload = dict(
168 source='doctest_mode',
167 source='doctest_mode',
169 mode=dstore.mode)
168 mode=dstore.mode)
170 shell.payload_manager.write_payload(payload)
169 shell.payload_manager.write_payload(payload)
171
170
172
171
173 _find_edit_target = CodeMagics._find_edit_target
172 _find_edit_target = CodeMagics._find_edit_target
174
173
175 @skip_doctest
174 @skip_doctest
176 @line_magic
175 @line_magic
177 def edit(self, parameter_s='', last_call=['','']):
176 def edit(self, parameter_s='', last_call=['','']):
178 """Bring up an editor and execute the resulting code.
177 """Bring up an editor and execute the resulting code.
179
178
180 Usage:
179 Usage:
181 %edit [options] [args]
180 %edit [options] [args]
182
181
183 %edit runs an external text editor. You will need to set the command for
182 %edit runs an external text editor. You will need to set the command for
184 this editor via the ``TerminalInteractiveShell.editor`` option in your
183 this editor via the ``TerminalInteractiveShell.editor`` option in your
185 configuration file before it will work.
184 configuration file before it will work.
186
185
187 This command allows you to conveniently edit multi-line code right in
186 This command allows you to conveniently edit multi-line code right in
188 your IPython session.
187 your IPython session.
189
188
190 If called without arguments, %edit opens up an empty editor with a
189 If called without arguments, %edit opens up an empty editor with a
191 temporary file and will execute the contents of this file when you
190 temporary file and will execute the contents of this file when you
192 close it (don't forget to save it!).
191 close it (don't forget to save it!).
193
192
194 Options:
193 Options:
195
194
196 -n <number>
195 -n <number>
197 Open the editor at a specified line number. By default, the IPython
196 Open the editor at a specified line number. By default, the IPython
198 editor hook uses the unix syntax 'editor +N filename', but you can
197 editor hook uses the unix syntax 'editor +N filename', but you can
199 configure this by providing your own modified hook if your favorite
198 configure this by providing your own modified hook if your favorite
200 editor supports line-number specifications with a different syntax.
199 editor supports line-number specifications with a different syntax.
201
200
202 -p
201 -p
203 Call the editor with the same data as the previous time it was used,
202 Call the editor with the same data as the previous time it was used,
204 regardless of how long ago (in your current session) it was.
203 regardless of how long ago (in your current session) it was.
205
204
206 -r
205 -r
207 Use 'raw' input. This option only applies to input taken from the
206 Use 'raw' input. This option only applies to input taken from the
208 user's history. By default, the 'processed' history is used, so that
207 user's history. By default, the 'processed' history is used, so that
209 magics are loaded in their transformed version to valid Python. If
208 magics are loaded in their transformed version to valid Python. If
210 this option is given, the raw input as typed as the command line is
209 this option is given, the raw input as typed as the command line is
211 used instead. When you exit the editor, it will be executed by
210 used instead. When you exit the editor, it will be executed by
212 IPython's own processor.
211 IPython's own processor.
213
212
214 Arguments:
213 Arguments:
215
214
216 If arguments are given, the following possibilites exist:
215 If arguments are given, the following possibilites exist:
217
216
218 - The arguments are numbers or pairs of colon-separated numbers (like
217 - The arguments are numbers or pairs of colon-separated numbers (like
219 1 4:8 9). These are interpreted as lines of previous input to be
218 1 4:8 9). These are interpreted as lines of previous input to be
220 loaded into the editor. The syntax is the same of the %macro command.
219 loaded into the editor. The syntax is the same of the %macro command.
221
220
222 - If the argument doesn't start with a number, it is evaluated as a
221 - If the argument doesn't start with a number, it is evaluated as a
223 variable and its contents loaded into the editor. You can thus edit
222 variable and its contents loaded into the editor. You can thus edit
224 any string which contains python code (including the result of
223 any string which contains python code (including the result of
225 previous edits).
224 previous edits).
226
225
227 - If the argument is the name of an object (other than a string),
226 - If the argument is the name of an object (other than a string),
228 IPython will try to locate the file where it was defined and open the
227 IPython will try to locate the file where it was defined and open the
229 editor at the point where it is defined. You can use ``%edit function``
228 editor at the point where it is defined. You can use ``%edit function``
230 to load an editor exactly at the point where 'function' is defined,
229 to load an editor exactly at the point where 'function' is defined,
231 edit it and have the file be executed automatically.
230 edit it and have the file be executed automatically.
232
231
233 If the object is a macro (see %macro for details), this opens up your
232 If the object is a macro (see %macro for details), this opens up your
234 specified editor with a temporary file containing the macro's data.
233 specified editor with a temporary file containing the macro's data.
235 Upon exit, the macro is reloaded with the contents of the file.
234 Upon exit, the macro is reloaded with the contents of the file.
236
235
237 Note: opening at an exact line is only supported under Unix, and some
236 Note: opening at an exact line is only supported under Unix, and some
238 editors (like kedit and gedit up to Gnome 2.8) do not understand the
237 editors (like kedit and gedit up to Gnome 2.8) do not understand the
239 '+NUMBER' parameter necessary for this feature. Good editors like
238 '+NUMBER' parameter necessary for this feature. Good editors like
240 (X)Emacs, vi, jed, pico and joe all do.
239 (X)Emacs, vi, jed, pico and joe all do.
241
240
242 - If the argument is not found as a variable, IPython will look for a
241 - If the argument is not found as a variable, IPython will look for a
243 file with that name (adding .py if necessary) and load it into the
242 file with that name (adding .py if necessary) and load it into the
244 editor. It will execute its contents with execfile() when you exit,
243 editor. It will execute its contents with execfile() when you exit,
245 loading any code in the file into your interactive namespace.
244 loading any code in the file into your interactive namespace.
246
245
247 Unlike in the terminal, this is designed to use a GUI editor, and we do
246 Unlike in the terminal, this is designed to use a GUI editor, and we do
248 not know when it has closed. So the file you edit will not be
247 not know when it has closed. So the file you edit will not be
249 automatically executed or printed.
248 automatically executed or printed.
250
249
251 Note that %edit is also available through the alias %ed.
250 Note that %edit is also available through the alias %ed.
252 """
251 """
253
252
254 opts,args = self.parse_options(parameter_s,'prn:')
253 opts,args = self.parse_options(parameter_s,'prn:')
255
254
256 try:
255 try:
257 filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
256 filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
258 except MacroToEdit as e:
257 except MacroToEdit as e:
259 # TODO: Implement macro editing over 2 processes.
258 # TODO: Implement macro editing over 2 processes.
260 print("Macro editing not yet implemented in 2-process model.")
259 print("Macro editing not yet implemented in 2-process model.")
261 return
260 return
262
261
263 # Make sure we send to the client an absolute path, in case the working
262 # Make sure we send to the client an absolute path, in case the working
264 # directory of client and kernel don't match
263 # directory of client and kernel don't match
265 filename = os.path.abspath(filename)
264 filename = os.path.abspath(filename)
266
265
267 payload = {
266 payload = {
268 'source' : 'edit_magic',
267 'source' : 'edit_magic',
269 'filename' : filename,
268 'filename' : filename,
270 'line_number' : lineno
269 'line_number' : lineno
271 }
270 }
272 self.shell.payload_manager.write_payload(payload)
271 self.shell.payload_manager.write_payload(payload)
273
272
274 # A few magics that are adapted to the specifics of using pexpect and a
273 # A few magics that are adapted to the specifics of using pexpect and a
275 # remote terminal
274 # remote terminal
276
275
277 @line_magic
276 @line_magic
278 def clear(self, arg_s):
277 def clear(self, arg_s):
279 """Clear the terminal."""
278 """Clear the terminal."""
280 if os.name == 'posix':
279 if os.name == 'posix':
281 self.shell.system("clear")
280 self.shell.system("clear")
282 else:
281 else:
283 self.shell.system("cls")
282 self.shell.system("cls")
284
283
285 if os.name == 'nt':
284 if os.name == 'nt':
286 # This is the usual name in windows
285 # This is the usual name in windows
287 cls = line_magic('cls')(clear)
286 cls = line_magic('cls')(clear)
288
287
289 # Terminal pagers won't work over pexpect, but we do have our own pager
288 # Terminal pagers won't work over pexpect, but we do have our own pager
290
289
291 @line_magic
290 @line_magic
292 def less(self, arg_s):
291 def less(self, arg_s):
293 """Show a file through the pager.
292 """Show a file through the pager.
294
293
295 Files ending in .py are syntax-highlighted."""
294 Files ending in .py are syntax-highlighted."""
296 if not arg_s:
295 if not arg_s:
297 raise UsageError('Missing filename.')
296 raise UsageError('Missing filename.')
298
297
299 cont = open(arg_s).read()
298 cont = open(arg_s).read()
300 if arg_s.endswith('.py'):
299 if arg_s.endswith('.py'):
301 cont = self.shell.pycolorize(openpy.read_py_file(arg_s, skip_encoding_cookie=False))
300 cont = self.shell.pycolorize(openpy.read_py_file(arg_s, skip_encoding_cookie=False))
302 else:
301 else:
303 cont = open(arg_s).read()
302 cont = open(arg_s).read()
304 page.page(cont)
303 page.page(cont)
305
304
306 more = line_magic('more')(less)
305 more = line_magic('more')(less)
307
306
308 # Man calls a pager, so we also need to redefine it
307 # Man calls a pager, so we also need to redefine it
309 if os.name == 'posix':
308 if os.name == 'posix':
310 @line_magic
309 @line_magic
311 def man(self, arg_s):
310 def man(self, arg_s):
312 """Find the man page for the given command and display in pager."""
311 """Find the man page for the given command and display in pager."""
313 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
312 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
314 split=False))
313 split=False))
315
314
316 @line_magic
315 @line_magic
317 def connect_info(self, arg_s):
316 def connect_info(self, arg_s):
318 """Print information for connecting other clients to this kernel
317 """Print information for connecting other clients to this kernel
319
318
320 It will print the contents of this session's connection file, as well as
319 It will print the contents of this session's connection file, as well as
321 shortcuts for local clients.
320 shortcuts for local clients.
322
321
323 In the simplest case, when called from the most recently launched kernel,
322 In the simplest case, when called from the most recently launched kernel,
324 secondary clients can be connected, simply with:
323 secondary clients can be connected, simply with:
325
324
326 $> ipython <app> --existing
325 $> ipython <app> --existing
327
326
328 """
327 """
329
328
330 from IPython.core.application import BaseIPythonApplication as BaseIPApp
329 from IPython.core.application import BaseIPythonApplication as BaseIPApp
331
330
332 if BaseIPApp.initialized():
331 if BaseIPApp.initialized():
333 app = BaseIPApp.instance()
332 app = BaseIPApp.instance()
334 security_dir = app.profile_dir.security_dir
333 security_dir = app.profile_dir.security_dir
335 profile = app.profile
334 profile = app.profile
336 else:
335 else:
337 profile = 'default'
336 profile = 'default'
338 security_dir = ''
337 security_dir = ''
339
338
340 try:
339 try:
341 connection_file = get_connection_file()
340 connection_file = get_connection_file()
342 info = get_connection_info(unpack=False)
341 info = get_connection_info(unpack=False)
343 except Exception as e:
342 except Exception as e:
344 error("Could not get connection info: %r" % e)
343 error("Could not get connection info: %r" % e)
345 return
344 return
346
345
347 # add profile flag for non-default profile
346 # add profile flag for non-default profile
348 profile_flag = "--profile %s" % profile if profile != 'default' else ""
347 profile_flag = "--profile %s" % profile if profile != 'default' else ""
349
348
350 # if it's in the security dir, truncate to basename
349 # if it's in the security dir, truncate to basename
351 if security_dir == os.path.dirname(connection_file):
350 if security_dir == os.path.dirname(connection_file):
352 connection_file = os.path.basename(connection_file)
351 connection_file = os.path.basename(connection_file)
353
352
354
353
355 print (info + '\n')
354 print (info + '\n')
356 print ("Paste the above JSON into a file, and connect with:\n"
355 print ("Paste the above JSON into a file, and connect with:\n"
357 " $> ipython <app> --existing <file>\n"
356 " $> ipython <app> --existing <file>\n"
358 "or, if you are local, you can connect with just:\n"
357 "or, if you are local, you can connect with just:\n"
359 " $> ipython <app> --existing {0} {1}\n"
358 " $> ipython <app> --existing {0} {1}\n"
360 "or even just:\n"
359 "or even just:\n"
361 " $> ipython <app> --existing {1}\n"
360 " $> ipython <app> --existing {1}\n"
362 "if this is the most recent IPython session you have started.".format(
361 "if this is the most recent IPython session you have started.".format(
363 connection_file, profile_flag
362 connection_file, profile_flag
364 )
363 )
365 )
364 )
366
365
367 @line_magic
366 @line_magic
368 def qtconsole(self, arg_s):
367 def qtconsole(self, arg_s):
369 """Open a qtconsole connected to this kernel.
368 """Open a qtconsole connected to this kernel.
370
369
371 Useful for connecting a qtconsole to running notebooks, for better
370 Useful for connecting a qtconsole to running notebooks, for better
372 debugging.
371 debugging.
373 """
372 """
374
373
375 # %qtconsole should imply bind_kernel for engines:
374 # %qtconsole should imply bind_kernel for engines:
376 try:
375 try:
377 from IPython.parallel import bind_kernel
376 from IPython.parallel import bind_kernel
378 except ImportError:
377 except ImportError:
379 # technically possible, because parallel has higher pyzmq min-version
378 # technically possible, because parallel has higher pyzmq min-version
380 pass
379 pass
381 else:
380 else:
382 bind_kernel()
381 bind_kernel()
383
382
384 try:
383 try:
385 p = connect_qtconsole(argv=arg_split(arg_s, os.name=='posix'))
384 p = connect_qtconsole(argv=arg_split(arg_s, os.name=='posix'))
386 except Exception as e:
385 except Exception as e:
387 error("Could not start qtconsole: %r" % e)
386 error("Could not start qtconsole: %r" % e)
388 return
387 return
389
388
390 @line_magic
389 @line_magic
391 def autosave(self, arg_s):
390 def autosave(self, arg_s):
392 """Set the autosave interval in the notebook (in seconds).
391 """Set the autosave interval in the notebook (in seconds).
393
392
394 The default value is 120, or two minutes.
393 The default value is 120, or two minutes.
395 ``%autosave 0`` will disable autosave.
394 ``%autosave 0`` will disable autosave.
396
395
397 This magic only has an effect when called from the notebook interface.
396 This magic only has an effect when called from the notebook interface.
398 It has no effect when called in a startup file.
397 It has no effect when called in a startup file.
399 """
398 """
400
399
401 try:
400 try:
402 interval = int(arg_s)
401 interval = int(arg_s)
403 except ValueError:
402 except ValueError:
404 raise UsageError("%%autosave requires an integer, got %r" % arg_s)
403 raise UsageError("%%autosave requires an integer, got %r" % arg_s)
405
404
406 # javascript wants milliseconds
405 # javascript wants milliseconds
407 milliseconds = 1000 * interval
406 milliseconds = 1000 * interval
408 display(Javascript("IPython.notebook.set_autosave_interval(%i)" % milliseconds),
407 display(Javascript("IPython.notebook.set_autosave_interval(%i)" % milliseconds),
409 include=['application/javascript']
408 include=['application/javascript']
410 )
409 )
411 if interval:
410 if interval:
412 print("Autosaving every %i seconds" % interval)
411 print("Autosaving every %i seconds" % interval)
413 else:
412 else:
414 print("Autosave disabled")
413 print("Autosave disabled")
415
414
416
415
417 class ZMQInteractiveShell(InteractiveShell):
416 class ZMQInteractiveShell(InteractiveShell):
418 """A subclass of InteractiveShell for ZMQ."""
417 """A subclass of InteractiveShell for ZMQ."""
419
418
420 displayhook_class = Type(ZMQShellDisplayHook)
419 displayhook_class = Type(ZMQShellDisplayHook)
421 display_pub_class = Type(ZMQDisplayPublisher)
420 display_pub_class = Type(ZMQDisplayPublisher)
422 data_pub_class = Type(ZMQDataPublisher)
421 data_pub_class = Type(ZMQDataPublisher)
423 kernel = Any()
422 kernel = Any()
424 parent_header = Any()
423 parent_header = Any()
425
424
426 def _banner1_default(self):
425 def _banner1_default(self):
427 return default_gui_banner
426 return default_gui_banner
428
427
429 # Override the traitlet in the parent class, because there's no point using
428 # Override the traitlet in the parent class, because there's no point using
430 # readline for the kernel. Can be removed when the readline code is moved
429 # readline for the kernel. Can be removed when the readline code is moved
431 # to the terminal frontend.
430 # to the terminal frontend.
432 colors_force = CBool(True)
431 colors_force = CBool(True)
433 readline_use = CBool(False)
432 readline_use = CBool(False)
434 # autoindent has no meaning in a zmqshell, and attempting to enable it
433 # autoindent has no meaning in a zmqshell, and attempting to enable it
435 # will print a warning in the absence of readline.
434 # will print a warning in the absence of readline.
436 autoindent = CBool(False)
435 autoindent = CBool(False)
437
436
438 exiter = Instance(ZMQExitAutocall)
437 exiter = Instance(ZMQExitAutocall)
439 def _exiter_default(self):
438 def _exiter_default(self):
440 return ZMQExitAutocall(self)
439 return ZMQExitAutocall(self)
441
440
442 def _exit_now_changed(self, name, old, new):
441 def _exit_now_changed(self, name, old, new):
443 """stop eventloop when exit_now fires"""
442 """stop eventloop when exit_now fires"""
444 if new:
443 if new:
445 loop = ioloop.IOLoop.instance()
444 loop = ioloop.IOLoop.instance()
446 loop.add_timeout(time.time()+0.1, loop.stop)
445 loop.add_timeout(time.time()+0.1, loop.stop)
447
446
448 keepkernel_on_exit = None
447 keepkernel_on_exit = None
449
448
450 # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no
449 # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no
451 # interactive input being read; we provide event loop support in ipkernel
450 # interactive input being read; we provide event loop support in ipkernel
452 @staticmethod
451 @staticmethod
453 def enable_gui(gui):
452 def enable_gui(gui):
454 from .eventloops import enable_gui as real_enable_gui
453 from .eventloops import enable_gui as real_enable_gui
455 try:
454 try:
456 real_enable_gui(gui)
455 real_enable_gui(gui)
457 except ValueError as e:
456 except ValueError as e:
458 raise UsageError("%s" % e)
457 raise UsageError("%s" % e)
459
458
460 def init_environment(self):
459 def init_environment(self):
461 """Configure the user's environment.
460 """Configure the user's environment.
462
461
463 """
462 """
464 env = os.environ
463 env = os.environ
465 # These two ensure 'ls' produces nice coloring on BSD-derived systems
464 # These two ensure 'ls' produces nice coloring on BSD-derived systems
466 env['TERM'] = 'xterm-color'
465 env['TERM'] = 'xterm-color'
467 env['CLICOLOR'] = '1'
466 env['CLICOLOR'] = '1'
468 # Since normal pagers don't work at all (over pexpect we don't have
467 # Since normal pagers don't work at all (over pexpect we don't have
469 # single-key control of the subprocess), try to disable paging in
468 # single-key control of the subprocess), try to disable paging in
470 # subprocesses as much as possible.
469 # subprocesses as much as possible.
471 env['PAGER'] = 'cat'
470 env['PAGER'] = 'cat'
472 env['GIT_PAGER'] = 'cat'
471 env['GIT_PAGER'] = 'cat'
473
472
474 # And install the payload version of page.
473 # And install the payload version of page.
475 install_payload_page()
474 install_payload_page()
476
475
477 def auto_rewrite_input(self, cmd):
476 def auto_rewrite_input(self, cmd):
478 """Called to show the auto-rewritten input for autocall and friends.
477 """Called to show the auto-rewritten input for autocall and friends.
479
478
480 FIXME: this payload is currently not correctly processed by the
479 FIXME: this payload is currently not correctly processed by the
481 frontend.
480 frontend.
482 """
481 """
483 new = self.prompt_manager.render('rewrite') + cmd
482 new = self.prompt_manager.render('rewrite') + cmd
484 payload = dict(
483 payload = dict(
485 source='auto_rewrite_input',
484 source='auto_rewrite_input',
486 transformed_input=new,
485 transformed_input=new,
487 )
486 )
488 self.payload_manager.write_payload(payload)
487 self.payload_manager.write_payload(payload)
489
488
490 def ask_exit(self):
489 def ask_exit(self):
491 """Engage the exit actions."""
490 """Engage the exit actions."""
492 self.exit_now = (not self.keepkernel_on_exit)
491 self.exit_now = (not self.keepkernel_on_exit)
493 payload = dict(
492 payload = dict(
494 source='ask_exit',
493 source='ask_exit',
495 exit=True,
494 exit=True,
496 keepkernel=self.keepkernel_on_exit,
495 keepkernel=self.keepkernel_on_exit,
497 )
496 )
498 self.payload_manager.write_payload(payload)
497 self.payload_manager.write_payload(payload)
499
498
500 def _showtraceback(self, etype, evalue, stb):
499 def _showtraceback(self, etype, evalue, stb):
501 # try to preserve ordering of tracebacks and print statements
500 # try to preserve ordering of tracebacks and print statements
502 sys.stdout.flush()
501 sys.stdout.flush()
503 sys.stderr.flush()
502 sys.stderr.flush()
504
503
505 exc_content = {
504 exc_content = {
506 u'traceback' : stb,
505 u'traceback' : stb,
507 u'ename' : unicode_type(etype.__name__),
506 u'ename' : unicode_type(etype.__name__),
508 u'evalue' : py3compat.safe_unicode(evalue),
507 u'evalue' : py3compat.safe_unicode(evalue),
509 }
508 }
510
509
511 dh = self.displayhook
510 dh = self.displayhook
512 # Send exception info over pub socket for other clients than the caller
511 # Send exception info over pub socket for other clients than the caller
513 # to pick up
512 # to pick up
514 topic = None
513 topic = None
515 if dh.topic:
514 if dh.topic:
516 topic = dh.topic.replace(b'execute_result', b'error')
515 topic = dh.topic.replace(b'execute_result', b'error')
517
516
518 exc_msg = dh.session.send(dh.pub_socket, u'error', json_clean(exc_content), dh.parent_header, ident=topic)
517 exc_msg = dh.session.send(dh.pub_socket, u'error', json_clean(exc_content), dh.parent_header, ident=topic)
519
518
520 # FIXME - Hack: store exception info in shell object. Right now, the
519 # FIXME - Hack: store exception info in shell object. Right now, the
521 # caller is reading this info after the fact, we need to fix this logic
520 # caller is reading this info after the fact, we need to fix this logic
522 # to remove this hack. Even uglier, we need to store the error status
521 # to remove this hack. Even uglier, we need to store the error status
523 # here, because in the main loop, the logic that sets it is being
522 # here, because in the main loop, the logic that sets it is being
524 # skipped because runlines swallows the exceptions.
523 # skipped because runlines swallows the exceptions.
525 exc_content[u'status'] = u'error'
524 exc_content[u'status'] = u'error'
526 self._reply_content = exc_content
525 self._reply_content = exc_content
527 # /FIXME
526 # /FIXME
528
527
529 return exc_content
528 return exc_content
530
529
531 def set_next_input(self, text):
530 def set_next_input(self, text):
532 """Send the specified text to the frontend to be presented at the next
531 """Send the specified text to the frontend to be presented at the next
533 input cell."""
532 input cell."""
534 payload = dict(
533 payload = dict(
535 source='set_next_input',
534 source='set_next_input',
536 text=text
535 text=text
537 )
536 )
538 self.payload_manager.write_payload(payload)
537 self.payload_manager.write_payload(payload)
539
538
540 def set_parent(self, parent):
539 def set_parent(self, parent):
541 """Set the parent header for associating output with its triggering input"""
540 """Set the parent header for associating output with its triggering input"""
542 self.parent_header = parent
541 self.parent_header = parent
543 self.displayhook.set_parent(parent)
542 self.displayhook.set_parent(parent)
544 self.display_pub.set_parent(parent)
543 self.display_pub.set_parent(parent)
545 self.data_pub.set_parent(parent)
544 self.data_pub.set_parent(parent)
546 try:
545 try:
547 sys.stdout.set_parent(parent)
546 sys.stdout.set_parent(parent)
548 except AttributeError:
547 except AttributeError:
549 pass
548 pass
550 try:
549 try:
551 sys.stderr.set_parent(parent)
550 sys.stderr.set_parent(parent)
552 except AttributeError:
551 except AttributeError:
553 pass
552 pass
554
553
555 def get_parent(self):
554 def get_parent(self):
556 return self.parent_header
555 return self.parent_header
557
556
558 #-------------------------------------------------------------------------
557 #-------------------------------------------------------------------------
559 # Things related to magics
558 # Things related to magics
560 #-------------------------------------------------------------------------
559 #-------------------------------------------------------------------------
561
560
562 def init_magics(self):
561 def init_magics(self):
563 super(ZMQInteractiveShell, self).init_magics()
562 super(ZMQInteractiveShell, self).init_magics()
564 self.register_magics(KernelMagics)
563 self.register_magics(KernelMagics)
565 self.magics_manager.register_alias('ed', 'edit')
564 self.magics_manager.register_alias('ed', 'edit')
566
565
567 def init_comms(self):
568 self.comm_manager = CommManager(shell=self, parent=self,
569 kernel=self.kernel)
570 self.configurables.append(self.comm_manager)
571
572
566
573 InteractiveShellABC.register(ZMQInteractiveShell)
567 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now