##// END OF EJS Templates
add InteractiveShell.display_page config...
Min RK -
Show More
@@ -1,3336 +1,3343 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 traceback
25 import traceback
26 import types
26 import types
27 import subprocess
27 import subprocess
28 from io import open as io_open
28 from io import open as io_open
29
29
30 from IPython.config.configurable import SingletonConfigurable
30 from IPython.config.configurable import SingletonConfigurable
31 from IPython.core import debugger, oinspect
31 from IPython.core import debugger, oinspect
32 from IPython.core import magic
32 from IPython.core import magic
33 from IPython.core import page
33 from IPython.core import page
34 from IPython.core import prefilter
34 from IPython.core import prefilter
35 from IPython.core import shadowns
35 from IPython.core import shadowns
36 from IPython.core import ultratb
36 from IPython.core import ultratb
37 from IPython.core.alias import AliasManager, AliasError
37 from IPython.core.alias import AliasManager, AliasError
38 from IPython.core.autocall import ExitAutocall
38 from IPython.core.autocall import ExitAutocall
39 from IPython.core.builtin_trap import BuiltinTrap
39 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.events import EventManager, available_events
40 from IPython.core.events import EventManager, available_events
41 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
41 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
42 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.displayhook import DisplayHook
43 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displaypub import DisplayPublisher
44 from IPython.core.displaypub import DisplayPublisher
45 from IPython.core.error import InputRejected, UsageError
45 from IPython.core.error import InputRejected, UsageError
46 from IPython.core.extensions import ExtensionManager
46 from IPython.core.extensions import ExtensionManager
47 from IPython.core.formatters import DisplayFormatter
47 from IPython.core.formatters import DisplayFormatter
48 from IPython.core.history import HistoryManager
48 from IPython.core.history import HistoryManager
49 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
49 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
50 from IPython.core.logger import Logger
50 from IPython.core.logger import Logger
51 from IPython.core.macro import Macro
51 from IPython.core.macro import Macro
52 from IPython.core.payload import PayloadManager
52 from IPython.core.payload import PayloadManager
53 from IPython.core.prefilter import PrefilterManager
53 from IPython.core.prefilter import PrefilterManager
54 from IPython.core.profiledir import ProfileDir
54 from IPython.core.profiledir import ProfileDir
55 from IPython.core.prompts import PromptManager
55 from IPython.core.prompts import PromptManager
56 from IPython.core.usage import default_banner
56 from IPython.core.usage import default_banner
57 from IPython.lib.latextools import LaTeXTool
57 from IPython.lib.latextools import LaTeXTool
58 from IPython.testing.skipdoctest import skip_doctest
58 from IPython.testing.skipdoctest import skip_doctest
59 from IPython.utils import PyColorize
59 from IPython.utils import PyColorize
60 from IPython.utils import io
60 from IPython.utils import io
61 from IPython.utils import py3compat
61 from IPython.utils import py3compat
62 from IPython.utils import openpy
62 from IPython.utils import openpy
63 from IPython.utils.decorators import undoc
63 from IPython.utils.decorators import undoc
64 from IPython.utils.io import ask_yes_no
64 from IPython.utils.io import ask_yes_no
65 from IPython.utils.ipstruct import Struct
65 from IPython.utils.ipstruct import Struct
66 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename, ensure_dir_exists
66 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename, ensure_dir_exists
67 from IPython.utils.pickleshare import PickleShareDB
67 from IPython.utils.pickleshare import PickleShareDB
68 from IPython.utils.process import system, getoutput
68 from IPython.utils.process import system, getoutput
69 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
69 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
70 with_metaclass, iteritems)
70 with_metaclass, iteritems)
71 from IPython.utils.strdispatch import StrDispatch
71 from IPython.utils.strdispatch import StrDispatch
72 from IPython.utils.syspathcontext import prepended_to_syspath
72 from IPython.utils.syspathcontext import prepended_to_syspath
73 from IPython.utils.text import (format_screen, LSString, SList,
73 from IPython.utils.text import (format_screen, LSString, SList,
74 DollarFormatter)
74 DollarFormatter)
75 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
75 from IPython.utils.traitlets import (Integer, Bool, CBool, CaselessStrEnum, Enum,
76 List, Unicode, Instance, Type)
76 List, Unicode, Instance, Type)
77 from IPython.utils.warn import warn, error
77 from IPython.utils.warn import warn, error
78 import IPython.core.hooks
78 import IPython.core.hooks
79
79
80 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81 # Globals
81 # Globals
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
88 # Utilities
88 # Utilities
89 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
90
90
91 @undoc
91 @undoc
92 def softspace(file, newvalue):
92 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
93 """Copied from code.py, to remove the dependency"""
94
94
95 oldvalue = 0
95 oldvalue = 0
96 try:
96 try:
97 oldvalue = file.softspace
97 oldvalue = file.softspace
98 except AttributeError:
98 except AttributeError:
99 pass
99 pass
100 try:
100 try:
101 file.softspace = newvalue
101 file.softspace = newvalue
102 except (AttributeError, TypeError):
102 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
103 # "attribute-less object" or "read-only attributes"
104 pass
104 pass
105 return oldvalue
105 return oldvalue
106
106
107 @undoc
107 @undoc
108 def no_op(*a, **kw): pass
108 def no_op(*a, **kw): pass
109
109
110 @undoc
110 @undoc
111 class NoOpContext(object):
111 class NoOpContext(object):
112 def __enter__(self): pass
112 def __enter__(self): pass
113 def __exit__(self, type, value, traceback): pass
113 def __exit__(self, type, value, traceback): pass
114 no_op_context = NoOpContext()
114 no_op_context = NoOpContext()
115
115
116 class SpaceInInput(Exception): pass
116 class SpaceInInput(Exception): pass
117
117
118 @undoc
118 @undoc
119 class Bunch: pass
119 class Bunch: pass
120
120
121
121
122 def get_default_colors():
122 def get_default_colors():
123 if sys.platform=='darwin':
123 if sys.platform=='darwin':
124 return "LightBG"
124 return "LightBG"
125 elif os.name=='nt':
125 elif os.name=='nt':
126 return 'Linux'
126 return 'Linux'
127 else:
127 else:
128 return 'Linux'
128 return 'Linux'
129
129
130
130
131 class SeparateUnicode(Unicode):
131 class SeparateUnicode(Unicode):
132 r"""A Unicode subclass to validate separate_in, separate_out, etc.
132 r"""A Unicode subclass to validate separate_in, separate_out, etc.
133
133
134 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
134 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
135 """
135 """
136
136
137 def validate(self, obj, value):
137 def validate(self, obj, value):
138 if value == '0': value = ''
138 if value == '0': value = ''
139 value = value.replace('\\n','\n')
139 value = value.replace('\\n','\n')
140 return super(SeparateUnicode, self).validate(obj, value)
140 return super(SeparateUnicode, self).validate(obj, value)
141
141
142
142
143 class ReadlineNoRecord(object):
143 class ReadlineNoRecord(object):
144 """Context manager to execute some code, then reload readline history
144 """Context manager to execute some code, then reload readline history
145 so that interactive input to the code doesn't appear when pressing up."""
145 so that interactive input to the code doesn't appear when pressing up."""
146 def __init__(self, shell):
146 def __init__(self, shell):
147 self.shell = shell
147 self.shell = shell
148 self._nested_level = 0
148 self._nested_level = 0
149
149
150 def __enter__(self):
150 def __enter__(self):
151 if self._nested_level == 0:
151 if self._nested_level == 0:
152 try:
152 try:
153 self.orig_length = self.current_length()
153 self.orig_length = self.current_length()
154 self.readline_tail = self.get_readline_tail()
154 self.readline_tail = self.get_readline_tail()
155 except (AttributeError, IndexError): # Can fail with pyreadline
155 except (AttributeError, IndexError): # Can fail with pyreadline
156 self.orig_length, self.readline_tail = 999999, []
156 self.orig_length, self.readline_tail = 999999, []
157 self._nested_level += 1
157 self._nested_level += 1
158
158
159 def __exit__(self, type, value, traceback):
159 def __exit__(self, type, value, traceback):
160 self._nested_level -= 1
160 self._nested_level -= 1
161 if self._nested_level == 0:
161 if self._nested_level == 0:
162 # Try clipping the end if it's got longer
162 # Try clipping the end if it's got longer
163 try:
163 try:
164 e = self.current_length() - self.orig_length
164 e = self.current_length() - self.orig_length
165 if e > 0:
165 if e > 0:
166 for _ in range(e):
166 for _ in range(e):
167 self.shell.readline.remove_history_item(self.orig_length)
167 self.shell.readline.remove_history_item(self.orig_length)
168
168
169 # If it still doesn't match, just reload readline history.
169 # If it still doesn't match, just reload readline history.
170 if self.current_length() != self.orig_length \
170 if self.current_length() != self.orig_length \
171 or self.get_readline_tail() != self.readline_tail:
171 or self.get_readline_tail() != self.readline_tail:
172 self.shell.refill_readline_hist()
172 self.shell.refill_readline_hist()
173 except (AttributeError, IndexError):
173 except (AttributeError, IndexError):
174 pass
174 pass
175 # Returning False will cause exceptions to propagate
175 # Returning False will cause exceptions to propagate
176 return False
176 return False
177
177
178 def current_length(self):
178 def current_length(self):
179 return self.shell.readline.get_current_history_length()
179 return self.shell.readline.get_current_history_length()
180
180
181 def get_readline_tail(self, n=10):
181 def get_readline_tail(self, n=10):
182 """Get the last n items in readline history."""
182 """Get the last n items in readline history."""
183 end = self.shell.readline.get_current_history_length() + 1
183 end = self.shell.readline.get_current_history_length() + 1
184 start = max(end-n, 1)
184 start = max(end-n, 1)
185 ghi = self.shell.readline.get_history_item
185 ghi = self.shell.readline.get_history_item
186 return [ghi(x) for x in range(start, end)]
186 return [ghi(x) for x in range(start, end)]
187
187
188
188
189 @undoc
189 @undoc
190 class DummyMod(object):
190 class DummyMod(object):
191 """A dummy module used for IPython's interactive module when
191 """A dummy module used for IPython's interactive module when
192 a namespace must be assigned to the module's __dict__."""
192 a namespace must be assigned to the module's __dict__."""
193 pass
193 pass
194
194
195 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
196 # Main IPython class
196 # Main IPython class
197 #-----------------------------------------------------------------------------
197 #-----------------------------------------------------------------------------
198
198
199 class InteractiveShell(SingletonConfigurable):
199 class InteractiveShell(SingletonConfigurable):
200 """An enhanced, interactive shell for Python."""
200 """An enhanced, interactive shell for Python."""
201
201
202 _instance = None
202 _instance = None
203
203
204 ast_transformers = List([], config=True, help=
204 ast_transformers = List([], config=True, help=
205 """
205 """
206 A list of ast.NodeTransformer subclass instances, which will be applied
206 A list of ast.NodeTransformer subclass instances, which will be applied
207 to user input before code is run.
207 to user input before code is run.
208 """
208 """
209 )
209 )
210
210
211 autocall = Enum((0,1,2), default_value=0, config=True, help=
211 autocall = Enum((0,1,2), default_value=0, config=True, help=
212 """
212 """
213 Make IPython automatically call any callable object even if you didn't
213 Make IPython automatically call any callable object even if you didn't
214 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
215 automatically. The value can be '0' to disable the feature, '1' for
215 automatically. The value can be '0' to disable the feature, '1' for
216 'smart' autocall, where it is not applied if there are no more
216 'smart' autocall, where it is not applied if there are no more
217 arguments on the line, and '2' for 'full' autocall, where all callable
217 arguments on the line, and '2' for 'full' autocall, where all callable
218 objects are automatically called (even if no arguments are present).
218 objects are automatically called (even if no arguments are present).
219 """
219 """
220 )
220 )
221 # TODO: remove all autoindent logic and put into frontends.
221 # TODO: remove all autoindent logic and put into frontends.
222 # We can't do this yet because even runlines uses the autoindent.
222 # We can't do this yet because even runlines uses the autoindent.
223 autoindent = CBool(True, config=True, help=
223 autoindent = CBool(True, config=True, help=
224 """
224 """
225 Autoindent IPython code entered interactively.
225 Autoindent IPython code entered interactively.
226 """
226 """
227 )
227 )
228 automagic = CBool(True, config=True, help=
228 automagic = CBool(True, config=True, help=
229 """
229 """
230 Enable magic commands to be called without the leading %.
230 Enable magic commands to be called without the leading %.
231 """
231 """
232 )
232 )
233
233
234 banner = Unicode('')
234 banner = Unicode('')
235
235
236 banner1 = Unicode(default_banner, config=True,
236 banner1 = Unicode(default_banner, config=True,
237 help="""The part of the banner to be printed before the profile"""
237 help="""The part of the banner to be printed before the profile"""
238 )
238 )
239 banner2 = Unicode('', config=True,
239 banner2 = Unicode('', config=True,
240 help="""The part of the banner to be printed after the profile"""
240 help="""The part of the banner to be printed after the profile"""
241 )
241 )
242
242
243 cache_size = Integer(1000, config=True, help=
243 cache_size = Integer(1000, config=True, help=
244 """
244 """
245 Set the size of the output cache. The default is 1000, you can
245 Set the size of the output cache. The default is 1000, you can
246 change it permanently in your config file. Setting it to 0 completely
246 change it permanently in your config file. Setting it to 0 completely
247 disables the caching system, and the minimum value accepted is 20 (if
247 disables the caching system, and the minimum value accepted is 20 (if
248 you provide a value less than 20, it is reset to 0 and a warning is
248 you provide a value less than 20, it is reset to 0 and a warning is
249 issued). This limit is defined because otherwise you'll spend more
249 issued). This limit is defined because otherwise you'll spend more
250 time re-flushing a too small cache than working
250 time re-flushing a too small cache than working
251 """
251 """
252 )
252 )
253 color_info = CBool(True, config=True, help=
253 color_info = CBool(True, config=True, help=
254 """
254 """
255 Use colors for displaying information about objects. Because this
255 Use colors for displaying information about objects. Because this
256 information is passed through a pager (like 'less'), and some pagers
256 information is passed through a pager (like 'less'), and some pagers
257 get confused with color codes, this capability can be turned off.
257 get confused with color codes, this capability can be turned off.
258 """
258 """
259 )
259 )
260 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
260 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
261 default_value=get_default_colors(), config=True,
261 default_value=get_default_colors(), config=True,
262 help="Set the color scheme (NoColor, Linux, or LightBG)."
262 help="Set the color scheme (NoColor, Linux, or LightBG)."
263 )
263 )
264 colors_force = CBool(False, help=
264 colors_force = CBool(False, help=
265 """
265 """
266 Force use of ANSI color codes, regardless of OS and readline
266 Force use of ANSI color codes, regardless of OS and readline
267 availability.
267 availability.
268 """
268 """
269 # FIXME: This is essentially a hack to allow ZMQShell to show colors
269 # FIXME: This is essentially a hack to allow ZMQShell to show colors
270 # without readline on Win32. When the ZMQ formatting system is
270 # without readline on Win32. When the ZMQ formatting system is
271 # refactored, this should be removed.
271 # refactored, this should be removed.
272 )
272 )
273 debug = CBool(False, config=True)
273 debug = CBool(False, config=True)
274 deep_reload = CBool(False, config=True, help=
274 deep_reload = CBool(False, config=True, help=
275 """
275 """
276 Enable deep (recursive) reloading by default. IPython can use the
276 Enable deep (recursive) reloading by default. IPython can use the
277 deep_reload module which reloads changes in modules recursively (it
277 deep_reload module which reloads changes in modules recursively (it
278 replaces the reload() function, so you don't need to change anything to
278 replaces the reload() function, so you don't need to change anything to
279 use it). deep_reload() forces a full reload of modules whose code may
279 use it). deep_reload() forces a full reload of modules whose code may
280 have changed, which the default reload() function does not. When
280 have changed, which the default reload() function does not. When
281 deep_reload is off, IPython will use the normal reload(), but
281 deep_reload is off, IPython will use the normal reload(), but
282 deep_reload will still be available as dreload().
282 deep_reload will still be available as dreload().
283 """
283 """
284 )
284 )
285 disable_failing_post_execute = CBool(False, config=True,
285 disable_failing_post_execute = CBool(False, config=True,
286 help="Don't call post-execute functions that have failed in the past."
286 help="Don't call post-execute functions that have failed in the past."
287 )
287 )
288 display_formatter = Instance(DisplayFormatter)
288 display_formatter = Instance(DisplayFormatter)
289 displayhook_class = Type(DisplayHook)
289 displayhook_class = Type(DisplayHook)
290 display_pub_class = Type(DisplayPublisher)
290 display_pub_class = Type(DisplayPublisher)
291 data_pub_class = None
291 data_pub_class = None
292
292
293 exit_now = CBool(False)
293 exit_now = CBool(False)
294 exiter = Instance(ExitAutocall)
294 exiter = Instance(ExitAutocall)
295 def _exiter_default(self):
295 def _exiter_default(self):
296 return ExitAutocall(self)
296 return ExitAutocall(self)
297 # Monotonically increasing execution counter
297 # Monotonically increasing execution counter
298 execution_count = Integer(1)
298 execution_count = Integer(1)
299 filename = Unicode("<ipython console>")
299 filename = Unicode("<ipython console>")
300 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
300 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
301
301
302 # Input splitter, to transform input line by line and detect when a block
302 # Input splitter, to transform input line by line and detect when a block
303 # is ready to be executed.
303 # is ready to be executed.
304 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
304 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
305 (), {'line_input_checker': True})
305 (), {'line_input_checker': True})
306
306
307 # This InputSplitter instance is used to transform completed cells before
307 # This InputSplitter instance is used to transform completed cells before
308 # running them. It allows cell magics to contain blank lines.
308 # running them. It allows cell magics to contain blank lines.
309 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
309 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
310 (), {'line_input_checker': False})
310 (), {'line_input_checker': False})
311
311
312 logstart = CBool(False, config=True, help=
312 logstart = CBool(False, config=True, help=
313 """
313 """
314 Start logging to the default log file.
314 Start logging to the default log file.
315 """
315 """
316 )
316 )
317 logfile = Unicode('', config=True, help=
317 logfile = Unicode('', config=True, help=
318 """
318 """
319 The name of the logfile to use.
319 The name of the logfile to use.
320 """
320 """
321 )
321 )
322 logappend = Unicode('', config=True, help=
322 logappend = Unicode('', config=True, help=
323 """
323 """
324 Start logging to the given file in append mode.
324 Start logging to the given file in append mode.
325 """
325 """
326 )
326 )
327 object_info_string_level = Enum((0,1,2), default_value=0,
327 object_info_string_level = Enum((0,1,2), default_value=0,
328 config=True)
328 config=True)
329 pdb = CBool(False, config=True, help=
329 pdb = CBool(False, config=True, help=
330 """
330 """
331 Automatically call the pdb debugger after every exception.
331 Automatically call the pdb debugger after every exception.
332 """
332 """
333 )
333 )
334 multiline_history = CBool(sys.platform != 'win32', config=True,
334 multiline_history = CBool(sys.platform != 'win32', config=True,
335 help="Save multi-line entries as one entry in readline history"
335 help="Save multi-line entries as one entry in readline history"
336 )
336 )
337 display_page = Bool(False, config=True,
338 help="""If True, anything that would be passed to the pager
339 will be displayed as regular output instead."""
340 )
337
341
338 # deprecated prompt traits:
342 # deprecated prompt traits:
339
343
340 prompt_in1 = Unicode('In [\\#]: ', config=True,
344 prompt_in1 = Unicode('In [\\#]: ', config=True,
341 help="Deprecated, use PromptManager.in_template")
345 help="Deprecated, use PromptManager.in_template")
342 prompt_in2 = Unicode(' .\\D.: ', config=True,
346 prompt_in2 = Unicode(' .\\D.: ', config=True,
343 help="Deprecated, use PromptManager.in2_template")
347 help="Deprecated, use PromptManager.in2_template")
344 prompt_out = Unicode('Out[\\#]: ', config=True,
348 prompt_out = Unicode('Out[\\#]: ', config=True,
345 help="Deprecated, use PromptManager.out_template")
349 help="Deprecated, use PromptManager.out_template")
346 prompts_pad_left = CBool(True, config=True,
350 prompts_pad_left = CBool(True, config=True,
347 help="Deprecated, use PromptManager.justify")
351 help="Deprecated, use PromptManager.justify")
348
352
349 def _prompt_trait_changed(self, name, old, new):
353 def _prompt_trait_changed(self, name, old, new):
350 table = {
354 table = {
351 'prompt_in1' : 'in_template',
355 'prompt_in1' : 'in_template',
352 'prompt_in2' : 'in2_template',
356 'prompt_in2' : 'in2_template',
353 'prompt_out' : 'out_template',
357 'prompt_out' : 'out_template',
354 'prompts_pad_left' : 'justify',
358 'prompts_pad_left' : 'justify',
355 }
359 }
356 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
360 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
357 name=name, newname=table[name])
361 name=name, newname=table[name])
358 )
362 )
359 # protect against weird cases where self.config may not exist:
363 # protect against weird cases where self.config may not exist:
360 if self.config is not None:
364 if self.config is not None:
361 # propagate to corresponding PromptManager trait
365 # propagate to corresponding PromptManager trait
362 setattr(self.config.PromptManager, table[name], new)
366 setattr(self.config.PromptManager, table[name], new)
363
367
364 _prompt_in1_changed = _prompt_trait_changed
368 _prompt_in1_changed = _prompt_trait_changed
365 _prompt_in2_changed = _prompt_trait_changed
369 _prompt_in2_changed = _prompt_trait_changed
366 _prompt_out_changed = _prompt_trait_changed
370 _prompt_out_changed = _prompt_trait_changed
367 _prompt_pad_left_changed = _prompt_trait_changed
371 _prompt_pad_left_changed = _prompt_trait_changed
368
372
369 show_rewritten_input = CBool(True, config=True,
373 show_rewritten_input = CBool(True, config=True,
370 help="Show rewritten input, e.g. for autocall."
374 help="Show rewritten input, e.g. for autocall."
371 )
375 )
372
376
373 quiet = CBool(False, config=True)
377 quiet = CBool(False, config=True)
374
378
375 history_length = Integer(10000, config=True)
379 history_length = Integer(10000, config=True)
376
380
377 # The readline stuff will eventually be moved to the terminal subclass
381 # The readline stuff will eventually be moved to the terminal subclass
378 # but for now, we can't do that as readline is welded in everywhere.
382 # but for now, we can't do that as readline is welded in everywhere.
379 readline_use = CBool(True, config=True)
383 readline_use = CBool(True, config=True)
380 readline_remove_delims = Unicode('-/~', config=True)
384 readline_remove_delims = Unicode('-/~', config=True)
381 readline_delims = Unicode() # set by init_readline()
385 readline_delims = Unicode() # set by init_readline()
382 # don't use \M- bindings by default, because they
386 # don't use \M- bindings by default, because they
383 # conflict with 8-bit encodings. See gh-58,gh-88
387 # conflict with 8-bit encodings. See gh-58,gh-88
384 readline_parse_and_bind = List([
388 readline_parse_and_bind = List([
385 'tab: complete',
389 'tab: complete',
386 '"\C-l": clear-screen',
390 '"\C-l": clear-screen',
387 'set show-all-if-ambiguous on',
391 'set show-all-if-ambiguous on',
388 '"\C-o": tab-insert',
392 '"\C-o": tab-insert',
389 '"\C-r": reverse-search-history',
393 '"\C-r": reverse-search-history',
390 '"\C-s": forward-search-history',
394 '"\C-s": forward-search-history',
391 '"\C-p": history-search-backward',
395 '"\C-p": history-search-backward',
392 '"\C-n": history-search-forward',
396 '"\C-n": history-search-forward',
393 '"\e[A": history-search-backward',
397 '"\e[A": history-search-backward',
394 '"\e[B": history-search-forward',
398 '"\e[B": history-search-forward',
395 '"\C-k": kill-line',
399 '"\C-k": kill-line',
396 '"\C-u": unix-line-discard',
400 '"\C-u": unix-line-discard',
397 ], config=True)
401 ], config=True)
398
402
399 _custom_readline_config = False
403 _custom_readline_config = False
400
404
401 def _readline_parse_and_bind_changed(self, name, old, new):
405 def _readline_parse_and_bind_changed(self, name, old, new):
402 # notice that readline config is customized
406 # notice that readline config is customized
403 # indicates that it should have higher priority than inputrc
407 # indicates that it should have higher priority than inputrc
404 self._custom_readline_config = True
408 self._custom_readline_config = True
405
409
406 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
410 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
407 default_value='last_expr', config=True,
411 default_value='last_expr', config=True,
408 help="""
412 help="""
409 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
413 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
410 run interactively (displaying output from expressions).""")
414 run interactively (displaying output from expressions).""")
411
415
412 # TODO: this part of prompt management should be moved to the frontends.
416 # TODO: this part of prompt management should be moved to the frontends.
413 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
417 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
414 separate_in = SeparateUnicode('\n', config=True)
418 separate_in = SeparateUnicode('\n', config=True)
415 separate_out = SeparateUnicode('', config=True)
419 separate_out = SeparateUnicode('', config=True)
416 separate_out2 = SeparateUnicode('', config=True)
420 separate_out2 = SeparateUnicode('', config=True)
417 wildcards_case_sensitive = CBool(True, config=True)
421 wildcards_case_sensitive = CBool(True, config=True)
418 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
422 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
419 default_value='Context', config=True)
423 default_value='Context', config=True)
420
424
421 # Subcomponents of InteractiveShell
425 # Subcomponents of InteractiveShell
422 alias_manager = Instance('IPython.core.alias.AliasManager')
426 alias_manager = Instance('IPython.core.alias.AliasManager')
423 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
427 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
424 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
428 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
425 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
429 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
426 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
430 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
427 payload_manager = Instance('IPython.core.payload.PayloadManager')
431 payload_manager = Instance('IPython.core.payload.PayloadManager')
428 history_manager = Instance('IPython.core.history.HistoryAccessorBase')
432 history_manager = Instance('IPython.core.history.HistoryAccessorBase')
429 magics_manager = Instance('IPython.core.magic.MagicsManager')
433 magics_manager = Instance('IPython.core.magic.MagicsManager')
430
434
431 profile_dir = Instance('IPython.core.application.ProfileDir')
435 profile_dir = Instance('IPython.core.application.ProfileDir')
432 @property
436 @property
433 def profile(self):
437 def profile(self):
434 if self.profile_dir is not None:
438 if self.profile_dir is not None:
435 name = os.path.basename(self.profile_dir.location)
439 name = os.path.basename(self.profile_dir.location)
436 return name.replace('profile_','')
440 return name.replace('profile_','')
437
441
438
442
439 # Private interface
443 # Private interface
440 _post_execute = Instance(dict)
444 _post_execute = Instance(dict)
441
445
442 # Tracks any GUI loop loaded for pylab
446 # Tracks any GUI loop loaded for pylab
443 pylab_gui_select = None
447 pylab_gui_select = None
444
448
445 def __init__(self, ipython_dir=None, profile_dir=None,
449 def __init__(self, ipython_dir=None, profile_dir=None,
446 user_module=None, user_ns=None,
450 user_module=None, user_ns=None,
447 custom_exceptions=((), None), **kwargs):
451 custom_exceptions=((), None), **kwargs):
448
452
449 # This is where traits with a config_key argument are updated
453 # This is where traits with a config_key argument are updated
450 # from the values on config.
454 # from the values on config.
451 super(InteractiveShell, self).__init__(**kwargs)
455 super(InteractiveShell, self).__init__(**kwargs)
452 self.configurables = [self]
456 self.configurables = [self]
453
457
454 # These are relatively independent and stateless
458 # These are relatively independent and stateless
455 self.init_ipython_dir(ipython_dir)
459 self.init_ipython_dir(ipython_dir)
456 self.init_profile_dir(profile_dir)
460 self.init_profile_dir(profile_dir)
457 self.init_instance_attrs()
461 self.init_instance_attrs()
458 self.init_environment()
462 self.init_environment()
459
463
460 # Check if we're in a virtualenv, and set up sys.path.
464 # Check if we're in a virtualenv, and set up sys.path.
461 self.init_virtualenv()
465 self.init_virtualenv()
462
466
463 # Create namespaces (user_ns, user_global_ns, etc.)
467 # Create namespaces (user_ns, user_global_ns, etc.)
464 self.init_create_namespaces(user_module, user_ns)
468 self.init_create_namespaces(user_module, user_ns)
465 # This has to be done after init_create_namespaces because it uses
469 # This has to be done after init_create_namespaces because it uses
466 # something in self.user_ns, but before init_sys_modules, which
470 # something in self.user_ns, but before init_sys_modules, which
467 # is the first thing to modify sys.
471 # is the first thing to modify sys.
468 # TODO: When we override sys.stdout and sys.stderr before this class
472 # TODO: When we override sys.stdout and sys.stderr before this class
469 # is created, we are saving the overridden ones here. Not sure if this
473 # is created, we are saving the overridden ones here. Not sure if this
470 # is what we want to do.
474 # is what we want to do.
471 self.save_sys_module_state()
475 self.save_sys_module_state()
472 self.init_sys_modules()
476 self.init_sys_modules()
473
477
474 # While we're trying to have each part of the code directly access what
478 # While we're trying to have each part of the code directly access what
475 # it needs without keeping redundant references to objects, we have too
479 # it needs without keeping redundant references to objects, we have too
476 # much legacy code that expects ip.db to exist.
480 # much legacy code that expects ip.db to exist.
477 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
481 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
478
482
479 self.init_history()
483 self.init_history()
480 self.init_encoding()
484 self.init_encoding()
481 self.init_prefilter()
485 self.init_prefilter()
482
486
483 self.init_syntax_highlighting()
487 self.init_syntax_highlighting()
484 self.init_hooks()
488 self.init_hooks()
485 self.init_events()
489 self.init_events()
486 self.init_pushd_popd_magic()
490 self.init_pushd_popd_magic()
487 # self.init_traceback_handlers use to be here, but we moved it below
491 # self.init_traceback_handlers use to be here, but we moved it below
488 # because it and init_io have to come after init_readline.
492 # because it and init_io have to come after init_readline.
489 self.init_user_ns()
493 self.init_user_ns()
490 self.init_logger()
494 self.init_logger()
491 self.init_builtins()
495 self.init_builtins()
492
496
493 # The following was in post_config_initialization
497 # The following was in post_config_initialization
494 self.init_inspector()
498 self.init_inspector()
495 # init_readline() must come before init_io(), because init_io uses
499 # init_readline() must come before init_io(), because init_io uses
496 # readline related things.
500 # readline related things.
497 self.init_readline()
501 self.init_readline()
498 # We save this here in case user code replaces raw_input, but it needs
502 # We save this here in case user code replaces raw_input, but it needs
499 # to be after init_readline(), because PyPy's readline works by replacing
503 # to be after init_readline(), because PyPy's readline works by replacing
500 # raw_input.
504 # raw_input.
501 if py3compat.PY3:
505 if py3compat.PY3:
502 self.raw_input_original = input
506 self.raw_input_original = input
503 else:
507 else:
504 self.raw_input_original = raw_input
508 self.raw_input_original = raw_input
505 # init_completer must come after init_readline, because it needs to
509 # init_completer must come after init_readline, because it needs to
506 # know whether readline is present or not system-wide to configure the
510 # know whether readline is present or not system-wide to configure the
507 # completers, since the completion machinery can now operate
511 # completers, since the completion machinery can now operate
508 # independently of readline (e.g. over the network)
512 # independently of readline (e.g. over the network)
509 self.init_completer()
513 self.init_completer()
510 # TODO: init_io() needs to happen before init_traceback handlers
514 # TODO: init_io() needs to happen before init_traceback handlers
511 # because the traceback handlers hardcode the stdout/stderr streams.
515 # because the traceback handlers hardcode the stdout/stderr streams.
512 # This logic in in debugger.Pdb and should eventually be changed.
516 # This logic in in debugger.Pdb and should eventually be changed.
513 self.init_io()
517 self.init_io()
514 self.init_traceback_handlers(custom_exceptions)
518 self.init_traceback_handlers(custom_exceptions)
515 self.init_prompts()
519 self.init_prompts()
516 self.init_display_formatter()
520 self.init_display_formatter()
517 self.init_display_pub()
521 self.init_display_pub()
518 self.init_data_pub()
522 self.init_data_pub()
519 self.init_displayhook()
523 self.init_displayhook()
520 self.init_latextool()
524 self.init_latextool()
521 self.init_magics()
525 self.init_magics()
522 self.init_alias()
526 self.init_alias()
523 self.init_logstart()
527 self.init_logstart()
524 self.init_pdb()
528 self.init_pdb()
525 self.init_extension_manager()
529 self.init_extension_manager()
526 self.init_payload()
530 self.init_payload()
527 self.hooks.late_startup_hook()
531 self.hooks.late_startup_hook()
528 self.events.trigger('shell_initialized', self)
532 self.events.trigger('shell_initialized', self)
529 atexit.register(self.atexit_operations)
533 atexit.register(self.atexit_operations)
530
534
531 def get_ipython(self):
535 def get_ipython(self):
532 """Return the currently running IPython instance."""
536 """Return the currently running IPython instance."""
533 return self
537 return self
534
538
535 #-------------------------------------------------------------------------
539 #-------------------------------------------------------------------------
536 # Trait changed handlers
540 # Trait changed handlers
537 #-------------------------------------------------------------------------
541 #-------------------------------------------------------------------------
538
542
539 def _ipython_dir_changed(self, name, new):
543 def _ipython_dir_changed(self, name, new):
540 ensure_dir_exists(new)
544 ensure_dir_exists(new)
541
545
542 def set_autoindent(self,value=None):
546 def set_autoindent(self,value=None):
543 """Set the autoindent flag, checking for readline support.
547 """Set the autoindent flag, checking for readline support.
544
548
545 If called with no arguments, it acts as a toggle."""
549 If called with no arguments, it acts as a toggle."""
546
550
547 if value != 0 and not self.has_readline:
551 if value != 0 and not self.has_readline:
548 if os.name == 'posix':
552 if os.name == 'posix':
549 warn("The auto-indent feature requires the readline library")
553 warn("The auto-indent feature requires the readline library")
550 self.autoindent = 0
554 self.autoindent = 0
551 return
555 return
552 if value is None:
556 if value is None:
553 self.autoindent = not self.autoindent
557 self.autoindent = not self.autoindent
554 else:
558 else:
555 self.autoindent = value
559 self.autoindent = value
556
560
557 #-------------------------------------------------------------------------
561 #-------------------------------------------------------------------------
558 # init_* methods called by __init__
562 # init_* methods called by __init__
559 #-------------------------------------------------------------------------
563 #-------------------------------------------------------------------------
560
564
561 def init_ipython_dir(self, ipython_dir):
565 def init_ipython_dir(self, ipython_dir):
562 if ipython_dir is not None:
566 if ipython_dir is not None:
563 self.ipython_dir = ipython_dir
567 self.ipython_dir = ipython_dir
564 return
568 return
565
569
566 self.ipython_dir = get_ipython_dir()
570 self.ipython_dir = get_ipython_dir()
567
571
568 def init_profile_dir(self, profile_dir):
572 def init_profile_dir(self, profile_dir):
569 if profile_dir is not None:
573 if profile_dir is not None:
570 self.profile_dir = profile_dir
574 self.profile_dir = profile_dir
571 return
575 return
572 self.profile_dir =\
576 self.profile_dir =\
573 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
577 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
574
578
575 def init_instance_attrs(self):
579 def init_instance_attrs(self):
576 self.more = False
580 self.more = False
577
581
578 # command compiler
582 # command compiler
579 self.compile = CachingCompiler()
583 self.compile = CachingCompiler()
580
584
581 # Make an empty namespace, which extension writers can rely on both
585 # Make an empty namespace, which extension writers can rely on both
582 # existing and NEVER being used by ipython itself. This gives them a
586 # existing and NEVER being used by ipython itself. This gives them a
583 # convenient location for storing additional information and state
587 # convenient location for storing additional information and state
584 # their extensions may require, without fear of collisions with other
588 # their extensions may require, without fear of collisions with other
585 # ipython names that may develop later.
589 # ipython names that may develop later.
586 self.meta = Struct()
590 self.meta = Struct()
587
591
588 # Temporary files used for various purposes. Deleted at exit.
592 # Temporary files used for various purposes. Deleted at exit.
589 self.tempfiles = []
593 self.tempfiles = []
590 self.tempdirs = []
594 self.tempdirs = []
591
595
592 # Keep track of readline usage (later set by init_readline)
596 # Keep track of readline usage (later set by init_readline)
593 self.has_readline = False
597 self.has_readline = False
594
598
595 # keep track of where we started running (mainly for crash post-mortem)
599 # keep track of where we started running (mainly for crash post-mortem)
596 # This is not being used anywhere currently.
600 # This is not being used anywhere currently.
597 self.starting_dir = py3compat.getcwd()
601 self.starting_dir = py3compat.getcwd()
598
602
599 # Indentation management
603 # Indentation management
600 self.indent_current_nsp = 0
604 self.indent_current_nsp = 0
601
605
602 # Dict to track post-execution functions that have been registered
606 # Dict to track post-execution functions that have been registered
603 self._post_execute = {}
607 self._post_execute = {}
604
608
605 def init_environment(self):
609 def init_environment(self):
606 """Any changes we need to make to the user's environment."""
610 """Any changes we need to make to the user's environment."""
607 pass
611 pass
608
612
609 def init_encoding(self):
613 def init_encoding(self):
610 # Get system encoding at startup time. Certain terminals (like Emacs
614 # 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
615 # under Win32 have it set to None, and we need to have a known valid
612 # encoding to use in the raw_input() method
616 # encoding to use in the raw_input() method
613 try:
617 try:
614 self.stdin_encoding = sys.stdin.encoding or 'ascii'
618 self.stdin_encoding = sys.stdin.encoding or 'ascii'
615 except AttributeError:
619 except AttributeError:
616 self.stdin_encoding = 'ascii'
620 self.stdin_encoding = 'ascii'
617
621
618 def init_syntax_highlighting(self):
622 def init_syntax_highlighting(self):
619 # Python source parser/formatter for syntax highlighting
623 # Python source parser/formatter for syntax highlighting
620 pyformat = PyColorize.Parser().format
624 pyformat = PyColorize.Parser().format
621 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
625 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
622
626
623 def init_pushd_popd_magic(self):
627 def init_pushd_popd_magic(self):
624 # for pushd/popd management
628 # for pushd/popd management
625 self.home_dir = get_home_dir()
629 self.home_dir = get_home_dir()
626
630
627 self.dir_stack = []
631 self.dir_stack = []
628
632
629 def init_logger(self):
633 def init_logger(self):
630 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
634 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
631 logmode='rotate')
635 logmode='rotate')
632
636
633 def init_logstart(self):
637 def init_logstart(self):
634 """Initialize logging in case it was requested at the command line.
638 """Initialize logging in case it was requested at the command line.
635 """
639 """
636 if self.logappend:
640 if self.logappend:
637 self.magic('logstart %s append' % self.logappend)
641 self.magic('logstart %s append' % self.logappend)
638 elif self.logfile:
642 elif self.logfile:
639 self.magic('logstart %s' % self.logfile)
643 self.magic('logstart %s' % self.logfile)
640 elif self.logstart:
644 elif self.logstart:
641 self.magic('logstart')
645 self.magic('logstart')
642
646
643 def init_builtins(self):
647 def init_builtins(self):
644 # A single, static flag that we set to True. Its presence indicates
648 # 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
649 # 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
650 # removing on exit or representing the existence of more than one
647 # IPython at a time.
651 # IPython at a time.
648 builtin_mod.__dict__['__IPYTHON__'] = True
652 builtin_mod.__dict__['__IPYTHON__'] = True
649
653
650 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
654 # 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
655 # 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
656 # 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
657 # those who adapted their codes to check for this flag, but will
654 # eventually remove it after a few more releases.
658 # eventually remove it after a few more releases.
655 builtin_mod.__dict__['__IPYTHON__active'] = \
659 builtin_mod.__dict__['__IPYTHON__active'] = \
656 'Deprecated, check for __IPYTHON__'
660 'Deprecated, check for __IPYTHON__'
657
661
658 self.builtin_trap = BuiltinTrap(shell=self)
662 self.builtin_trap = BuiltinTrap(shell=self)
659
663
660 def init_inspector(self):
664 def init_inspector(self):
661 # Object inspector
665 # Object inspector
662 self.inspector = oinspect.Inspector(oinspect.InspectColors,
666 self.inspector = oinspect.Inspector(oinspect.InspectColors,
663 PyColorize.ANSICodeColors,
667 PyColorize.ANSICodeColors,
664 'NoColor',
668 'NoColor',
665 self.object_info_string_level)
669 self.object_info_string_level)
666
670
667 def init_io(self):
671 def init_io(self):
668 # This will just use sys.stdout and sys.stderr. If you want to
672 # 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
673 # override sys.stdout and sys.stderr themselves, you need to do that
670 # *before* instantiating this class, because io holds onto
674 # *before* instantiating this class, because io holds onto
671 # references to the underlying streams.
675 # references to the underlying streams.
672 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
676 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
673 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
677 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
674 else:
678 else:
675 io.stdout = io.IOStream(sys.stdout)
679 io.stdout = io.IOStream(sys.stdout)
676 io.stderr = io.IOStream(sys.stderr)
680 io.stderr = io.IOStream(sys.stderr)
677
681
678 def init_prompts(self):
682 def init_prompts(self):
679 self.prompt_manager = PromptManager(shell=self, parent=self)
683 self.prompt_manager = PromptManager(shell=self, parent=self)
680 self.configurables.append(self.prompt_manager)
684 self.configurables.append(self.prompt_manager)
681 # Set system prompts, so that scripts can decide if they are running
685 # Set system prompts, so that scripts can decide if they are running
682 # interactively.
686 # interactively.
683 sys.ps1 = 'In : '
687 sys.ps1 = 'In : '
684 sys.ps2 = '...: '
688 sys.ps2 = '...: '
685 sys.ps3 = 'Out: '
689 sys.ps3 = 'Out: '
686
690
687 def init_display_formatter(self):
691 def init_display_formatter(self):
688 self.display_formatter = DisplayFormatter(parent=self)
692 self.display_formatter = DisplayFormatter(parent=self)
689 self.configurables.append(self.display_formatter)
693 self.configurables.append(self.display_formatter)
690
694
691 def init_display_pub(self):
695 def init_display_pub(self):
692 self.display_pub = self.display_pub_class(parent=self)
696 self.display_pub = self.display_pub_class(parent=self)
693 self.configurables.append(self.display_pub)
697 self.configurables.append(self.display_pub)
694
698
695 def init_data_pub(self):
699 def init_data_pub(self):
696 if not self.data_pub_class:
700 if not self.data_pub_class:
697 self.data_pub = None
701 self.data_pub = None
698 return
702 return
699 self.data_pub = self.data_pub_class(parent=self)
703 self.data_pub = self.data_pub_class(parent=self)
700 self.configurables.append(self.data_pub)
704 self.configurables.append(self.data_pub)
701
705
702 def init_displayhook(self):
706 def init_displayhook(self):
703 # Initialize displayhook, set in/out prompts and printing system
707 # Initialize displayhook, set in/out prompts and printing system
704 self.displayhook = self.displayhook_class(
708 self.displayhook = self.displayhook_class(
705 parent=self,
709 parent=self,
706 shell=self,
710 shell=self,
707 cache_size=self.cache_size,
711 cache_size=self.cache_size,
708 )
712 )
709 self.configurables.append(self.displayhook)
713 self.configurables.append(self.displayhook)
710 # This is a context manager that installs/revmoes the displayhook at
714 # This is a context manager that installs/revmoes the displayhook at
711 # the appropriate time.
715 # the appropriate time.
712 self.display_trap = DisplayTrap(hook=self.displayhook)
716 self.display_trap = DisplayTrap(hook=self.displayhook)
713
717
714 def init_latextool(self):
718 def init_latextool(self):
715 """Configure LaTeXTool."""
719 """Configure LaTeXTool."""
716 cfg = LaTeXTool.instance(parent=self)
720 cfg = LaTeXTool.instance(parent=self)
717 if cfg not in self.configurables:
721 if cfg not in self.configurables:
718 self.configurables.append(cfg)
722 self.configurables.append(cfg)
719
723
720 def init_virtualenv(self):
724 def init_virtualenv(self):
721 """Add a virtualenv to sys.path so the user can import modules from it.
725 """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
726 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
727 virtualenv was built, and it ignores the --no-site-packages option. A
724 warning will appear suggesting the user installs IPython in the
728 warning will appear suggesting the user installs IPython in the
725 virtualenv, but for many cases, it probably works well enough.
729 virtualenv, but for many cases, it probably works well enough.
726
730
727 Adapted from code snippets online.
731 Adapted from code snippets online.
728
732
729 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
733 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
730 """
734 """
731 if 'VIRTUAL_ENV' not in os.environ:
735 if 'VIRTUAL_ENV' not in os.environ:
732 # Not in a virtualenv
736 # Not in a virtualenv
733 return
737 return
734
738
735 # venv detection:
739 # venv detection:
736 # stdlib venv may symlink sys.executable, so we can't use realpath.
740 # 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.
741 # 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)
742 # So we just check every item in the symlink tree (generally <= 3)
739 p = os.path.normcase(sys.executable)
743 p = os.path.normcase(sys.executable)
740 paths = [p]
744 paths = [p]
741 while os.path.islink(p):
745 while os.path.islink(p):
742 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
746 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
743 paths.append(p)
747 paths.append(p)
744 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
748 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
745 if any(p.startswith(p_venv) for p in paths):
749 if any(p.startswith(p_venv) for p in paths):
746 # Running properly in the virtualenv, don't need to do anything
750 # Running properly in the virtualenv, don't need to do anything
747 return
751 return
748
752
749 warn("Attempting to work in a virtualenv. If you encounter problems, please "
753 warn("Attempting to work in a virtualenv. If you encounter problems, please "
750 "install IPython inside the virtualenv.")
754 "install IPython inside the virtualenv.")
751 if sys.platform == "win32":
755 if sys.platform == "win32":
752 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
756 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
753 else:
757 else:
754 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
758 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
755 'python%d.%d' % sys.version_info[:2], 'site-packages')
759 'python%d.%d' % sys.version_info[:2], 'site-packages')
756
760
757 import site
761 import site
758 sys.path.insert(0, virtual_env)
762 sys.path.insert(0, virtual_env)
759 site.addsitedir(virtual_env)
763 site.addsitedir(virtual_env)
760
764
761 #-------------------------------------------------------------------------
765 #-------------------------------------------------------------------------
762 # Things related to injections into the sys module
766 # Things related to injections into the sys module
763 #-------------------------------------------------------------------------
767 #-------------------------------------------------------------------------
764
768
765 def save_sys_module_state(self):
769 def save_sys_module_state(self):
766 """Save the state of hooks in the sys module.
770 """Save the state of hooks in the sys module.
767
771
768 This has to be called after self.user_module is created.
772 This has to be called after self.user_module is created.
769 """
773 """
770 self._orig_sys_module_state = {}
774 self._orig_sys_module_state = {}
771 self._orig_sys_module_state['stdin'] = sys.stdin
775 self._orig_sys_module_state['stdin'] = sys.stdin
772 self._orig_sys_module_state['stdout'] = sys.stdout
776 self._orig_sys_module_state['stdout'] = sys.stdout
773 self._orig_sys_module_state['stderr'] = sys.stderr
777 self._orig_sys_module_state['stderr'] = sys.stderr
774 self._orig_sys_module_state['excepthook'] = sys.excepthook
778 self._orig_sys_module_state['excepthook'] = sys.excepthook
775 self._orig_sys_modules_main_name = self.user_module.__name__
779 self._orig_sys_modules_main_name = self.user_module.__name__
776 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
780 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
777
781
778 def restore_sys_module_state(self):
782 def restore_sys_module_state(self):
779 """Restore the state of the sys module."""
783 """Restore the state of the sys module."""
780 try:
784 try:
781 for k, v in iteritems(self._orig_sys_module_state):
785 for k, v in iteritems(self._orig_sys_module_state):
782 setattr(sys, k, v)
786 setattr(sys, k, v)
783 except AttributeError:
787 except AttributeError:
784 pass
788 pass
785 # Reset what what done in self.init_sys_modules
789 # Reset what what done in self.init_sys_modules
786 if self._orig_sys_modules_main_mod is not None:
790 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
791 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
788
792
789 #-------------------------------------------------------------------------
793 #-------------------------------------------------------------------------
790 # Things related to the banner
794 # Things related to the banner
791 #-------------------------------------------------------------------------
795 #-------------------------------------------------------------------------
792
796
793 @property
797 @property
794 def banner(self):
798 def banner(self):
795 banner = self.banner1
799 banner = self.banner1
796 if self.profile and self.profile != 'default':
800 if self.profile and self.profile != 'default':
797 banner += '\nIPython profile: %s\n' % self.profile
801 banner += '\nIPython profile: %s\n' % self.profile
798 if self.banner2:
802 if self.banner2:
799 banner += '\n' + self.banner2
803 banner += '\n' + self.banner2
800 return banner
804 return banner
801
805
802 def show_banner(self, banner=None):
806 def show_banner(self, banner=None):
803 if banner is None:
807 if banner is None:
804 banner = self.banner
808 banner = self.banner
805 self.write(banner)
809 self.write(banner)
806
810
807 #-------------------------------------------------------------------------
811 #-------------------------------------------------------------------------
808 # Things related to hooks
812 # Things related to hooks
809 #-------------------------------------------------------------------------
813 #-------------------------------------------------------------------------
810
814
811 def init_hooks(self):
815 def init_hooks(self):
812 # hooks holds pointers used for user-side customizations
816 # hooks holds pointers used for user-side customizations
813 self.hooks = Struct()
817 self.hooks = Struct()
814
818
815 self.strdispatchers = {}
819 self.strdispatchers = {}
816
820
817 # Set all default hooks, defined in the IPython.hooks module.
821 # Set all default hooks, defined in the IPython.hooks module.
818 hooks = IPython.core.hooks
822 hooks = IPython.core.hooks
819 for hook_name in hooks.__all__:
823 for hook_name in hooks.__all__:
820 # default hooks have priority 100, i.e. low; user hooks should have
824 # default hooks have priority 100, i.e. low; user hooks should have
821 # 0-100 priority
825 # 0-100 priority
822 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
826 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
823
827
828 if self.display_page:
829 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
830
824 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
831 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
825 _warn_deprecated=True):
832 _warn_deprecated=True):
826 """set_hook(name,hook) -> sets an internal IPython hook.
833 """set_hook(name,hook) -> sets an internal IPython hook.
827
834
828 IPython exposes some of its internal API as user-modifiable hooks. By
835 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
836 adding your function to one of these hooks, you can modify IPython's
830 behavior to call at runtime your own routines."""
837 behavior to call at runtime your own routines."""
831
838
832 # At some point in the future, this should validate the hook before it
839 # 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
840 # accepts it. Probably at least check that the hook takes the number
834 # of args it's supposed to.
841 # of args it's supposed to.
835
842
836 f = types.MethodType(hook,self)
843 f = types.MethodType(hook,self)
837
844
838 # check if the hook is for strdispatcher first
845 # check if the hook is for strdispatcher first
839 if str_key is not None:
846 if str_key is not None:
840 sdp = self.strdispatchers.get(name, StrDispatch())
847 sdp = self.strdispatchers.get(name, StrDispatch())
841 sdp.add_s(str_key, f, priority )
848 sdp.add_s(str_key, f, priority )
842 self.strdispatchers[name] = sdp
849 self.strdispatchers[name] = sdp
843 return
850 return
844 if re_key is not None:
851 if re_key is not None:
845 sdp = self.strdispatchers.get(name, StrDispatch())
852 sdp = self.strdispatchers.get(name, StrDispatch())
846 sdp.add_re(re.compile(re_key), f, priority )
853 sdp.add_re(re.compile(re_key), f, priority )
847 self.strdispatchers[name] = sdp
854 self.strdispatchers[name] = sdp
848 return
855 return
849
856
850 dp = getattr(self.hooks, name, None)
857 dp = getattr(self.hooks, name, None)
851 if name not in IPython.core.hooks.__all__:
858 if name not in IPython.core.hooks.__all__:
852 print("Warning! Hook '%s' is not one of %s" % \
859 print("Warning! Hook '%s' is not one of %s" % \
853 (name, IPython.core.hooks.__all__ ))
860 (name, IPython.core.hooks.__all__ ))
854
861
855 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
862 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
856 alternative = IPython.core.hooks.deprecated[name]
863 alternative = IPython.core.hooks.deprecated[name]
857 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
864 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
858
865
859 if not dp:
866 if not dp:
860 dp = IPython.core.hooks.CommandChainDispatcher()
867 dp = IPython.core.hooks.CommandChainDispatcher()
861
868
862 try:
869 try:
863 dp.add(f,priority)
870 dp.add(f,priority)
864 except AttributeError:
871 except AttributeError:
865 # it was not commandchain, plain old func - replace
872 # it was not commandchain, plain old func - replace
866 dp = f
873 dp = f
867
874
868 setattr(self.hooks,name, dp)
875 setattr(self.hooks,name, dp)
869
876
870 #-------------------------------------------------------------------------
877 #-------------------------------------------------------------------------
871 # Things related to events
878 # Things related to events
872 #-------------------------------------------------------------------------
879 #-------------------------------------------------------------------------
873
880
874 def init_events(self):
881 def init_events(self):
875 self.events = EventManager(self, available_events)
882 self.events = EventManager(self, available_events)
876
883
877 self.events.register("pre_execute", self._clear_warning_registry)
884 self.events.register("pre_execute", self._clear_warning_registry)
878
885
879 def register_post_execute(self, func):
886 def register_post_execute(self, func):
880 """DEPRECATED: Use ip.events.register('post_run_cell', func)
887 """DEPRECATED: Use ip.events.register('post_run_cell', func)
881
888
882 Register a function for calling after code execution.
889 Register a function for calling after code execution.
883 """
890 """
884 warn("ip.register_post_execute is deprecated, use "
891 warn("ip.register_post_execute is deprecated, use "
885 "ip.events.register('post_run_cell', func) instead.")
892 "ip.events.register('post_run_cell', func) instead.")
886 self.events.register('post_run_cell', func)
893 self.events.register('post_run_cell', func)
887
894
888 def _clear_warning_registry(self):
895 def _clear_warning_registry(self):
889 # clear the warning registry, so that different code blocks with
896 # clear the warning registry, so that different code blocks with
890 # overlapping line number ranges don't cause spurious suppression of
897 # overlapping line number ranges don't cause spurious suppression of
891 # warnings (see gh-6611 for details)
898 # warnings (see gh-6611 for details)
892 if "__warningregistry__" in self.user_global_ns:
899 if "__warningregistry__" in self.user_global_ns:
893 del self.user_global_ns["__warningregistry__"]
900 del self.user_global_ns["__warningregistry__"]
894
901
895 #-------------------------------------------------------------------------
902 #-------------------------------------------------------------------------
896 # Things related to the "main" module
903 # Things related to the "main" module
897 #-------------------------------------------------------------------------
904 #-------------------------------------------------------------------------
898
905
899 def new_main_mod(self, filename, modname):
906 def new_main_mod(self, filename, modname):
900 """Return a new 'main' module object for user code execution.
907 """Return a new 'main' module object for user code execution.
901
908
902 ``filename`` should be the path of the script which will be run in the
909 ``filename`` should be the path of the script which will be run in the
903 module. Requests with the same filename will get the same module, with
910 module. Requests with the same filename will get the same module, with
904 its namespace cleared.
911 its namespace cleared.
905
912
906 ``modname`` should be the module name - normally either '__main__' or
913 ``modname`` should be the module name - normally either '__main__' or
907 the basename of the file without the extension.
914 the basename of the file without the extension.
908
915
909 When scripts are executed via %run, we must keep a reference to their
916 When scripts are executed via %run, we must keep a reference to their
910 __main__ module around so that Python doesn't
917 __main__ module around so that Python doesn't
911 clear it, rendering references to module globals useless.
918 clear it, rendering references to module globals useless.
912
919
913 This method keeps said reference in a private dict, keyed by the
920 This method keeps said reference in a private dict, keyed by the
914 absolute path of the script. This way, for multiple executions of the
921 absolute path of the script. This way, for multiple executions of the
915 same script we only keep one copy of the namespace (the last one),
922 same script we only keep one copy of the namespace (the last one),
916 thus preventing memory leaks from old references while allowing the
923 thus preventing memory leaks from old references while allowing the
917 objects from the last execution to be accessible.
924 objects from the last execution to be accessible.
918 """
925 """
919 filename = os.path.abspath(filename)
926 filename = os.path.abspath(filename)
920 try:
927 try:
921 main_mod = self._main_mod_cache[filename]
928 main_mod = self._main_mod_cache[filename]
922 except KeyError:
929 except KeyError:
923 main_mod = self._main_mod_cache[filename] = types.ModuleType(
930 main_mod = self._main_mod_cache[filename] = types.ModuleType(
924 py3compat.cast_bytes_py2(modname),
931 py3compat.cast_bytes_py2(modname),
925 doc="Module created for script run in IPython")
932 doc="Module created for script run in IPython")
926 else:
933 else:
927 main_mod.__dict__.clear()
934 main_mod.__dict__.clear()
928 main_mod.__name__ = modname
935 main_mod.__name__ = modname
929
936
930 main_mod.__file__ = filename
937 main_mod.__file__ = filename
931 # It seems pydoc (and perhaps others) needs any module instance to
938 # It seems pydoc (and perhaps others) needs any module instance to
932 # implement a __nonzero__ method
939 # implement a __nonzero__ method
933 main_mod.__nonzero__ = lambda : True
940 main_mod.__nonzero__ = lambda : True
934
941
935 return main_mod
942 return main_mod
936
943
937 def clear_main_mod_cache(self):
944 def clear_main_mod_cache(self):
938 """Clear the cache of main modules.
945 """Clear the cache of main modules.
939
946
940 Mainly for use by utilities like %reset.
947 Mainly for use by utilities like %reset.
941
948
942 Examples
949 Examples
943 --------
950 --------
944
951
945 In [15]: import IPython
952 In [15]: import IPython
946
953
947 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
954 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
948
955
949 In [17]: len(_ip._main_mod_cache) > 0
956 In [17]: len(_ip._main_mod_cache) > 0
950 Out[17]: True
957 Out[17]: True
951
958
952 In [18]: _ip.clear_main_mod_cache()
959 In [18]: _ip.clear_main_mod_cache()
953
960
954 In [19]: len(_ip._main_mod_cache) == 0
961 In [19]: len(_ip._main_mod_cache) == 0
955 Out[19]: True
962 Out[19]: True
956 """
963 """
957 self._main_mod_cache.clear()
964 self._main_mod_cache.clear()
958
965
959 #-------------------------------------------------------------------------
966 #-------------------------------------------------------------------------
960 # Things related to debugging
967 # Things related to debugging
961 #-------------------------------------------------------------------------
968 #-------------------------------------------------------------------------
962
969
963 def init_pdb(self):
970 def init_pdb(self):
964 # Set calling of pdb on exceptions
971 # Set calling of pdb on exceptions
965 # self.call_pdb is a property
972 # self.call_pdb is a property
966 self.call_pdb = self.pdb
973 self.call_pdb = self.pdb
967
974
968 def _get_call_pdb(self):
975 def _get_call_pdb(self):
969 return self._call_pdb
976 return self._call_pdb
970
977
971 def _set_call_pdb(self,val):
978 def _set_call_pdb(self,val):
972
979
973 if val not in (0,1,False,True):
980 if val not in (0,1,False,True):
974 raise ValueError('new call_pdb value must be boolean')
981 raise ValueError('new call_pdb value must be boolean')
975
982
976 # store value in instance
983 # store value in instance
977 self._call_pdb = val
984 self._call_pdb = val
978
985
979 # notify the actual exception handlers
986 # notify the actual exception handlers
980 self.InteractiveTB.call_pdb = val
987 self.InteractiveTB.call_pdb = val
981
988
982 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
989 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
983 'Control auto-activation of pdb at exceptions')
990 'Control auto-activation of pdb at exceptions')
984
991
985 def debugger(self,force=False):
992 def debugger(self,force=False):
986 """Call the pydb/pdb debugger.
993 """Call the pydb/pdb debugger.
987
994
988 Keywords:
995 Keywords:
989
996
990 - force(False): by default, this routine checks the instance call_pdb
997 - force(False): by default, this routine checks the instance call_pdb
991 flag and does not actually invoke the debugger if the flag is false.
998 flag and does not actually invoke the debugger if the flag is false.
992 The 'force' option forces the debugger to activate even if the flag
999 The 'force' option forces the debugger to activate even if the flag
993 is false.
1000 is false.
994 """
1001 """
995
1002
996 if not (force or self.call_pdb):
1003 if not (force or self.call_pdb):
997 return
1004 return
998
1005
999 if not hasattr(sys,'last_traceback'):
1006 if not hasattr(sys,'last_traceback'):
1000 error('No traceback has been produced, nothing to debug.')
1007 error('No traceback has been produced, nothing to debug.')
1001 return
1008 return
1002
1009
1003 # use pydb if available
1010 # use pydb if available
1004 if debugger.has_pydb:
1011 if debugger.has_pydb:
1005 from pydb import pm
1012 from pydb import pm
1006 else:
1013 else:
1007 # fallback to our internal debugger
1014 # fallback to our internal debugger
1008 pm = lambda : self.InteractiveTB.debugger(force=True)
1015 pm = lambda : self.InteractiveTB.debugger(force=True)
1009
1016
1010 with self.readline_no_record:
1017 with self.readline_no_record:
1011 pm()
1018 pm()
1012
1019
1013 #-------------------------------------------------------------------------
1020 #-------------------------------------------------------------------------
1014 # Things related to IPython's various namespaces
1021 # Things related to IPython's various namespaces
1015 #-------------------------------------------------------------------------
1022 #-------------------------------------------------------------------------
1016 default_user_namespaces = True
1023 default_user_namespaces = True
1017
1024
1018 def init_create_namespaces(self, user_module=None, user_ns=None):
1025 def init_create_namespaces(self, user_module=None, user_ns=None):
1019 # Create the namespace where the user will operate. user_ns is
1026 # Create the namespace where the user will operate. user_ns is
1020 # normally the only one used, and it is passed to the exec calls as
1027 # normally the only one used, and it is passed to the exec calls as
1021 # the locals argument. But we do carry a user_global_ns namespace
1028 # the locals argument. But we do carry a user_global_ns namespace
1022 # given as the exec 'globals' argument, This is useful in embedding
1029 # given as the exec 'globals' argument, This is useful in embedding
1023 # situations where the ipython shell opens in a context where the
1030 # situations where the ipython shell opens in a context where the
1024 # distinction between locals and globals is meaningful. For
1031 # distinction between locals and globals is meaningful. For
1025 # non-embedded contexts, it is just the same object as the user_ns dict.
1032 # non-embedded contexts, it is just the same object as the user_ns dict.
1026
1033
1027 # FIXME. For some strange reason, __builtins__ is showing up at user
1034 # FIXME. For some strange reason, __builtins__ is showing up at user
1028 # level as a dict instead of a module. This is a manual fix, but I
1035 # level as a dict instead of a module. This is a manual fix, but I
1029 # should really track down where the problem is coming from. Alex
1036 # should really track down where the problem is coming from. Alex
1030 # Schmolck reported this problem first.
1037 # Schmolck reported this problem first.
1031
1038
1032 # A useful post by Alex Martelli on this topic:
1039 # A useful post by Alex Martelli on this topic:
1033 # Re: inconsistent value from __builtins__
1040 # Re: inconsistent value from __builtins__
1034 # Von: Alex Martelli <aleaxit@yahoo.com>
1041 # Von: Alex Martelli <aleaxit@yahoo.com>
1035 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1042 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1036 # Gruppen: comp.lang.python
1043 # Gruppen: comp.lang.python
1037
1044
1038 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1045 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1039 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1046 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1040 # > <type 'dict'>
1047 # > <type 'dict'>
1041 # > >>> print type(__builtins__)
1048 # > >>> print type(__builtins__)
1042 # > <type 'module'>
1049 # > <type 'module'>
1043 # > Is this difference in return value intentional?
1050 # > Is this difference in return value intentional?
1044
1051
1045 # Well, it's documented that '__builtins__' can be either a dictionary
1052 # Well, it's documented that '__builtins__' can be either a dictionary
1046 # or a module, and it's been that way for a long time. Whether it's
1053 # or a module, and it's been that way for a long time. Whether it's
1047 # intentional (or sensible), I don't know. In any case, the idea is
1054 # intentional (or sensible), I don't know. In any case, the idea is
1048 # that if you need to access the built-in namespace directly, you
1055 # that if you need to access the built-in namespace directly, you
1049 # should start with "import __builtin__" (note, no 's') which will
1056 # should start with "import __builtin__" (note, no 's') which will
1050 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1057 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1051
1058
1052 # These routines return a properly built module and dict as needed by
1059 # These routines return a properly built module and dict as needed by
1053 # the rest of the code, and can also be used by extension writers to
1060 # the rest of the code, and can also be used by extension writers to
1054 # generate properly initialized namespaces.
1061 # generate properly initialized namespaces.
1055 if (user_ns is not None) or (user_module is not None):
1062 if (user_ns is not None) or (user_module is not None):
1056 self.default_user_namespaces = False
1063 self.default_user_namespaces = False
1057 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1064 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1058
1065
1059 # A record of hidden variables we have added to the user namespace, so
1066 # A record of hidden variables we have added to the user namespace, so
1060 # we can list later only variables defined in actual interactive use.
1067 # we can list later only variables defined in actual interactive use.
1061 self.user_ns_hidden = {}
1068 self.user_ns_hidden = {}
1062
1069
1063 # Now that FakeModule produces a real module, we've run into a nasty
1070 # Now that FakeModule produces a real module, we've run into a nasty
1064 # problem: after script execution (via %run), the module where the user
1071 # problem: after script execution (via %run), the module where the user
1065 # code ran is deleted. Now that this object is a true module (needed
1072 # code ran is deleted. Now that this object is a true module (needed
1066 # so docetst and other tools work correctly), the Python module
1073 # so docetst and other tools work correctly), the Python module
1067 # teardown mechanism runs over it, and sets to None every variable
1074 # teardown mechanism runs over it, and sets to None every variable
1068 # present in that module. Top-level references to objects from the
1075 # present in that module. Top-level references to objects from the
1069 # script survive, because the user_ns is updated with them. However,
1076 # script survive, because the user_ns is updated with them. However,
1070 # calling functions defined in the script that use other things from
1077 # calling functions defined in the script that use other things from
1071 # the script will fail, because the function's closure had references
1078 # the script will fail, because the function's closure had references
1072 # to the original objects, which are now all None. So we must protect
1079 # to the original objects, which are now all None. So we must protect
1073 # these modules from deletion by keeping a cache.
1080 # these modules from deletion by keeping a cache.
1074 #
1081 #
1075 # To avoid keeping stale modules around (we only need the one from the
1082 # To avoid keeping stale modules around (we only need the one from the
1076 # last run), we use a dict keyed with the full path to the script, so
1083 # last run), we use a dict keyed with the full path to the script, so
1077 # only the last version of the module is held in the cache. Note,
1084 # only the last version of the module is held in the cache. Note,
1078 # however, that we must cache the module *namespace contents* (their
1085 # however, that we must cache the module *namespace contents* (their
1079 # __dict__). Because if we try to cache the actual modules, old ones
1086 # __dict__). Because if we try to cache the actual modules, old ones
1080 # (uncached) could be destroyed while still holding references (such as
1087 # (uncached) could be destroyed while still holding references (such as
1081 # those held by GUI objects that tend to be long-lived)>
1088 # those held by GUI objects that tend to be long-lived)>
1082 #
1089 #
1083 # The %reset command will flush this cache. See the cache_main_mod()
1090 # The %reset command will flush this cache. See the cache_main_mod()
1084 # and clear_main_mod_cache() methods for details on use.
1091 # and clear_main_mod_cache() methods for details on use.
1085
1092
1086 # This is the cache used for 'main' namespaces
1093 # This is the cache used for 'main' namespaces
1087 self._main_mod_cache = {}
1094 self._main_mod_cache = {}
1088
1095
1089 # A table holding all the namespaces IPython deals with, so that
1096 # A table holding all the namespaces IPython deals with, so that
1090 # introspection facilities can search easily.
1097 # introspection facilities can search easily.
1091 self.ns_table = {'user_global':self.user_module.__dict__,
1098 self.ns_table = {'user_global':self.user_module.__dict__,
1092 'user_local':self.user_ns,
1099 'user_local':self.user_ns,
1093 'builtin':builtin_mod.__dict__
1100 'builtin':builtin_mod.__dict__
1094 }
1101 }
1095
1102
1096 @property
1103 @property
1097 def user_global_ns(self):
1104 def user_global_ns(self):
1098 return self.user_module.__dict__
1105 return self.user_module.__dict__
1099
1106
1100 def prepare_user_module(self, user_module=None, user_ns=None):
1107 def prepare_user_module(self, user_module=None, user_ns=None):
1101 """Prepare the module and namespace in which user code will be run.
1108 """Prepare the module and namespace in which user code will be run.
1102
1109
1103 When IPython is started normally, both parameters are None: a new module
1110 When IPython is started normally, both parameters are None: a new module
1104 is created automatically, and its __dict__ used as the namespace.
1111 is created automatically, and its __dict__ used as the namespace.
1105
1112
1106 If only user_module is provided, its __dict__ is used as the namespace.
1113 If only user_module is provided, its __dict__ is used as the namespace.
1107 If only user_ns is provided, a dummy module is created, and user_ns
1114 If only user_ns is provided, a dummy module is created, and user_ns
1108 becomes the global namespace. If both are provided (as they may be
1115 becomes the global namespace. If both are provided (as they may be
1109 when embedding), user_ns is the local namespace, and user_module
1116 when embedding), user_ns is the local namespace, and user_module
1110 provides the global namespace.
1117 provides the global namespace.
1111
1118
1112 Parameters
1119 Parameters
1113 ----------
1120 ----------
1114 user_module : module, optional
1121 user_module : module, optional
1115 The current user module in which IPython is being run. If None,
1122 The current user module in which IPython is being run. If None,
1116 a clean module will be created.
1123 a clean module will be created.
1117 user_ns : dict, optional
1124 user_ns : dict, optional
1118 A namespace in which to run interactive commands.
1125 A namespace in which to run interactive commands.
1119
1126
1120 Returns
1127 Returns
1121 -------
1128 -------
1122 A tuple of user_module and user_ns, each properly initialised.
1129 A tuple of user_module and user_ns, each properly initialised.
1123 """
1130 """
1124 if user_module is None and user_ns is not None:
1131 if user_module is None and user_ns is not None:
1125 user_ns.setdefault("__name__", "__main__")
1132 user_ns.setdefault("__name__", "__main__")
1126 user_module = DummyMod()
1133 user_module = DummyMod()
1127 user_module.__dict__ = user_ns
1134 user_module.__dict__ = user_ns
1128
1135
1129 if user_module is None:
1136 if user_module is None:
1130 user_module = types.ModuleType("__main__",
1137 user_module = types.ModuleType("__main__",
1131 doc="Automatically created module for IPython interactive environment")
1138 doc="Automatically created module for IPython interactive environment")
1132
1139
1133 # We must ensure that __builtin__ (without the final 's') is always
1140 # We must ensure that __builtin__ (without the final 's') is always
1134 # available and pointing to the __builtin__ *module*. For more details:
1141 # available and pointing to the __builtin__ *module*. For more details:
1135 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1142 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1136 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1143 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1137 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1144 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1138
1145
1139 if user_ns is None:
1146 if user_ns is None:
1140 user_ns = user_module.__dict__
1147 user_ns = user_module.__dict__
1141
1148
1142 return user_module, user_ns
1149 return user_module, user_ns
1143
1150
1144 def init_sys_modules(self):
1151 def init_sys_modules(self):
1145 # We need to insert into sys.modules something that looks like a
1152 # We need to insert into sys.modules something that looks like a
1146 # module but which accesses the IPython namespace, for shelve and
1153 # module but which accesses the IPython namespace, for shelve and
1147 # pickle to work interactively. Normally they rely on getting
1154 # pickle to work interactively. Normally they rely on getting
1148 # everything out of __main__, but for embedding purposes each IPython
1155 # everything out of __main__, but for embedding purposes each IPython
1149 # instance has its own private namespace, so we can't go shoving
1156 # instance has its own private namespace, so we can't go shoving
1150 # everything into __main__.
1157 # everything into __main__.
1151
1158
1152 # note, however, that we should only do this for non-embedded
1159 # note, however, that we should only do this for non-embedded
1153 # ipythons, which really mimic the __main__.__dict__ with their own
1160 # ipythons, which really mimic the __main__.__dict__ with their own
1154 # namespace. Embedded instances, on the other hand, should not do
1161 # namespace. Embedded instances, on the other hand, should not do
1155 # this because they need to manage the user local/global namespaces
1162 # this because they need to manage the user local/global namespaces
1156 # only, but they live within a 'normal' __main__ (meaning, they
1163 # only, but they live within a 'normal' __main__ (meaning, they
1157 # shouldn't overtake the execution environment of the script they're
1164 # shouldn't overtake the execution environment of the script they're
1158 # embedded in).
1165 # embedded in).
1159
1166
1160 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1167 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1161 main_name = self.user_module.__name__
1168 main_name = self.user_module.__name__
1162 sys.modules[main_name] = self.user_module
1169 sys.modules[main_name] = self.user_module
1163
1170
1164 def init_user_ns(self):
1171 def init_user_ns(self):
1165 """Initialize all user-visible namespaces to their minimum defaults.
1172 """Initialize all user-visible namespaces to their minimum defaults.
1166
1173
1167 Certain history lists are also initialized here, as they effectively
1174 Certain history lists are also initialized here, as they effectively
1168 act as user namespaces.
1175 act as user namespaces.
1169
1176
1170 Notes
1177 Notes
1171 -----
1178 -----
1172 All data structures here are only filled in, they are NOT reset by this
1179 All data structures here are only filled in, they are NOT reset by this
1173 method. If they were not empty before, data will simply be added to
1180 method. If they were not empty before, data will simply be added to
1174 therm.
1181 therm.
1175 """
1182 """
1176 # This function works in two parts: first we put a few things in
1183 # This function works in two parts: first we put a few things in
1177 # user_ns, and we sync that contents into user_ns_hidden so that these
1184 # user_ns, and we sync that contents into user_ns_hidden so that these
1178 # initial variables aren't shown by %who. After the sync, we add the
1185 # initial variables aren't shown by %who. After the sync, we add the
1179 # rest of what we *do* want the user to see with %who even on a new
1186 # rest of what we *do* want the user to see with %who even on a new
1180 # session (probably nothing, so theye really only see their own stuff)
1187 # session (probably nothing, so theye really only see their own stuff)
1181
1188
1182 # The user dict must *always* have a __builtin__ reference to the
1189 # The user dict must *always* have a __builtin__ reference to the
1183 # Python standard __builtin__ namespace, which must be imported.
1190 # Python standard __builtin__ namespace, which must be imported.
1184 # This is so that certain operations in prompt evaluation can be
1191 # This is so that certain operations in prompt evaluation can be
1185 # reliably executed with builtins. Note that we can NOT use
1192 # reliably executed with builtins. Note that we can NOT use
1186 # __builtins__ (note the 's'), because that can either be a dict or a
1193 # __builtins__ (note the 's'), because that can either be a dict or a
1187 # module, and can even mutate at runtime, depending on the context
1194 # module, and can even mutate at runtime, depending on the context
1188 # (Python makes no guarantees on it). In contrast, __builtin__ is
1195 # (Python makes no guarantees on it). In contrast, __builtin__ is
1189 # always a module object, though it must be explicitly imported.
1196 # always a module object, though it must be explicitly imported.
1190
1197
1191 # For more details:
1198 # For more details:
1192 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1199 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1193 ns = dict()
1200 ns = dict()
1194
1201
1195 # make global variables for user access to the histories
1202 # make global variables for user access to the histories
1196 ns['_ih'] = self.history_manager.input_hist_parsed
1203 ns['_ih'] = self.history_manager.input_hist_parsed
1197 ns['_oh'] = self.history_manager.output_hist
1204 ns['_oh'] = self.history_manager.output_hist
1198 ns['_dh'] = self.history_manager.dir_hist
1205 ns['_dh'] = self.history_manager.dir_hist
1199
1206
1200 ns['_sh'] = shadowns
1207 ns['_sh'] = shadowns
1201
1208
1202 # user aliases to input and output histories. These shouldn't show up
1209 # user aliases to input and output histories. These shouldn't show up
1203 # in %who, as they can have very large reprs.
1210 # in %who, as they can have very large reprs.
1204 ns['In'] = self.history_manager.input_hist_parsed
1211 ns['In'] = self.history_manager.input_hist_parsed
1205 ns['Out'] = self.history_manager.output_hist
1212 ns['Out'] = self.history_manager.output_hist
1206
1213
1207 # Store myself as the public api!!!
1214 # Store myself as the public api!!!
1208 ns['get_ipython'] = self.get_ipython
1215 ns['get_ipython'] = self.get_ipython
1209
1216
1210 ns['exit'] = self.exiter
1217 ns['exit'] = self.exiter
1211 ns['quit'] = self.exiter
1218 ns['quit'] = self.exiter
1212
1219
1213 # Sync what we've added so far to user_ns_hidden so these aren't seen
1220 # Sync what we've added so far to user_ns_hidden so these aren't seen
1214 # by %who
1221 # by %who
1215 self.user_ns_hidden.update(ns)
1222 self.user_ns_hidden.update(ns)
1216
1223
1217 # Anything put into ns now would show up in %who. Think twice before
1224 # Anything put into ns now would show up in %who. Think twice before
1218 # putting anything here, as we really want %who to show the user their
1225 # putting anything here, as we really want %who to show the user their
1219 # stuff, not our variables.
1226 # stuff, not our variables.
1220
1227
1221 # Finally, update the real user's namespace
1228 # Finally, update the real user's namespace
1222 self.user_ns.update(ns)
1229 self.user_ns.update(ns)
1223
1230
1224 @property
1231 @property
1225 def all_ns_refs(self):
1232 def all_ns_refs(self):
1226 """Get a list of references to all the namespace dictionaries in which
1233 """Get a list of references to all the namespace dictionaries in which
1227 IPython might store a user-created object.
1234 IPython might store a user-created object.
1228
1235
1229 Note that this does not include the displayhook, which also caches
1236 Note that this does not include the displayhook, which also caches
1230 objects from the output."""
1237 objects from the output."""
1231 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1238 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1232 [m.__dict__ for m in self._main_mod_cache.values()]
1239 [m.__dict__ for m in self._main_mod_cache.values()]
1233
1240
1234 def reset(self, new_session=True):
1241 def reset(self, new_session=True):
1235 """Clear all internal namespaces, and attempt to release references to
1242 """Clear all internal namespaces, and attempt to release references to
1236 user objects.
1243 user objects.
1237
1244
1238 If new_session is True, a new history session will be opened.
1245 If new_session is True, a new history session will be opened.
1239 """
1246 """
1240 # Clear histories
1247 # Clear histories
1241 self.history_manager.reset(new_session)
1248 self.history_manager.reset(new_session)
1242 # Reset counter used to index all histories
1249 # Reset counter used to index all histories
1243 if new_session:
1250 if new_session:
1244 self.execution_count = 1
1251 self.execution_count = 1
1245
1252
1246 # Flush cached output items
1253 # Flush cached output items
1247 if self.displayhook.do_full_cache:
1254 if self.displayhook.do_full_cache:
1248 self.displayhook.flush()
1255 self.displayhook.flush()
1249
1256
1250 # The main execution namespaces must be cleared very carefully,
1257 # The main execution namespaces must be cleared very carefully,
1251 # skipping the deletion of the builtin-related keys, because doing so
1258 # skipping the deletion of the builtin-related keys, because doing so
1252 # would cause errors in many object's __del__ methods.
1259 # would cause errors in many object's __del__ methods.
1253 if self.user_ns is not self.user_global_ns:
1260 if self.user_ns is not self.user_global_ns:
1254 self.user_ns.clear()
1261 self.user_ns.clear()
1255 ns = self.user_global_ns
1262 ns = self.user_global_ns
1256 drop_keys = set(ns.keys())
1263 drop_keys = set(ns.keys())
1257 drop_keys.discard('__builtin__')
1264 drop_keys.discard('__builtin__')
1258 drop_keys.discard('__builtins__')
1265 drop_keys.discard('__builtins__')
1259 drop_keys.discard('__name__')
1266 drop_keys.discard('__name__')
1260 for k in drop_keys:
1267 for k in drop_keys:
1261 del ns[k]
1268 del ns[k]
1262
1269
1263 self.user_ns_hidden.clear()
1270 self.user_ns_hidden.clear()
1264
1271
1265 # Restore the user namespaces to minimal usability
1272 # Restore the user namespaces to minimal usability
1266 self.init_user_ns()
1273 self.init_user_ns()
1267
1274
1268 # Restore the default and user aliases
1275 # Restore the default and user aliases
1269 self.alias_manager.clear_aliases()
1276 self.alias_manager.clear_aliases()
1270 self.alias_manager.init_aliases()
1277 self.alias_manager.init_aliases()
1271
1278
1272 # Flush the private list of module references kept for script
1279 # Flush the private list of module references kept for script
1273 # execution protection
1280 # execution protection
1274 self.clear_main_mod_cache()
1281 self.clear_main_mod_cache()
1275
1282
1276 def del_var(self, varname, by_name=False):
1283 def del_var(self, varname, by_name=False):
1277 """Delete a variable from the various namespaces, so that, as
1284 """Delete a variable from the various namespaces, so that, as
1278 far as possible, we're not keeping any hidden references to it.
1285 far as possible, we're not keeping any hidden references to it.
1279
1286
1280 Parameters
1287 Parameters
1281 ----------
1288 ----------
1282 varname : str
1289 varname : str
1283 The name of the variable to delete.
1290 The name of the variable to delete.
1284 by_name : bool
1291 by_name : bool
1285 If True, delete variables with the given name in each
1292 If True, delete variables with the given name in each
1286 namespace. If False (default), find the variable in the user
1293 namespace. If False (default), find the variable in the user
1287 namespace, and delete references to it.
1294 namespace, and delete references to it.
1288 """
1295 """
1289 if varname in ('__builtin__', '__builtins__'):
1296 if varname in ('__builtin__', '__builtins__'):
1290 raise ValueError("Refusing to delete %s" % varname)
1297 raise ValueError("Refusing to delete %s" % varname)
1291
1298
1292 ns_refs = self.all_ns_refs
1299 ns_refs = self.all_ns_refs
1293
1300
1294 if by_name: # Delete by name
1301 if by_name: # Delete by name
1295 for ns in ns_refs:
1302 for ns in ns_refs:
1296 try:
1303 try:
1297 del ns[varname]
1304 del ns[varname]
1298 except KeyError:
1305 except KeyError:
1299 pass
1306 pass
1300 else: # Delete by object
1307 else: # Delete by object
1301 try:
1308 try:
1302 obj = self.user_ns[varname]
1309 obj = self.user_ns[varname]
1303 except KeyError:
1310 except KeyError:
1304 raise NameError("name '%s' is not defined" % varname)
1311 raise NameError("name '%s' is not defined" % varname)
1305 # Also check in output history
1312 # Also check in output history
1306 ns_refs.append(self.history_manager.output_hist)
1313 ns_refs.append(self.history_manager.output_hist)
1307 for ns in ns_refs:
1314 for ns in ns_refs:
1308 to_delete = [n for n, o in iteritems(ns) if o is obj]
1315 to_delete = [n for n, o in iteritems(ns) if o is obj]
1309 for name in to_delete:
1316 for name in to_delete:
1310 del ns[name]
1317 del ns[name]
1311
1318
1312 # displayhook keeps extra references, but not in a dictionary
1319 # displayhook keeps extra references, but not in a dictionary
1313 for name in ('_', '__', '___'):
1320 for name in ('_', '__', '___'):
1314 if getattr(self.displayhook, name) is obj:
1321 if getattr(self.displayhook, name) is obj:
1315 setattr(self.displayhook, name, None)
1322 setattr(self.displayhook, name, None)
1316
1323
1317 def reset_selective(self, regex=None):
1324 def reset_selective(self, regex=None):
1318 """Clear selective variables from internal namespaces based on a
1325 """Clear selective variables from internal namespaces based on a
1319 specified regular expression.
1326 specified regular expression.
1320
1327
1321 Parameters
1328 Parameters
1322 ----------
1329 ----------
1323 regex : string or compiled pattern, optional
1330 regex : string or compiled pattern, optional
1324 A regular expression pattern that will be used in searching
1331 A regular expression pattern that will be used in searching
1325 variable names in the users namespaces.
1332 variable names in the users namespaces.
1326 """
1333 """
1327 if regex is not None:
1334 if regex is not None:
1328 try:
1335 try:
1329 m = re.compile(regex)
1336 m = re.compile(regex)
1330 except TypeError:
1337 except TypeError:
1331 raise TypeError('regex must be a string or compiled pattern')
1338 raise TypeError('regex must be a string or compiled pattern')
1332 # Search for keys in each namespace that match the given regex
1339 # Search for keys in each namespace that match the given regex
1333 # If a match is found, delete the key/value pair.
1340 # If a match is found, delete the key/value pair.
1334 for ns in self.all_ns_refs:
1341 for ns in self.all_ns_refs:
1335 for var in ns:
1342 for var in ns:
1336 if m.search(var):
1343 if m.search(var):
1337 del ns[var]
1344 del ns[var]
1338
1345
1339 def push(self, variables, interactive=True):
1346 def push(self, variables, interactive=True):
1340 """Inject a group of variables into the IPython user namespace.
1347 """Inject a group of variables into the IPython user namespace.
1341
1348
1342 Parameters
1349 Parameters
1343 ----------
1350 ----------
1344 variables : dict, str or list/tuple of str
1351 variables : dict, str or list/tuple of str
1345 The variables to inject into the user's namespace. If a dict, a
1352 The variables to inject into the user's namespace. If a dict, a
1346 simple update is done. If a str, the string is assumed to have
1353 simple update is done. If a str, the string is assumed to have
1347 variable names separated by spaces. A list/tuple of str can also
1354 variable names separated by spaces. A list/tuple of str can also
1348 be used to give the variable names. If just the variable names are
1355 be used to give the variable names. If just the variable names are
1349 give (list/tuple/str) then the variable values looked up in the
1356 give (list/tuple/str) then the variable values looked up in the
1350 callers frame.
1357 callers frame.
1351 interactive : bool
1358 interactive : bool
1352 If True (default), the variables will be listed with the ``who``
1359 If True (default), the variables will be listed with the ``who``
1353 magic.
1360 magic.
1354 """
1361 """
1355 vdict = None
1362 vdict = None
1356
1363
1357 # We need a dict of name/value pairs to do namespace updates.
1364 # We need a dict of name/value pairs to do namespace updates.
1358 if isinstance(variables, dict):
1365 if isinstance(variables, dict):
1359 vdict = variables
1366 vdict = variables
1360 elif isinstance(variables, string_types+(list, tuple)):
1367 elif isinstance(variables, string_types+(list, tuple)):
1361 if isinstance(variables, string_types):
1368 if isinstance(variables, string_types):
1362 vlist = variables.split()
1369 vlist = variables.split()
1363 else:
1370 else:
1364 vlist = variables
1371 vlist = variables
1365 vdict = {}
1372 vdict = {}
1366 cf = sys._getframe(1)
1373 cf = sys._getframe(1)
1367 for name in vlist:
1374 for name in vlist:
1368 try:
1375 try:
1369 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1376 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1370 except:
1377 except:
1371 print('Could not get variable %s from %s' %
1378 print('Could not get variable %s from %s' %
1372 (name,cf.f_code.co_name))
1379 (name,cf.f_code.co_name))
1373 else:
1380 else:
1374 raise ValueError('variables must be a dict/str/list/tuple')
1381 raise ValueError('variables must be a dict/str/list/tuple')
1375
1382
1376 # Propagate variables to user namespace
1383 # Propagate variables to user namespace
1377 self.user_ns.update(vdict)
1384 self.user_ns.update(vdict)
1378
1385
1379 # And configure interactive visibility
1386 # And configure interactive visibility
1380 user_ns_hidden = self.user_ns_hidden
1387 user_ns_hidden = self.user_ns_hidden
1381 if interactive:
1388 if interactive:
1382 for name in vdict:
1389 for name in vdict:
1383 user_ns_hidden.pop(name, None)
1390 user_ns_hidden.pop(name, None)
1384 else:
1391 else:
1385 user_ns_hidden.update(vdict)
1392 user_ns_hidden.update(vdict)
1386
1393
1387 def drop_by_id(self, variables):
1394 def drop_by_id(self, variables):
1388 """Remove a dict of variables from the user namespace, if they are the
1395 """Remove a dict of variables from the user namespace, if they are the
1389 same as the values in the dictionary.
1396 same as the values in the dictionary.
1390
1397
1391 This is intended for use by extensions: variables that they've added can
1398 This is intended for use by extensions: variables that they've added can
1392 be taken back out if they are unloaded, without removing any that the
1399 be taken back out if they are unloaded, without removing any that the
1393 user has overwritten.
1400 user has overwritten.
1394
1401
1395 Parameters
1402 Parameters
1396 ----------
1403 ----------
1397 variables : dict
1404 variables : dict
1398 A dictionary mapping object names (as strings) to the objects.
1405 A dictionary mapping object names (as strings) to the objects.
1399 """
1406 """
1400 for name, obj in iteritems(variables):
1407 for name, obj in iteritems(variables):
1401 if name in self.user_ns and self.user_ns[name] is obj:
1408 if name in self.user_ns and self.user_ns[name] is obj:
1402 del self.user_ns[name]
1409 del self.user_ns[name]
1403 self.user_ns_hidden.pop(name, None)
1410 self.user_ns_hidden.pop(name, None)
1404
1411
1405 #-------------------------------------------------------------------------
1412 #-------------------------------------------------------------------------
1406 # Things related to object introspection
1413 # Things related to object introspection
1407 #-------------------------------------------------------------------------
1414 #-------------------------------------------------------------------------
1408
1415
1409 def _ofind(self, oname, namespaces=None):
1416 def _ofind(self, oname, namespaces=None):
1410 """Find an object in the available namespaces.
1417 """Find an object in the available namespaces.
1411
1418
1412 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1419 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1413
1420
1414 Has special code to detect magic functions.
1421 Has special code to detect magic functions.
1415 """
1422 """
1416 oname = oname.strip()
1423 oname = oname.strip()
1417 #print '1- oname: <%r>' % oname # dbg
1424 #print '1- oname: <%r>' % oname # dbg
1418 if not oname.startswith(ESC_MAGIC) and \
1425 if not oname.startswith(ESC_MAGIC) and \
1419 not oname.startswith(ESC_MAGIC2) and \
1426 not oname.startswith(ESC_MAGIC2) and \
1420 not py3compat.isidentifier(oname, dotted=True):
1427 not py3compat.isidentifier(oname, dotted=True):
1421 return dict(found=False)
1428 return dict(found=False)
1422
1429
1423 alias_ns = None
1430 alias_ns = None
1424 if namespaces is None:
1431 if namespaces is None:
1425 # Namespaces to search in:
1432 # Namespaces to search in:
1426 # Put them in a list. The order is important so that we
1433 # Put them in a list. The order is important so that we
1427 # find things in the same order that Python finds them.
1434 # find things in the same order that Python finds them.
1428 namespaces = [ ('Interactive', self.user_ns),
1435 namespaces = [ ('Interactive', self.user_ns),
1429 ('Interactive (global)', self.user_global_ns),
1436 ('Interactive (global)', self.user_global_ns),
1430 ('Python builtin', builtin_mod.__dict__),
1437 ('Python builtin', builtin_mod.__dict__),
1431 ]
1438 ]
1432
1439
1433 # initialize results to 'null'
1440 # initialize results to 'null'
1434 found = False; obj = None; ospace = None; ds = None;
1441 found = False; obj = None; ospace = None; ds = None;
1435 ismagic = False; isalias = False; parent = None
1442 ismagic = False; isalias = False; parent = None
1436
1443
1437 # We need to special-case 'print', which as of python2.6 registers as a
1444 # We need to special-case 'print', which as of python2.6 registers as a
1438 # function but should only be treated as one if print_function was
1445 # function but should only be treated as one if print_function was
1439 # loaded with a future import. In this case, just bail.
1446 # loaded with a future import. In this case, just bail.
1440 if (oname == 'print' and not py3compat.PY3 and not \
1447 if (oname == 'print' and not py3compat.PY3 and not \
1441 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1448 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1442 return {'found':found, 'obj':obj, 'namespace':ospace,
1449 return {'found':found, 'obj':obj, 'namespace':ospace,
1443 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1450 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1444
1451
1445 # Look for the given name by splitting it in parts. If the head is
1452 # Look for the given name by splitting it in parts. If the head is
1446 # found, then we look for all the remaining parts as members, and only
1453 # found, then we look for all the remaining parts as members, and only
1447 # declare success if we can find them all.
1454 # declare success if we can find them all.
1448 oname_parts = oname.split('.')
1455 oname_parts = oname.split('.')
1449 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1456 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1450 for nsname,ns in namespaces:
1457 for nsname,ns in namespaces:
1451 try:
1458 try:
1452 obj = ns[oname_head]
1459 obj = ns[oname_head]
1453 except KeyError:
1460 except KeyError:
1454 continue
1461 continue
1455 else:
1462 else:
1456 #print 'oname_rest:', oname_rest # dbg
1463 #print 'oname_rest:', oname_rest # dbg
1457 for idx, part in enumerate(oname_rest):
1464 for idx, part in enumerate(oname_rest):
1458 try:
1465 try:
1459 parent = obj
1466 parent = obj
1460 # The last part is looked up in a special way to avoid
1467 # The last part is looked up in a special way to avoid
1461 # descriptor invocation as it may raise or have side
1468 # descriptor invocation as it may raise or have side
1462 # effects.
1469 # effects.
1463 if idx == len(oname_rest) - 1:
1470 if idx == len(oname_rest) - 1:
1464 obj = self._getattr_property(obj, part)
1471 obj = self._getattr_property(obj, part)
1465 else:
1472 else:
1466 obj = getattr(obj, part)
1473 obj = getattr(obj, part)
1467 except:
1474 except:
1468 # Blanket except b/c some badly implemented objects
1475 # Blanket except b/c some badly implemented objects
1469 # allow __getattr__ to raise exceptions other than
1476 # allow __getattr__ to raise exceptions other than
1470 # AttributeError, which then crashes IPython.
1477 # AttributeError, which then crashes IPython.
1471 break
1478 break
1472 else:
1479 else:
1473 # If we finish the for loop (no break), we got all members
1480 # If we finish the for loop (no break), we got all members
1474 found = True
1481 found = True
1475 ospace = nsname
1482 ospace = nsname
1476 break # namespace loop
1483 break # namespace loop
1477
1484
1478 # Try to see if it's magic
1485 # Try to see if it's magic
1479 if not found:
1486 if not found:
1480 obj = None
1487 obj = None
1481 if oname.startswith(ESC_MAGIC2):
1488 if oname.startswith(ESC_MAGIC2):
1482 oname = oname.lstrip(ESC_MAGIC2)
1489 oname = oname.lstrip(ESC_MAGIC2)
1483 obj = self.find_cell_magic(oname)
1490 obj = self.find_cell_magic(oname)
1484 elif oname.startswith(ESC_MAGIC):
1491 elif oname.startswith(ESC_MAGIC):
1485 oname = oname.lstrip(ESC_MAGIC)
1492 oname = oname.lstrip(ESC_MAGIC)
1486 obj = self.find_line_magic(oname)
1493 obj = self.find_line_magic(oname)
1487 else:
1494 else:
1488 # search without prefix, so run? will find %run?
1495 # search without prefix, so run? will find %run?
1489 obj = self.find_line_magic(oname)
1496 obj = self.find_line_magic(oname)
1490 if obj is None:
1497 if obj is None:
1491 obj = self.find_cell_magic(oname)
1498 obj = self.find_cell_magic(oname)
1492 if obj is not None:
1499 if obj is not None:
1493 found = True
1500 found = True
1494 ospace = 'IPython internal'
1501 ospace = 'IPython internal'
1495 ismagic = True
1502 ismagic = True
1496
1503
1497 # Last try: special-case some literals like '', [], {}, etc:
1504 # Last try: special-case some literals like '', [], {}, etc:
1498 if not found and oname_head in ["''",'""','[]','{}','()']:
1505 if not found and oname_head in ["''",'""','[]','{}','()']:
1499 obj = eval(oname_head)
1506 obj = eval(oname_head)
1500 found = True
1507 found = True
1501 ospace = 'Interactive'
1508 ospace = 'Interactive'
1502
1509
1503 return {'found':found, 'obj':obj, 'namespace':ospace,
1510 return {'found':found, 'obj':obj, 'namespace':ospace,
1504 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1511 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1505
1512
1506 @staticmethod
1513 @staticmethod
1507 def _getattr_property(obj, attrname):
1514 def _getattr_property(obj, attrname):
1508 """Property-aware getattr to use in object finding.
1515 """Property-aware getattr to use in object finding.
1509
1516
1510 If attrname represents a property, return it unevaluated (in case it has
1517 If attrname represents a property, return it unevaluated (in case it has
1511 side effects or raises an error.
1518 side effects or raises an error.
1512
1519
1513 """
1520 """
1514 if not isinstance(obj, type):
1521 if not isinstance(obj, type):
1515 try:
1522 try:
1516 # `getattr(type(obj), attrname)` is not guaranteed to return
1523 # `getattr(type(obj), attrname)` is not guaranteed to return
1517 # `obj`, but does so for property:
1524 # `obj`, but does so for property:
1518 #
1525 #
1519 # property.__get__(self, None, cls) -> self
1526 # property.__get__(self, None, cls) -> self
1520 #
1527 #
1521 # The universal alternative is to traverse the mro manually
1528 # The universal alternative is to traverse the mro manually
1522 # searching for attrname in class dicts.
1529 # searching for attrname in class dicts.
1523 attr = getattr(type(obj), attrname)
1530 attr = getattr(type(obj), attrname)
1524 except AttributeError:
1531 except AttributeError:
1525 pass
1532 pass
1526 else:
1533 else:
1527 # This relies on the fact that data descriptors (with both
1534 # This relies on the fact that data descriptors (with both
1528 # __get__ & __set__ magic methods) take precedence over
1535 # __get__ & __set__ magic methods) take precedence over
1529 # instance-level attributes:
1536 # instance-level attributes:
1530 #
1537 #
1531 # class A(object):
1538 # class A(object):
1532 # @property
1539 # @property
1533 # def foobar(self): return 123
1540 # def foobar(self): return 123
1534 # a = A()
1541 # a = A()
1535 # a.__dict__['foobar'] = 345
1542 # a.__dict__['foobar'] = 345
1536 # a.foobar # == 123
1543 # a.foobar # == 123
1537 #
1544 #
1538 # So, a property may be returned right away.
1545 # So, a property may be returned right away.
1539 if isinstance(attr, property):
1546 if isinstance(attr, property):
1540 return attr
1547 return attr
1541
1548
1542 # Nothing helped, fall back.
1549 # Nothing helped, fall back.
1543 return getattr(obj, attrname)
1550 return getattr(obj, attrname)
1544
1551
1545 def _object_find(self, oname, namespaces=None):
1552 def _object_find(self, oname, namespaces=None):
1546 """Find an object and return a struct with info about it."""
1553 """Find an object and return a struct with info about it."""
1547 return Struct(self._ofind(oname, namespaces))
1554 return Struct(self._ofind(oname, namespaces))
1548
1555
1549 def _inspect(self, meth, oname, namespaces=None, **kw):
1556 def _inspect(self, meth, oname, namespaces=None, **kw):
1550 """Generic interface to the inspector system.
1557 """Generic interface to the inspector system.
1551
1558
1552 This function is meant to be called by pdef, pdoc & friends."""
1559 This function is meant to be called by pdef, pdoc & friends."""
1553 info = self._object_find(oname, namespaces)
1560 info = self._object_find(oname, namespaces)
1554 if info.found:
1561 if info.found:
1555 pmethod = getattr(self.inspector, meth)
1562 pmethod = getattr(self.inspector, meth)
1556 formatter = format_screen if info.ismagic else None
1563 formatter = format_screen if info.ismagic else None
1557 if meth == 'pdoc':
1564 if meth == 'pdoc':
1558 pmethod(info.obj, oname, formatter)
1565 pmethod(info.obj, oname, formatter)
1559 elif meth == 'pinfo':
1566 elif meth == 'pinfo':
1560 pmethod(info.obj, oname, formatter, info, **kw)
1567 pmethod(info.obj, oname, formatter, info, **kw)
1561 else:
1568 else:
1562 pmethod(info.obj, oname)
1569 pmethod(info.obj, oname)
1563 else:
1570 else:
1564 print('Object `%s` not found.' % oname)
1571 print('Object `%s` not found.' % oname)
1565 return 'not found' # so callers can take other action
1572 return 'not found' # so callers can take other action
1566
1573
1567 def object_inspect(self, oname, detail_level=0):
1574 def object_inspect(self, oname, detail_level=0):
1568 """Get object info about oname"""
1575 """Get object info about oname"""
1569 with self.builtin_trap:
1576 with self.builtin_trap:
1570 info = self._object_find(oname)
1577 info = self._object_find(oname)
1571 if info.found:
1578 if info.found:
1572 return self.inspector.info(info.obj, oname, info=info,
1579 return self.inspector.info(info.obj, oname, info=info,
1573 detail_level=detail_level
1580 detail_level=detail_level
1574 )
1581 )
1575 else:
1582 else:
1576 return oinspect.object_info(name=oname, found=False)
1583 return oinspect.object_info(name=oname, found=False)
1577
1584
1578 def object_inspect_text(self, oname, detail_level=0):
1585 def object_inspect_text(self, oname, detail_level=0):
1579 """Get object info as formatted text"""
1586 """Get object info as formatted text"""
1580 with self.builtin_trap:
1587 with self.builtin_trap:
1581 info = self._object_find(oname)
1588 info = self._object_find(oname)
1582 if info.found:
1589 if info.found:
1583 return self.inspector._format_info(info.obj, oname, info=info,
1590 return self.inspector._format_info(info.obj, oname, info=info,
1584 detail_level=detail_level
1591 detail_level=detail_level
1585 )
1592 )
1586 else:
1593 else:
1587 raise KeyError(oname)
1594 raise KeyError(oname)
1588
1595
1589 #-------------------------------------------------------------------------
1596 #-------------------------------------------------------------------------
1590 # Things related to history management
1597 # Things related to history management
1591 #-------------------------------------------------------------------------
1598 #-------------------------------------------------------------------------
1592
1599
1593 def init_history(self):
1600 def init_history(self):
1594 """Sets up the command history, and starts regular autosaves."""
1601 """Sets up the command history, and starts regular autosaves."""
1595 self.history_manager = HistoryManager(shell=self, parent=self)
1602 self.history_manager = HistoryManager(shell=self, parent=self)
1596 self.configurables.append(self.history_manager)
1603 self.configurables.append(self.history_manager)
1597
1604
1598 #-------------------------------------------------------------------------
1605 #-------------------------------------------------------------------------
1599 # Things related to exception handling and tracebacks (not debugging)
1606 # Things related to exception handling and tracebacks (not debugging)
1600 #-------------------------------------------------------------------------
1607 #-------------------------------------------------------------------------
1601
1608
1602 def init_traceback_handlers(self, custom_exceptions):
1609 def init_traceback_handlers(self, custom_exceptions):
1603 # Syntax error handler.
1610 # Syntax error handler.
1604 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1611 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1605
1612
1606 # The interactive one is initialized with an offset, meaning we always
1613 # The interactive one is initialized with an offset, meaning we always
1607 # want to remove the topmost item in the traceback, which is our own
1614 # want to remove the topmost item in the traceback, which is our own
1608 # internal code. Valid modes: ['Plain','Context','Verbose']
1615 # internal code. Valid modes: ['Plain','Context','Verbose']
1609 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1616 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1610 color_scheme='NoColor',
1617 color_scheme='NoColor',
1611 tb_offset = 1,
1618 tb_offset = 1,
1612 check_cache=check_linecache_ipython)
1619 check_cache=check_linecache_ipython)
1613
1620
1614 # The instance will store a pointer to the system-wide exception hook,
1621 # The instance will store a pointer to the system-wide exception hook,
1615 # so that runtime code (such as magics) can access it. This is because
1622 # so that runtime code (such as magics) can access it. This is because
1616 # during the read-eval loop, it may get temporarily overwritten.
1623 # during the read-eval loop, it may get temporarily overwritten.
1617 self.sys_excepthook = sys.excepthook
1624 self.sys_excepthook = sys.excepthook
1618
1625
1619 # and add any custom exception handlers the user may have specified
1626 # and add any custom exception handlers the user may have specified
1620 self.set_custom_exc(*custom_exceptions)
1627 self.set_custom_exc(*custom_exceptions)
1621
1628
1622 # Set the exception mode
1629 # Set the exception mode
1623 self.InteractiveTB.set_mode(mode=self.xmode)
1630 self.InteractiveTB.set_mode(mode=self.xmode)
1624
1631
1625 def set_custom_exc(self, exc_tuple, handler):
1632 def set_custom_exc(self, exc_tuple, handler):
1626 """set_custom_exc(exc_tuple,handler)
1633 """set_custom_exc(exc_tuple,handler)
1627
1634
1628 Set a custom exception handler, which will be called if any of the
1635 Set a custom exception handler, which will be called if any of the
1629 exceptions in exc_tuple occur in the mainloop (specifically, in the
1636 exceptions in exc_tuple occur in the mainloop (specifically, in the
1630 run_code() method).
1637 run_code() method).
1631
1638
1632 Parameters
1639 Parameters
1633 ----------
1640 ----------
1634
1641
1635 exc_tuple : tuple of exception classes
1642 exc_tuple : tuple of exception classes
1636 A *tuple* of exception classes, for which to call the defined
1643 A *tuple* of exception classes, for which to call the defined
1637 handler. It is very important that you use a tuple, and NOT A
1644 handler. It is very important that you use a tuple, and NOT A
1638 LIST here, because of the way Python's except statement works. If
1645 LIST here, because of the way Python's except statement works. If
1639 you only want to trap a single exception, use a singleton tuple::
1646 you only want to trap a single exception, use a singleton tuple::
1640
1647
1641 exc_tuple == (MyCustomException,)
1648 exc_tuple == (MyCustomException,)
1642
1649
1643 handler : callable
1650 handler : callable
1644 handler must have the following signature::
1651 handler must have the following signature::
1645
1652
1646 def my_handler(self, etype, value, tb, tb_offset=None):
1653 def my_handler(self, etype, value, tb, tb_offset=None):
1647 ...
1654 ...
1648 return structured_traceback
1655 return structured_traceback
1649
1656
1650 Your handler must return a structured traceback (a list of strings),
1657 Your handler must return a structured traceback (a list of strings),
1651 or None.
1658 or None.
1652
1659
1653 This will be made into an instance method (via types.MethodType)
1660 This will be made into an instance method (via types.MethodType)
1654 of IPython itself, and it will be called if any of the exceptions
1661 of IPython itself, and it will be called if any of the exceptions
1655 listed in the exc_tuple are caught. If the handler is None, an
1662 listed in the exc_tuple are caught. If the handler is None, an
1656 internal basic one is used, which just prints basic info.
1663 internal basic one is used, which just prints basic info.
1657
1664
1658 To protect IPython from crashes, if your handler ever raises an
1665 To protect IPython from crashes, if your handler ever raises an
1659 exception or returns an invalid result, it will be immediately
1666 exception or returns an invalid result, it will be immediately
1660 disabled.
1667 disabled.
1661
1668
1662 WARNING: by putting in your own exception handler into IPython's main
1669 WARNING: by putting in your own exception handler into IPython's main
1663 execution loop, you run a very good chance of nasty crashes. This
1670 execution loop, you run a very good chance of nasty crashes. This
1664 facility should only be used if you really know what you are doing."""
1671 facility should only be used if you really know what you are doing."""
1665
1672
1666 assert type(exc_tuple)==type(()) , \
1673 assert type(exc_tuple)==type(()) , \
1667 "The custom exceptions must be given AS A TUPLE."
1674 "The custom exceptions must be given AS A TUPLE."
1668
1675
1669 def dummy_handler(self,etype,value,tb,tb_offset=None):
1676 def dummy_handler(self,etype,value,tb,tb_offset=None):
1670 print('*** Simple custom exception handler ***')
1677 print('*** Simple custom exception handler ***')
1671 print('Exception type :',etype)
1678 print('Exception type :',etype)
1672 print('Exception value:',value)
1679 print('Exception value:',value)
1673 print('Traceback :',tb)
1680 print('Traceback :',tb)
1674 #print 'Source code :','\n'.join(self.buffer)
1681 #print 'Source code :','\n'.join(self.buffer)
1675
1682
1676 def validate_stb(stb):
1683 def validate_stb(stb):
1677 """validate structured traceback return type
1684 """validate structured traceback return type
1678
1685
1679 return type of CustomTB *should* be a list of strings, but allow
1686 return type of CustomTB *should* be a list of strings, but allow
1680 single strings or None, which are harmless.
1687 single strings or None, which are harmless.
1681
1688
1682 This function will *always* return a list of strings,
1689 This function will *always* return a list of strings,
1683 and will raise a TypeError if stb is inappropriate.
1690 and will raise a TypeError if stb is inappropriate.
1684 """
1691 """
1685 msg = "CustomTB must return list of strings, not %r" % stb
1692 msg = "CustomTB must return list of strings, not %r" % stb
1686 if stb is None:
1693 if stb is None:
1687 return []
1694 return []
1688 elif isinstance(stb, string_types):
1695 elif isinstance(stb, string_types):
1689 return [stb]
1696 return [stb]
1690 elif not isinstance(stb, list):
1697 elif not isinstance(stb, list):
1691 raise TypeError(msg)
1698 raise TypeError(msg)
1692 # it's a list
1699 # it's a list
1693 for line in stb:
1700 for line in stb:
1694 # check every element
1701 # check every element
1695 if not isinstance(line, string_types):
1702 if not isinstance(line, string_types):
1696 raise TypeError(msg)
1703 raise TypeError(msg)
1697 return stb
1704 return stb
1698
1705
1699 if handler is None:
1706 if handler is None:
1700 wrapped = dummy_handler
1707 wrapped = dummy_handler
1701 else:
1708 else:
1702 def wrapped(self,etype,value,tb,tb_offset=None):
1709 def wrapped(self,etype,value,tb,tb_offset=None):
1703 """wrap CustomTB handler, to protect IPython from user code
1710 """wrap CustomTB handler, to protect IPython from user code
1704
1711
1705 This makes it harder (but not impossible) for custom exception
1712 This makes it harder (but not impossible) for custom exception
1706 handlers to crash IPython.
1713 handlers to crash IPython.
1707 """
1714 """
1708 try:
1715 try:
1709 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1716 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1710 return validate_stb(stb)
1717 return validate_stb(stb)
1711 except:
1718 except:
1712 # clear custom handler immediately
1719 # clear custom handler immediately
1713 self.set_custom_exc((), None)
1720 self.set_custom_exc((), None)
1714 print("Custom TB Handler failed, unregistering", file=io.stderr)
1721 print("Custom TB Handler failed, unregistering", file=io.stderr)
1715 # show the exception in handler first
1722 # show the exception in handler first
1716 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1723 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1717 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1724 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1718 print("The original exception:", file=io.stdout)
1725 print("The original exception:", file=io.stdout)
1719 stb = self.InteractiveTB.structured_traceback(
1726 stb = self.InteractiveTB.structured_traceback(
1720 (etype,value,tb), tb_offset=tb_offset
1727 (etype,value,tb), tb_offset=tb_offset
1721 )
1728 )
1722 return stb
1729 return stb
1723
1730
1724 self.CustomTB = types.MethodType(wrapped,self)
1731 self.CustomTB = types.MethodType(wrapped,self)
1725 self.custom_exceptions = exc_tuple
1732 self.custom_exceptions = exc_tuple
1726
1733
1727 def excepthook(self, etype, value, tb):
1734 def excepthook(self, etype, value, tb):
1728 """One more defense for GUI apps that call sys.excepthook.
1735 """One more defense for GUI apps that call sys.excepthook.
1729
1736
1730 GUI frameworks like wxPython trap exceptions and call
1737 GUI frameworks like wxPython trap exceptions and call
1731 sys.excepthook themselves. I guess this is a feature that
1738 sys.excepthook themselves. I guess this is a feature that
1732 enables them to keep running after exceptions that would
1739 enables them to keep running after exceptions that would
1733 otherwise kill their mainloop. This is a bother for IPython
1740 otherwise kill their mainloop. This is a bother for IPython
1734 which excepts to catch all of the program exceptions with a try:
1741 which excepts to catch all of the program exceptions with a try:
1735 except: statement.
1742 except: statement.
1736
1743
1737 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1744 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1738 any app directly invokes sys.excepthook, it will look to the user like
1745 any app directly invokes sys.excepthook, it will look to the user like
1739 IPython crashed. In order to work around this, we can disable the
1746 IPython crashed. In order to work around this, we can disable the
1740 CrashHandler and replace it with this excepthook instead, which prints a
1747 CrashHandler and replace it with this excepthook instead, which prints a
1741 regular traceback using our InteractiveTB. In this fashion, apps which
1748 regular traceback using our InteractiveTB. In this fashion, apps which
1742 call sys.excepthook will generate a regular-looking exception from
1749 call sys.excepthook will generate a regular-looking exception from
1743 IPython, and the CrashHandler will only be triggered by real IPython
1750 IPython, and the CrashHandler will only be triggered by real IPython
1744 crashes.
1751 crashes.
1745
1752
1746 This hook should be used sparingly, only in places which are not likely
1753 This hook should be used sparingly, only in places which are not likely
1747 to be true IPython errors.
1754 to be true IPython errors.
1748 """
1755 """
1749 self.showtraceback((etype, value, tb), tb_offset=0)
1756 self.showtraceback((etype, value, tb), tb_offset=0)
1750
1757
1751 def _get_exc_info(self, exc_tuple=None):
1758 def _get_exc_info(self, exc_tuple=None):
1752 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1759 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1753
1760
1754 Ensures sys.last_type,value,traceback hold the exc_info we found,
1761 Ensures sys.last_type,value,traceback hold the exc_info we found,
1755 from whichever source.
1762 from whichever source.
1756
1763
1757 raises ValueError if none of these contain any information
1764 raises ValueError if none of these contain any information
1758 """
1765 """
1759 if exc_tuple is None:
1766 if exc_tuple is None:
1760 etype, value, tb = sys.exc_info()
1767 etype, value, tb = sys.exc_info()
1761 else:
1768 else:
1762 etype, value, tb = exc_tuple
1769 etype, value, tb = exc_tuple
1763
1770
1764 if etype is None:
1771 if etype is None:
1765 if hasattr(sys, 'last_type'):
1772 if hasattr(sys, 'last_type'):
1766 etype, value, tb = sys.last_type, sys.last_value, \
1773 etype, value, tb = sys.last_type, sys.last_value, \
1767 sys.last_traceback
1774 sys.last_traceback
1768
1775
1769 if etype is None:
1776 if etype is None:
1770 raise ValueError("No exception to find")
1777 raise ValueError("No exception to find")
1771
1778
1772 # Now store the exception info in sys.last_type etc.
1779 # Now store the exception info in sys.last_type etc.
1773 # WARNING: these variables are somewhat deprecated and not
1780 # WARNING: these variables are somewhat deprecated and not
1774 # necessarily safe to use in a threaded environment, but tools
1781 # necessarily safe to use in a threaded environment, but tools
1775 # like pdb depend on their existence, so let's set them. If we
1782 # like pdb depend on their existence, so let's set them. If we
1776 # find problems in the field, we'll need to revisit their use.
1783 # find problems in the field, we'll need to revisit their use.
1777 sys.last_type = etype
1784 sys.last_type = etype
1778 sys.last_value = value
1785 sys.last_value = value
1779 sys.last_traceback = tb
1786 sys.last_traceback = tb
1780
1787
1781 return etype, value, tb
1788 return etype, value, tb
1782
1789
1783 def show_usage_error(self, exc):
1790 def show_usage_error(self, exc):
1784 """Show a short message for UsageErrors
1791 """Show a short message for UsageErrors
1785
1792
1786 These are special exceptions that shouldn't show a traceback.
1793 These are special exceptions that shouldn't show a traceback.
1787 """
1794 """
1788 self.write_err("UsageError: %s" % exc)
1795 self.write_err("UsageError: %s" % exc)
1789
1796
1790 def get_exception_only(self, exc_tuple=None):
1797 def get_exception_only(self, exc_tuple=None):
1791 """
1798 """
1792 Return as a string (ending with a newline) the exception that
1799 Return as a string (ending with a newline) the exception that
1793 just occurred, without any traceback.
1800 just occurred, without any traceback.
1794 """
1801 """
1795 etype, value, tb = self._get_exc_info(exc_tuple)
1802 etype, value, tb = self._get_exc_info(exc_tuple)
1796 msg = traceback.format_exception_only(etype, value)
1803 msg = traceback.format_exception_only(etype, value)
1797 return ''.join(msg)
1804 return ''.join(msg)
1798
1805
1799 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1806 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1800 exception_only=False):
1807 exception_only=False):
1801 """Display the exception that just occurred.
1808 """Display the exception that just occurred.
1802
1809
1803 If nothing is known about the exception, this is the method which
1810 If nothing is known about the exception, this is the method which
1804 should be used throughout the code for presenting user tracebacks,
1811 should be used throughout the code for presenting user tracebacks,
1805 rather than directly invoking the InteractiveTB object.
1812 rather than directly invoking the InteractiveTB object.
1806
1813
1807 A specific showsyntaxerror() also exists, but this method can take
1814 A specific showsyntaxerror() also exists, but this method can take
1808 care of calling it if needed, so unless you are explicitly catching a
1815 care of calling it if needed, so unless you are explicitly catching a
1809 SyntaxError exception, don't try to analyze the stack manually and
1816 SyntaxError exception, don't try to analyze the stack manually and
1810 simply call this method."""
1817 simply call this method."""
1811
1818
1812 try:
1819 try:
1813 try:
1820 try:
1814 etype, value, tb = self._get_exc_info(exc_tuple)
1821 etype, value, tb = self._get_exc_info(exc_tuple)
1815 except ValueError:
1822 except ValueError:
1816 self.write_err('No traceback available to show.\n')
1823 self.write_err('No traceback available to show.\n')
1817 return
1824 return
1818
1825
1819 if issubclass(etype, SyntaxError):
1826 if issubclass(etype, SyntaxError):
1820 # Though this won't be called by syntax errors in the input
1827 # Though this won't be called by syntax errors in the input
1821 # line, there may be SyntaxError cases with imported code.
1828 # line, there may be SyntaxError cases with imported code.
1822 self.showsyntaxerror(filename)
1829 self.showsyntaxerror(filename)
1823 elif etype is UsageError:
1830 elif etype is UsageError:
1824 self.show_usage_error(value)
1831 self.show_usage_error(value)
1825 else:
1832 else:
1826 if exception_only:
1833 if exception_only:
1827 stb = ['An exception has occurred, use %tb to see '
1834 stb = ['An exception has occurred, use %tb to see '
1828 'the full traceback.\n']
1835 'the full traceback.\n']
1829 stb.extend(self.InteractiveTB.get_exception_only(etype,
1836 stb.extend(self.InteractiveTB.get_exception_only(etype,
1830 value))
1837 value))
1831 else:
1838 else:
1832 try:
1839 try:
1833 # Exception classes can customise their traceback - we
1840 # Exception classes can customise their traceback - we
1834 # use this in IPython.parallel for exceptions occurring
1841 # use this in IPython.parallel for exceptions occurring
1835 # in the engines. This should return a list of strings.
1842 # in the engines. This should return a list of strings.
1836 stb = value._render_traceback_()
1843 stb = value._render_traceback_()
1837 except Exception:
1844 except Exception:
1838 stb = self.InteractiveTB.structured_traceback(etype,
1845 stb = self.InteractiveTB.structured_traceback(etype,
1839 value, tb, tb_offset=tb_offset)
1846 value, tb, tb_offset=tb_offset)
1840
1847
1841 self._showtraceback(etype, value, stb)
1848 self._showtraceback(etype, value, stb)
1842 if self.call_pdb:
1849 if self.call_pdb:
1843 # drop into debugger
1850 # drop into debugger
1844 self.debugger(force=True)
1851 self.debugger(force=True)
1845 return
1852 return
1846
1853
1847 # Actually show the traceback
1854 # Actually show the traceback
1848 self._showtraceback(etype, value, stb)
1855 self._showtraceback(etype, value, stb)
1849
1856
1850 except KeyboardInterrupt:
1857 except KeyboardInterrupt:
1851 self.write_err('\n' + self.get_exception_only())
1858 self.write_err('\n' + self.get_exception_only())
1852
1859
1853 def _showtraceback(self, etype, evalue, stb):
1860 def _showtraceback(self, etype, evalue, stb):
1854 """Actually show a traceback.
1861 """Actually show a traceback.
1855
1862
1856 Subclasses may override this method to put the traceback on a different
1863 Subclasses may override this method to put the traceback on a different
1857 place, like a side channel.
1864 place, like a side channel.
1858 """
1865 """
1859 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1866 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1860
1867
1861 def showsyntaxerror(self, filename=None):
1868 def showsyntaxerror(self, filename=None):
1862 """Display the syntax error that just occurred.
1869 """Display the syntax error that just occurred.
1863
1870
1864 This doesn't display a stack trace because there isn't one.
1871 This doesn't display a stack trace because there isn't one.
1865
1872
1866 If a filename is given, it is stuffed in the exception instead
1873 If a filename is given, it is stuffed in the exception instead
1867 of what was there before (because Python's parser always uses
1874 of what was there before (because Python's parser always uses
1868 "<string>" when reading from a string).
1875 "<string>" when reading from a string).
1869 """
1876 """
1870 etype, value, last_traceback = self._get_exc_info()
1877 etype, value, last_traceback = self._get_exc_info()
1871
1878
1872 if filename and issubclass(etype, SyntaxError):
1879 if filename and issubclass(etype, SyntaxError):
1873 try:
1880 try:
1874 value.filename = filename
1881 value.filename = filename
1875 except:
1882 except:
1876 # Not the format we expect; leave it alone
1883 # Not the format we expect; leave it alone
1877 pass
1884 pass
1878
1885
1879 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1886 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1880 self._showtraceback(etype, value, stb)
1887 self._showtraceback(etype, value, stb)
1881
1888
1882 # This is overridden in TerminalInteractiveShell to show a message about
1889 # This is overridden in TerminalInteractiveShell to show a message about
1883 # the %paste magic.
1890 # the %paste magic.
1884 def showindentationerror(self):
1891 def showindentationerror(self):
1885 """Called by run_cell when there's an IndentationError in code entered
1892 """Called by run_cell when there's an IndentationError in code entered
1886 at the prompt.
1893 at the prompt.
1887
1894
1888 This is overridden in TerminalInteractiveShell to show a message about
1895 This is overridden in TerminalInteractiveShell to show a message about
1889 the %paste magic."""
1896 the %paste magic."""
1890 self.showsyntaxerror()
1897 self.showsyntaxerror()
1891
1898
1892 #-------------------------------------------------------------------------
1899 #-------------------------------------------------------------------------
1893 # Things related to readline
1900 # Things related to readline
1894 #-------------------------------------------------------------------------
1901 #-------------------------------------------------------------------------
1895
1902
1896 def init_readline(self):
1903 def init_readline(self):
1897 """Command history completion/saving/reloading."""
1904 """Command history completion/saving/reloading."""
1898
1905
1899 if self.readline_use:
1906 if self.readline_use:
1900 import IPython.utils.rlineimpl as readline
1907 import IPython.utils.rlineimpl as readline
1901
1908
1902 self.rl_next_input = None
1909 self.rl_next_input = None
1903 self.rl_do_indent = False
1910 self.rl_do_indent = False
1904
1911
1905 if not self.readline_use or not readline.have_readline:
1912 if not self.readline_use or not readline.have_readline:
1906 self.has_readline = False
1913 self.has_readline = False
1907 self.readline = None
1914 self.readline = None
1908 # Set a number of methods that depend on readline to be no-op
1915 # Set a number of methods that depend on readline to be no-op
1909 self.readline_no_record = no_op_context
1916 self.readline_no_record = no_op_context
1910 self.set_readline_completer = no_op
1917 self.set_readline_completer = no_op
1911 self.set_custom_completer = no_op
1918 self.set_custom_completer = no_op
1912 if self.readline_use:
1919 if self.readline_use:
1913 warn('Readline services not available or not loaded.')
1920 warn('Readline services not available or not loaded.')
1914 else:
1921 else:
1915 self.has_readline = True
1922 self.has_readline = True
1916 self.readline = readline
1923 self.readline = readline
1917 sys.modules['readline'] = readline
1924 sys.modules['readline'] = readline
1918
1925
1919 # Platform-specific configuration
1926 # Platform-specific configuration
1920 if os.name == 'nt':
1927 if os.name == 'nt':
1921 # FIXME - check with Frederick to see if we can harmonize
1928 # FIXME - check with Frederick to see if we can harmonize
1922 # naming conventions with pyreadline to avoid this
1929 # naming conventions with pyreadline to avoid this
1923 # platform-dependent check
1930 # platform-dependent check
1924 self.readline_startup_hook = readline.set_pre_input_hook
1931 self.readline_startup_hook = readline.set_pre_input_hook
1925 else:
1932 else:
1926 self.readline_startup_hook = readline.set_startup_hook
1933 self.readline_startup_hook = readline.set_startup_hook
1927
1934
1928 # Readline config order:
1935 # Readline config order:
1929 # - IPython config (default value)
1936 # - IPython config (default value)
1930 # - custom inputrc
1937 # - custom inputrc
1931 # - IPython config (user customized)
1938 # - IPython config (user customized)
1932
1939
1933 # load IPython config before inputrc if default
1940 # load IPython config before inputrc if default
1934 # skip if libedit because parse_and_bind syntax is different
1941 # skip if libedit because parse_and_bind syntax is different
1935 if not self._custom_readline_config and not readline.uses_libedit:
1942 if not self._custom_readline_config and not readline.uses_libedit:
1936 for rlcommand in self.readline_parse_and_bind:
1943 for rlcommand in self.readline_parse_and_bind:
1937 readline.parse_and_bind(rlcommand)
1944 readline.parse_and_bind(rlcommand)
1938
1945
1939 # Load user's initrc file (readline config)
1946 # Load user's initrc file (readline config)
1940 # Or if libedit is used, load editrc.
1947 # Or if libedit is used, load editrc.
1941 inputrc_name = os.environ.get('INPUTRC')
1948 inputrc_name = os.environ.get('INPUTRC')
1942 if inputrc_name is None:
1949 if inputrc_name is None:
1943 inputrc_name = '.inputrc'
1950 inputrc_name = '.inputrc'
1944 if readline.uses_libedit:
1951 if readline.uses_libedit:
1945 inputrc_name = '.editrc'
1952 inputrc_name = '.editrc'
1946 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1953 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1947 if os.path.isfile(inputrc_name):
1954 if os.path.isfile(inputrc_name):
1948 try:
1955 try:
1949 readline.read_init_file(inputrc_name)
1956 readline.read_init_file(inputrc_name)
1950 except:
1957 except:
1951 warn('Problems reading readline initialization file <%s>'
1958 warn('Problems reading readline initialization file <%s>'
1952 % inputrc_name)
1959 % inputrc_name)
1953
1960
1954 # load IPython config after inputrc if user has customized
1961 # load IPython config after inputrc if user has customized
1955 if self._custom_readline_config:
1962 if self._custom_readline_config:
1956 for rlcommand in self.readline_parse_and_bind:
1963 for rlcommand in self.readline_parse_and_bind:
1957 readline.parse_and_bind(rlcommand)
1964 readline.parse_and_bind(rlcommand)
1958
1965
1959 # Remove some chars from the delimiters list. If we encounter
1966 # Remove some chars from the delimiters list. If we encounter
1960 # unicode chars, discard them.
1967 # unicode chars, discard them.
1961 delims = readline.get_completer_delims()
1968 delims = readline.get_completer_delims()
1962 if not py3compat.PY3:
1969 if not py3compat.PY3:
1963 delims = delims.encode("ascii", "ignore")
1970 delims = delims.encode("ascii", "ignore")
1964 for d in self.readline_remove_delims:
1971 for d in self.readline_remove_delims:
1965 delims = delims.replace(d, "")
1972 delims = delims.replace(d, "")
1966 delims = delims.replace(ESC_MAGIC, '')
1973 delims = delims.replace(ESC_MAGIC, '')
1967 readline.set_completer_delims(delims)
1974 readline.set_completer_delims(delims)
1968 # Store these so we can restore them if something like rpy2 modifies
1975 # Store these so we can restore them if something like rpy2 modifies
1969 # them.
1976 # them.
1970 self.readline_delims = delims
1977 self.readline_delims = delims
1971 # otherwise we end up with a monster history after a while:
1978 # otherwise we end up with a monster history after a while:
1972 readline.set_history_length(self.history_length)
1979 readline.set_history_length(self.history_length)
1973
1980
1974 self.refill_readline_hist()
1981 self.refill_readline_hist()
1975 self.readline_no_record = ReadlineNoRecord(self)
1982 self.readline_no_record = ReadlineNoRecord(self)
1976
1983
1977 # Configure auto-indent for all platforms
1984 # Configure auto-indent for all platforms
1978 self.set_autoindent(self.autoindent)
1985 self.set_autoindent(self.autoindent)
1979
1986
1980 def refill_readline_hist(self):
1987 def refill_readline_hist(self):
1981 # Load the last 1000 lines from history
1988 # Load the last 1000 lines from history
1982 self.readline.clear_history()
1989 self.readline.clear_history()
1983 stdin_encoding = sys.stdin.encoding or "utf-8"
1990 stdin_encoding = sys.stdin.encoding or "utf-8"
1984 last_cell = u""
1991 last_cell = u""
1985 for _, _, cell in self.history_manager.get_tail(1000,
1992 for _, _, cell in self.history_manager.get_tail(1000,
1986 include_latest=True):
1993 include_latest=True):
1987 # Ignore blank lines and consecutive duplicates
1994 # Ignore blank lines and consecutive duplicates
1988 cell = cell.rstrip()
1995 cell = cell.rstrip()
1989 if cell and (cell != last_cell):
1996 if cell and (cell != last_cell):
1990 try:
1997 try:
1991 if self.multiline_history:
1998 if self.multiline_history:
1992 self.readline.add_history(py3compat.unicode_to_str(cell,
1999 self.readline.add_history(py3compat.unicode_to_str(cell,
1993 stdin_encoding))
2000 stdin_encoding))
1994 else:
2001 else:
1995 for line in cell.splitlines():
2002 for line in cell.splitlines():
1996 self.readline.add_history(py3compat.unicode_to_str(line,
2003 self.readline.add_history(py3compat.unicode_to_str(line,
1997 stdin_encoding))
2004 stdin_encoding))
1998 last_cell = cell
2005 last_cell = cell
1999
2006
2000 except TypeError:
2007 except TypeError:
2001 # The history DB can get corrupted so it returns strings
2008 # The history DB can get corrupted so it returns strings
2002 # containing null bytes, which readline objects to.
2009 # containing null bytes, which readline objects to.
2003 continue
2010 continue
2004
2011
2005 @skip_doctest
2012 @skip_doctest
2006 def set_next_input(self, s, replace=False):
2013 def set_next_input(self, s, replace=False):
2007 """ Sets the 'default' input string for the next command line.
2014 """ Sets the 'default' input string for the next command line.
2008
2015
2009 Requires readline.
2016 Requires readline.
2010
2017
2011 Example::
2018 Example::
2012
2019
2013 In [1]: _ip.set_next_input("Hello Word")
2020 In [1]: _ip.set_next_input("Hello Word")
2014 In [2]: Hello Word_ # cursor is here
2021 In [2]: Hello Word_ # cursor is here
2015 """
2022 """
2016 self.rl_next_input = py3compat.cast_bytes_py2(s)
2023 self.rl_next_input = py3compat.cast_bytes_py2(s)
2017
2024
2018 # Maybe move this to the terminal subclass?
2025 # Maybe move this to the terminal subclass?
2019 def pre_readline(self):
2026 def pre_readline(self):
2020 """readline hook to be used at the start of each line.
2027 """readline hook to be used at the start of each line.
2021
2028
2022 Currently it handles auto-indent only."""
2029 Currently it handles auto-indent only."""
2023
2030
2024 if self.rl_do_indent:
2031 if self.rl_do_indent:
2025 self.readline.insert_text(self._indent_current_str())
2032 self.readline.insert_text(self._indent_current_str())
2026 if self.rl_next_input is not None:
2033 if self.rl_next_input is not None:
2027 self.readline.insert_text(self.rl_next_input)
2034 self.readline.insert_text(self.rl_next_input)
2028 self.rl_next_input = None
2035 self.rl_next_input = None
2029
2036
2030 def _indent_current_str(self):
2037 def _indent_current_str(self):
2031 """return the current level of indentation as a string"""
2038 """return the current level of indentation as a string"""
2032 return self.input_splitter.indent_spaces * ' '
2039 return self.input_splitter.indent_spaces * ' '
2033
2040
2034 #-------------------------------------------------------------------------
2041 #-------------------------------------------------------------------------
2035 # Things related to text completion
2042 # Things related to text completion
2036 #-------------------------------------------------------------------------
2043 #-------------------------------------------------------------------------
2037
2044
2038 def init_completer(self):
2045 def init_completer(self):
2039 """Initialize the completion machinery.
2046 """Initialize the completion machinery.
2040
2047
2041 This creates completion machinery that can be used by client code,
2048 This creates completion machinery that can be used by client code,
2042 either interactively in-process (typically triggered by the readline
2049 either interactively in-process (typically triggered by the readline
2043 library), programatically (such as in test suites) or out-of-prcess
2050 library), programatically (such as in test suites) or out-of-prcess
2044 (typically over the network by remote frontends).
2051 (typically over the network by remote frontends).
2045 """
2052 """
2046 from IPython.core.completer import IPCompleter
2053 from IPython.core.completer import IPCompleter
2047 from IPython.core.completerlib import (module_completer,
2054 from IPython.core.completerlib import (module_completer,
2048 magic_run_completer, cd_completer, reset_completer)
2055 magic_run_completer, cd_completer, reset_completer)
2049
2056
2050 self.Completer = IPCompleter(shell=self,
2057 self.Completer = IPCompleter(shell=self,
2051 namespace=self.user_ns,
2058 namespace=self.user_ns,
2052 global_namespace=self.user_global_ns,
2059 global_namespace=self.user_global_ns,
2053 use_readline=self.has_readline,
2060 use_readline=self.has_readline,
2054 parent=self,
2061 parent=self,
2055 )
2062 )
2056 self.configurables.append(self.Completer)
2063 self.configurables.append(self.Completer)
2057
2064
2058 # Add custom completers to the basic ones built into IPCompleter
2065 # Add custom completers to the basic ones built into IPCompleter
2059 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2066 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2060 self.strdispatchers['complete_command'] = sdisp
2067 self.strdispatchers['complete_command'] = sdisp
2061 self.Completer.custom_completers = sdisp
2068 self.Completer.custom_completers = sdisp
2062
2069
2063 self.set_hook('complete_command', module_completer, str_key = 'import')
2070 self.set_hook('complete_command', module_completer, str_key = 'import')
2064 self.set_hook('complete_command', module_completer, str_key = 'from')
2071 self.set_hook('complete_command', module_completer, str_key = 'from')
2065 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2072 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2066 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2073 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2067 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2074 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2068
2075
2069 # Only configure readline if we truly are using readline. IPython can
2076 # Only configure readline if we truly are using readline. IPython can
2070 # do tab-completion over the network, in GUIs, etc, where readline
2077 # do tab-completion over the network, in GUIs, etc, where readline
2071 # itself may be absent
2078 # itself may be absent
2072 if self.has_readline:
2079 if self.has_readline:
2073 self.set_readline_completer()
2080 self.set_readline_completer()
2074
2081
2075 def complete(self, text, line=None, cursor_pos=None):
2082 def complete(self, text, line=None, cursor_pos=None):
2076 """Return the completed text and a list of completions.
2083 """Return the completed text and a list of completions.
2077
2084
2078 Parameters
2085 Parameters
2079 ----------
2086 ----------
2080
2087
2081 text : string
2088 text : string
2082 A string of text to be completed on. It can be given as empty and
2089 A string of text to be completed on. It can be given as empty and
2083 instead a line/position pair are given. In this case, the
2090 instead a line/position pair are given. In this case, the
2084 completer itself will split the line like readline does.
2091 completer itself will split the line like readline does.
2085
2092
2086 line : string, optional
2093 line : string, optional
2087 The complete line that text is part of.
2094 The complete line that text is part of.
2088
2095
2089 cursor_pos : int, optional
2096 cursor_pos : int, optional
2090 The position of the cursor on the input line.
2097 The position of the cursor on the input line.
2091
2098
2092 Returns
2099 Returns
2093 -------
2100 -------
2094 text : string
2101 text : string
2095 The actual text that was completed.
2102 The actual text that was completed.
2096
2103
2097 matches : list
2104 matches : list
2098 A sorted list with all possible completions.
2105 A sorted list with all possible completions.
2099
2106
2100 The optional arguments allow the completion to take more context into
2107 The optional arguments allow the completion to take more context into
2101 account, and are part of the low-level completion API.
2108 account, and are part of the low-level completion API.
2102
2109
2103 This is a wrapper around the completion mechanism, similar to what
2110 This is a wrapper around the completion mechanism, similar to what
2104 readline does at the command line when the TAB key is hit. By
2111 readline does at the command line when the TAB key is hit. By
2105 exposing it as a method, it can be used by other non-readline
2112 exposing it as a method, it can be used by other non-readline
2106 environments (such as GUIs) for text completion.
2113 environments (such as GUIs) for text completion.
2107
2114
2108 Simple usage example:
2115 Simple usage example:
2109
2116
2110 In [1]: x = 'hello'
2117 In [1]: x = 'hello'
2111
2118
2112 In [2]: _ip.complete('x.l')
2119 In [2]: _ip.complete('x.l')
2113 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2120 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2114 """
2121 """
2115
2122
2116 # Inject names into __builtin__ so we can complete on the added names.
2123 # Inject names into __builtin__ so we can complete on the added names.
2117 with self.builtin_trap:
2124 with self.builtin_trap:
2118 return self.Completer.complete(text, line, cursor_pos)
2125 return self.Completer.complete(text, line, cursor_pos)
2119
2126
2120 def set_custom_completer(self, completer, pos=0):
2127 def set_custom_completer(self, completer, pos=0):
2121 """Adds a new custom completer function.
2128 """Adds a new custom completer function.
2122
2129
2123 The position argument (defaults to 0) is the index in the completers
2130 The position argument (defaults to 0) is the index in the completers
2124 list where you want the completer to be inserted."""
2131 list where you want the completer to be inserted."""
2125
2132
2126 newcomp = types.MethodType(completer,self.Completer)
2133 newcomp = types.MethodType(completer,self.Completer)
2127 self.Completer.matchers.insert(pos,newcomp)
2134 self.Completer.matchers.insert(pos,newcomp)
2128
2135
2129 def set_readline_completer(self):
2136 def set_readline_completer(self):
2130 """Reset readline's completer to be our own."""
2137 """Reset readline's completer to be our own."""
2131 self.readline.set_completer(self.Completer.rlcomplete)
2138 self.readline.set_completer(self.Completer.rlcomplete)
2132
2139
2133 def set_completer_frame(self, frame=None):
2140 def set_completer_frame(self, frame=None):
2134 """Set the frame of the completer."""
2141 """Set the frame of the completer."""
2135 if frame:
2142 if frame:
2136 self.Completer.namespace = frame.f_locals
2143 self.Completer.namespace = frame.f_locals
2137 self.Completer.global_namespace = frame.f_globals
2144 self.Completer.global_namespace = frame.f_globals
2138 else:
2145 else:
2139 self.Completer.namespace = self.user_ns
2146 self.Completer.namespace = self.user_ns
2140 self.Completer.global_namespace = self.user_global_ns
2147 self.Completer.global_namespace = self.user_global_ns
2141
2148
2142 #-------------------------------------------------------------------------
2149 #-------------------------------------------------------------------------
2143 # Things related to magics
2150 # Things related to magics
2144 #-------------------------------------------------------------------------
2151 #-------------------------------------------------------------------------
2145
2152
2146 def init_magics(self):
2153 def init_magics(self):
2147 from IPython.core import magics as m
2154 from IPython.core import magics as m
2148 self.magics_manager = magic.MagicsManager(shell=self,
2155 self.magics_manager = magic.MagicsManager(shell=self,
2149 parent=self,
2156 parent=self,
2150 user_magics=m.UserMagics(self))
2157 user_magics=m.UserMagics(self))
2151 self.configurables.append(self.magics_manager)
2158 self.configurables.append(self.magics_manager)
2152
2159
2153 # Expose as public API from the magics manager
2160 # Expose as public API from the magics manager
2154 self.register_magics = self.magics_manager.register
2161 self.register_magics = self.magics_manager.register
2155 self.define_magic = self.magics_manager.define_magic
2162 self.define_magic = self.magics_manager.define_magic
2156
2163
2157 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2164 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2158 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2165 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2159 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2166 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2160 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2167 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2161 )
2168 )
2162
2169
2163 # Register Magic Aliases
2170 # Register Magic Aliases
2164 mman = self.magics_manager
2171 mman = self.magics_manager
2165 # FIXME: magic aliases should be defined by the Magics classes
2172 # FIXME: magic aliases should be defined by the Magics classes
2166 # or in MagicsManager, not here
2173 # or in MagicsManager, not here
2167 mman.register_alias('ed', 'edit')
2174 mman.register_alias('ed', 'edit')
2168 mman.register_alias('hist', 'history')
2175 mman.register_alias('hist', 'history')
2169 mman.register_alias('rep', 'recall')
2176 mman.register_alias('rep', 'recall')
2170 mman.register_alias('SVG', 'svg', 'cell')
2177 mman.register_alias('SVG', 'svg', 'cell')
2171 mman.register_alias('HTML', 'html', 'cell')
2178 mman.register_alias('HTML', 'html', 'cell')
2172 mman.register_alias('file', 'writefile', 'cell')
2179 mman.register_alias('file', 'writefile', 'cell')
2173
2180
2174 # FIXME: Move the color initialization to the DisplayHook, which
2181 # FIXME: Move the color initialization to the DisplayHook, which
2175 # should be split into a prompt manager and displayhook. We probably
2182 # should be split into a prompt manager and displayhook. We probably
2176 # even need a centralize colors management object.
2183 # even need a centralize colors management object.
2177 self.magic('colors %s' % self.colors)
2184 self.magic('colors %s' % self.colors)
2178
2185
2179 # Defined here so that it's included in the documentation
2186 # Defined here so that it's included in the documentation
2180 @functools.wraps(magic.MagicsManager.register_function)
2187 @functools.wraps(magic.MagicsManager.register_function)
2181 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2188 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2182 self.magics_manager.register_function(func,
2189 self.magics_manager.register_function(func,
2183 magic_kind=magic_kind, magic_name=magic_name)
2190 magic_kind=magic_kind, magic_name=magic_name)
2184
2191
2185 def run_line_magic(self, magic_name, line):
2192 def run_line_magic(self, magic_name, line):
2186 """Execute the given line magic.
2193 """Execute the given line magic.
2187
2194
2188 Parameters
2195 Parameters
2189 ----------
2196 ----------
2190 magic_name : str
2197 magic_name : str
2191 Name of the desired magic function, without '%' prefix.
2198 Name of the desired magic function, without '%' prefix.
2192
2199
2193 line : str
2200 line : str
2194 The rest of the input line as a single string.
2201 The rest of the input line as a single string.
2195 """
2202 """
2196 fn = self.find_line_magic(magic_name)
2203 fn = self.find_line_magic(magic_name)
2197 if fn is None:
2204 if fn is None:
2198 cm = self.find_cell_magic(magic_name)
2205 cm = self.find_cell_magic(magic_name)
2199 etpl = "Line magic function `%%%s` not found%s."
2206 etpl = "Line magic function `%%%s` not found%s."
2200 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2207 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2201 'did you mean that instead?)' % magic_name )
2208 'did you mean that instead?)' % magic_name )
2202 error(etpl % (magic_name, extra))
2209 error(etpl % (magic_name, extra))
2203 else:
2210 else:
2204 # Note: this is the distance in the stack to the user's frame.
2211 # Note: this is the distance in the stack to the user's frame.
2205 # This will need to be updated if the internal calling logic gets
2212 # This will need to be updated if the internal calling logic gets
2206 # refactored, or else we'll be expanding the wrong variables.
2213 # refactored, or else we'll be expanding the wrong variables.
2207 stack_depth = 2
2214 stack_depth = 2
2208 magic_arg_s = self.var_expand(line, stack_depth)
2215 magic_arg_s = self.var_expand(line, stack_depth)
2209 # Put magic args in a list so we can call with f(*a) syntax
2216 # Put magic args in a list so we can call with f(*a) syntax
2210 args = [magic_arg_s]
2217 args = [magic_arg_s]
2211 kwargs = {}
2218 kwargs = {}
2212 # Grab local namespace if we need it:
2219 # Grab local namespace if we need it:
2213 if getattr(fn, "needs_local_scope", False):
2220 if getattr(fn, "needs_local_scope", False):
2214 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2221 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2215 with self.builtin_trap:
2222 with self.builtin_trap:
2216 result = fn(*args,**kwargs)
2223 result = fn(*args,**kwargs)
2217 return result
2224 return result
2218
2225
2219 def run_cell_magic(self, magic_name, line, cell):
2226 def run_cell_magic(self, magic_name, line, cell):
2220 """Execute the given cell magic.
2227 """Execute the given cell magic.
2221
2228
2222 Parameters
2229 Parameters
2223 ----------
2230 ----------
2224 magic_name : str
2231 magic_name : str
2225 Name of the desired magic function, without '%' prefix.
2232 Name of the desired magic function, without '%' prefix.
2226
2233
2227 line : str
2234 line : str
2228 The rest of the first input line as a single string.
2235 The rest of the first input line as a single string.
2229
2236
2230 cell : str
2237 cell : str
2231 The body of the cell as a (possibly multiline) string.
2238 The body of the cell as a (possibly multiline) string.
2232 """
2239 """
2233 fn = self.find_cell_magic(magic_name)
2240 fn = self.find_cell_magic(magic_name)
2234 if fn is None:
2241 if fn is None:
2235 lm = self.find_line_magic(magic_name)
2242 lm = self.find_line_magic(magic_name)
2236 etpl = "Cell magic `%%{0}` not found{1}."
2243 etpl = "Cell magic `%%{0}` not found{1}."
2237 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2244 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2238 'did you mean that instead?)'.format(magic_name))
2245 'did you mean that instead?)'.format(magic_name))
2239 error(etpl.format(magic_name, extra))
2246 error(etpl.format(magic_name, extra))
2240 elif cell == '':
2247 elif cell == '':
2241 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2248 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2242 if self.find_line_magic(magic_name) is not None:
2249 if self.find_line_magic(magic_name) is not None:
2243 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2250 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2244 raise UsageError(message)
2251 raise UsageError(message)
2245 else:
2252 else:
2246 # Note: this is the distance in the stack to the user's frame.
2253 # Note: this is the distance in the stack to the user's frame.
2247 # This will need to be updated if the internal calling logic gets
2254 # This will need to be updated if the internal calling logic gets
2248 # refactored, or else we'll be expanding the wrong variables.
2255 # refactored, or else we'll be expanding the wrong variables.
2249 stack_depth = 2
2256 stack_depth = 2
2250 magic_arg_s = self.var_expand(line, stack_depth)
2257 magic_arg_s = self.var_expand(line, stack_depth)
2251 with self.builtin_trap:
2258 with self.builtin_trap:
2252 result = fn(magic_arg_s, cell)
2259 result = fn(magic_arg_s, cell)
2253 return result
2260 return result
2254
2261
2255 def find_line_magic(self, magic_name):
2262 def find_line_magic(self, magic_name):
2256 """Find and return a line magic by name.
2263 """Find and return a line magic by name.
2257
2264
2258 Returns None if the magic isn't found."""
2265 Returns None if the magic isn't found."""
2259 return self.magics_manager.magics['line'].get(magic_name)
2266 return self.magics_manager.magics['line'].get(magic_name)
2260
2267
2261 def find_cell_magic(self, magic_name):
2268 def find_cell_magic(self, magic_name):
2262 """Find and return a cell magic by name.
2269 """Find and return a cell magic by name.
2263
2270
2264 Returns None if the magic isn't found."""
2271 Returns None if the magic isn't found."""
2265 return self.magics_manager.magics['cell'].get(magic_name)
2272 return self.magics_manager.magics['cell'].get(magic_name)
2266
2273
2267 def find_magic(self, magic_name, magic_kind='line'):
2274 def find_magic(self, magic_name, magic_kind='line'):
2268 """Find and return a magic of the given type by name.
2275 """Find and return a magic of the given type by name.
2269
2276
2270 Returns None if the magic isn't found."""
2277 Returns None if the magic isn't found."""
2271 return self.magics_manager.magics[magic_kind].get(magic_name)
2278 return self.magics_manager.magics[magic_kind].get(magic_name)
2272
2279
2273 def magic(self, arg_s):
2280 def magic(self, arg_s):
2274 """DEPRECATED. Use run_line_magic() instead.
2281 """DEPRECATED. Use run_line_magic() instead.
2275
2282
2276 Call a magic function by name.
2283 Call a magic function by name.
2277
2284
2278 Input: a string containing the name of the magic function to call and
2285 Input: a string containing the name of the magic function to call and
2279 any additional arguments to be passed to the magic.
2286 any additional arguments to be passed to the magic.
2280
2287
2281 magic('name -opt foo bar') is equivalent to typing at the ipython
2288 magic('name -opt foo bar') is equivalent to typing at the ipython
2282 prompt:
2289 prompt:
2283
2290
2284 In[1]: %name -opt foo bar
2291 In[1]: %name -opt foo bar
2285
2292
2286 To call a magic without arguments, simply use magic('name').
2293 To call a magic without arguments, simply use magic('name').
2287
2294
2288 This provides a proper Python function to call IPython's magics in any
2295 This provides a proper Python function to call IPython's magics in any
2289 valid Python code you can type at the interpreter, including loops and
2296 valid Python code you can type at the interpreter, including loops and
2290 compound statements.
2297 compound statements.
2291 """
2298 """
2292 # TODO: should we issue a loud deprecation warning here?
2299 # TODO: should we issue a loud deprecation warning here?
2293 magic_name, _, magic_arg_s = arg_s.partition(' ')
2300 magic_name, _, magic_arg_s = arg_s.partition(' ')
2294 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2301 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2295 return self.run_line_magic(magic_name, magic_arg_s)
2302 return self.run_line_magic(magic_name, magic_arg_s)
2296
2303
2297 #-------------------------------------------------------------------------
2304 #-------------------------------------------------------------------------
2298 # Things related to macros
2305 # Things related to macros
2299 #-------------------------------------------------------------------------
2306 #-------------------------------------------------------------------------
2300
2307
2301 def define_macro(self, name, themacro):
2308 def define_macro(self, name, themacro):
2302 """Define a new macro
2309 """Define a new macro
2303
2310
2304 Parameters
2311 Parameters
2305 ----------
2312 ----------
2306 name : str
2313 name : str
2307 The name of the macro.
2314 The name of the macro.
2308 themacro : str or Macro
2315 themacro : str or Macro
2309 The action to do upon invoking the macro. If a string, a new
2316 The action to do upon invoking the macro. If a string, a new
2310 Macro object is created by passing the string to it.
2317 Macro object is created by passing the string to it.
2311 """
2318 """
2312
2319
2313 from IPython.core import macro
2320 from IPython.core import macro
2314
2321
2315 if isinstance(themacro, string_types):
2322 if isinstance(themacro, string_types):
2316 themacro = macro.Macro(themacro)
2323 themacro = macro.Macro(themacro)
2317 if not isinstance(themacro, macro.Macro):
2324 if not isinstance(themacro, macro.Macro):
2318 raise ValueError('A macro must be a string or a Macro instance.')
2325 raise ValueError('A macro must be a string or a Macro instance.')
2319 self.user_ns[name] = themacro
2326 self.user_ns[name] = themacro
2320
2327
2321 #-------------------------------------------------------------------------
2328 #-------------------------------------------------------------------------
2322 # Things related to the running of system commands
2329 # Things related to the running of system commands
2323 #-------------------------------------------------------------------------
2330 #-------------------------------------------------------------------------
2324
2331
2325 def system_piped(self, cmd):
2332 def system_piped(self, cmd):
2326 """Call the given cmd in a subprocess, piping stdout/err
2333 """Call the given cmd in a subprocess, piping stdout/err
2327
2334
2328 Parameters
2335 Parameters
2329 ----------
2336 ----------
2330 cmd : str
2337 cmd : str
2331 Command to execute (can not end in '&', as background processes are
2338 Command to execute (can not end in '&', as background processes are
2332 not supported. Should not be a command that expects input
2339 not supported. Should not be a command that expects input
2333 other than simple text.
2340 other than simple text.
2334 """
2341 """
2335 if cmd.rstrip().endswith('&'):
2342 if cmd.rstrip().endswith('&'):
2336 # this is *far* from a rigorous test
2343 # this is *far* from a rigorous test
2337 # We do not support backgrounding processes because we either use
2344 # We do not support backgrounding processes because we either use
2338 # pexpect or pipes to read from. Users can always just call
2345 # pexpect or pipes to read from. Users can always just call
2339 # os.system() or use ip.system=ip.system_raw
2346 # os.system() or use ip.system=ip.system_raw
2340 # if they really want a background process.
2347 # if they really want a background process.
2341 raise OSError("Background processes not supported.")
2348 raise OSError("Background processes not supported.")
2342
2349
2343 # we explicitly do NOT return the subprocess status code, because
2350 # we explicitly do NOT return the subprocess status code, because
2344 # a non-None value would trigger :func:`sys.displayhook` calls.
2351 # a non-None value would trigger :func:`sys.displayhook` calls.
2345 # Instead, we store the exit_code in user_ns.
2352 # Instead, we store the exit_code in user_ns.
2346 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2353 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2347
2354
2348 def system_raw(self, cmd):
2355 def system_raw(self, cmd):
2349 """Call the given cmd in a subprocess using os.system on Windows or
2356 """Call the given cmd in a subprocess using os.system on Windows or
2350 subprocess.call using the system shell on other platforms.
2357 subprocess.call using the system shell on other platforms.
2351
2358
2352 Parameters
2359 Parameters
2353 ----------
2360 ----------
2354 cmd : str
2361 cmd : str
2355 Command to execute.
2362 Command to execute.
2356 """
2363 """
2357 cmd = self.var_expand(cmd, depth=1)
2364 cmd = self.var_expand(cmd, depth=1)
2358 # protect os.system from UNC paths on Windows, which it can't handle:
2365 # protect os.system from UNC paths on Windows, which it can't handle:
2359 if sys.platform == 'win32':
2366 if sys.platform == 'win32':
2360 from IPython.utils._process_win32 import AvoidUNCPath
2367 from IPython.utils._process_win32 import AvoidUNCPath
2361 with AvoidUNCPath() as path:
2368 with AvoidUNCPath() as path:
2362 if path is not None:
2369 if path is not None:
2363 cmd = '"pushd %s &&"%s' % (path, cmd)
2370 cmd = '"pushd %s &&"%s' % (path, cmd)
2364 cmd = py3compat.unicode_to_str(cmd)
2371 cmd = py3compat.unicode_to_str(cmd)
2365 try:
2372 try:
2366 ec = os.system(cmd)
2373 ec = os.system(cmd)
2367 except KeyboardInterrupt:
2374 except KeyboardInterrupt:
2368 self.write_err('\n' + self.get_exception_only())
2375 self.write_err('\n' + self.get_exception_only())
2369 ec = -2
2376 ec = -2
2370 else:
2377 else:
2371 cmd = py3compat.unicode_to_str(cmd)
2378 cmd = py3compat.unicode_to_str(cmd)
2372 # For posix the result of the subprocess.call() below is an exit
2379 # For posix the result of the subprocess.call() below is an exit
2373 # code, which by convention is zero for success, positive for
2380 # code, which by convention is zero for success, positive for
2374 # program failure. Exit codes above 128 are reserved for signals,
2381 # program failure. Exit codes above 128 are reserved for signals,
2375 # and the formula for converting a signal to an exit code is usually
2382 # and the formula for converting a signal to an exit code is usually
2376 # signal_number+128. To more easily differentiate between exit
2383 # signal_number+128. To more easily differentiate between exit
2377 # codes and signals, ipython uses negative numbers. For instance
2384 # codes and signals, ipython uses negative numbers. For instance
2378 # since control-c is signal 2 but exit code 130, ipython's
2385 # since control-c is signal 2 but exit code 130, ipython's
2379 # _exit_code variable will read -2. Note that some shells like
2386 # _exit_code variable will read -2. Note that some shells like
2380 # csh and fish don't follow sh/bash conventions for exit codes.
2387 # csh and fish don't follow sh/bash conventions for exit codes.
2381 executable = os.environ.get('SHELL', None)
2388 executable = os.environ.get('SHELL', None)
2382 try:
2389 try:
2383 # Use env shell instead of default /bin/sh
2390 # Use env shell instead of default /bin/sh
2384 ec = subprocess.call(cmd, shell=True, executable=executable)
2391 ec = subprocess.call(cmd, shell=True, executable=executable)
2385 except KeyboardInterrupt:
2392 except KeyboardInterrupt:
2386 # intercept control-C; a long traceback is not useful here
2393 # intercept control-C; a long traceback is not useful here
2387 self.write_err('\n' + self.get_exception_only())
2394 self.write_err('\n' + self.get_exception_only())
2388 ec = 130
2395 ec = 130
2389 if ec > 128:
2396 if ec > 128:
2390 ec = -(ec - 128)
2397 ec = -(ec - 128)
2391
2398
2392 # We explicitly do NOT return the subprocess status code, because
2399 # We explicitly do NOT return the subprocess status code, because
2393 # a non-None value would trigger :func:`sys.displayhook` calls.
2400 # a non-None value would trigger :func:`sys.displayhook` calls.
2394 # Instead, we store the exit_code in user_ns. Note the semantics
2401 # Instead, we store the exit_code in user_ns. Note the semantics
2395 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2402 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2396 # but raising SystemExit(_exit_code) will give status 254!
2403 # but raising SystemExit(_exit_code) will give status 254!
2397 self.user_ns['_exit_code'] = ec
2404 self.user_ns['_exit_code'] = ec
2398
2405
2399 # use piped system by default, because it is better behaved
2406 # use piped system by default, because it is better behaved
2400 system = system_piped
2407 system = system_piped
2401
2408
2402 def getoutput(self, cmd, split=True, depth=0):
2409 def getoutput(self, cmd, split=True, depth=0):
2403 """Get output (possibly including stderr) from a subprocess.
2410 """Get output (possibly including stderr) from a subprocess.
2404
2411
2405 Parameters
2412 Parameters
2406 ----------
2413 ----------
2407 cmd : str
2414 cmd : str
2408 Command to execute (can not end in '&', as background processes are
2415 Command to execute (can not end in '&', as background processes are
2409 not supported.
2416 not supported.
2410 split : bool, optional
2417 split : bool, optional
2411 If True, split the output into an IPython SList. Otherwise, an
2418 If True, split the output into an IPython SList. Otherwise, an
2412 IPython LSString is returned. These are objects similar to normal
2419 IPython LSString is returned. These are objects similar to normal
2413 lists and strings, with a few convenience attributes for easier
2420 lists and strings, with a few convenience attributes for easier
2414 manipulation of line-based output. You can use '?' on them for
2421 manipulation of line-based output. You can use '?' on them for
2415 details.
2422 details.
2416 depth : int, optional
2423 depth : int, optional
2417 How many frames above the caller are the local variables which should
2424 How many frames above the caller are the local variables which should
2418 be expanded in the command string? The default (0) assumes that the
2425 be expanded in the command string? The default (0) assumes that the
2419 expansion variables are in the stack frame calling this function.
2426 expansion variables are in the stack frame calling this function.
2420 """
2427 """
2421 if cmd.rstrip().endswith('&'):
2428 if cmd.rstrip().endswith('&'):
2422 # this is *far* from a rigorous test
2429 # this is *far* from a rigorous test
2423 raise OSError("Background processes not supported.")
2430 raise OSError("Background processes not supported.")
2424 out = getoutput(self.var_expand(cmd, depth=depth+1))
2431 out = getoutput(self.var_expand(cmd, depth=depth+1))
2425 if split:
2432 if split:
2426 out = SList(out.splitlines())
2433 out = SList(out.splitlines())
2427 else:
2434 else:
2428 out = LSString(out)
2435 out = LSString(out)
2429 return out
2436 return out
2430
2437
2431 #-------------------------------------------------------------------------
2438 #-------------------------------------------------------------------------
2432 # Things related to aliases
2439 # Things related to aliases
2433 #-------------------------------------------------------------------------
2440 #-------------------------------------------------------------------------
2434
2441
2435 def init_alias(self):
2442 def init_alias(self):
2436 self.alias_manager = AliasManager(shell=self, parent=self)
2443 self.alias_manager = AliasManager(shell=self, parent=self)
2437 self.configurables.append(self.alias_manager)
2444 self.configurables.append(self.alias_manager)
2438
2445
2439 #-------------------------------------------------------------------------
2446 #-------------------------------------------------------------------------
2440 # Things related to extensions
2447 # Things related to extensions
2441 #-------------------------------------------------------------------------
2448 #-------------------------------------------------------------------------
2442
2449
2443 def init_extension_manager(self):
2450 def init_extension_manager(self):
2444 self.extension_manager = ExtensionManager(shell=self, parent=self)
2451 self.extension_manager = ExtensionManager(shell=self, parent=self)
2445 self.configurables.append(self.extension_manager)
2452 self.configurables.append(self.extension_manager)
2446
2453
2447 #-------------------------------------------------------------------------
2454 #-------------------------------------------------------------------------
2448 # Things related to payloads
2455 # Things related to payloads
2449 #-------------------------------------------------------------------------
2456 #-------------------------------------------------------------------------
2450
2457
2451 def init_payload(self):
2458 def init_payload(self):
2452 self.payload_manager = PayloadManager(parent=self)
2459 self.payload_manager = PayloadManager(parent=self)
2453 self.configurables.append(self.payload_manager)
2460 self.configurables.append(self.payload_manager)
2454
2461
2455 #-------------------------------------------------------------------------
2462 #-------------------------------------------------------------------------
2456 # Things related to the prefilter
2463 # Things related to the prefilter
2457 #-------------------------------------------------------------------------
2464 #-------------------------------------------------------------------------
2458
2465
2459 def init_prefilter(self):
2466 def init_prefilter(self):
2460 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2467 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2461 self.configurables.append(self.prefilter_manager)
2468 self.configurables.append(self.prefilter_manager)
2462 # Ultimately this will be refactored in the new interpreter code, but
2469 # Ultimately this will be refactored in the new interpreter code, but
2463 # for now, we should expose the main prefilter method (there's legacy
2470 # for now, we should expose the main prefilter method (there's legacy
2464 # code out there that may rely on this).
2471 # code out there that may rely on this).
2465 self.prefilter = self.prefilter_manager.prefilter_lines
2472 self.prefilter = self.prefilter_manager.prefilter_lines
2466
2473
2467 def auto_rewrite_input(self, cmd):
2474 def auto_rewrite_input(self, cmd):
2468 """Print to the screen the rewritten form of the user's command.
2475 """Print to the screen the rewritten form of the user's command.
2469
2476
2470 This shows visual feedback by rewriting input lines that cause
2477 This shows visual feedback by rewriting input lines that cause
2471 automatic calling to kick in, like::
2478 automatic calling to kick in, like::
2472
2479
2473 /f x
2480 /f x
2474
2481
2475 into::
2482 into::
2476
2483
2477 ------> f(x)
2484 ------> f(x)
2478
2485
2479 after the user's input prompt. This helps the user understand that the
2486 after the user's input prompt. This helps the user understand that the
2480 input line was transformed automatically by IPython.
2487 input line was transformed automatically by IPython.
2481 """
2488 """
2482 if not self.show_rewritten_input:
2489 if not self.show_rewritten_input:
2483 return
2490 return
2484
2491
2485 rw = self.prompt_manager.render('rewrite') + cmd
2492 rw = self.prompt_manager.render('rewrite') + cmd
2486
2493
2487 try:
2494 try:
2488 # plain ascii works better w/ pyreadline, on some machines, so
2495 # plain ascii works better w/ pyreadline, on some machines, so
2489 # we use it and only print uncolored rewrite if we have unicode
2496 # we use it and only print uncolored rewrite if we have unicode
2490 rw = str(rw)
2497 rw = str(rw)
2491 print(rw, file=io.stdout)
2498 print(rw, file=io.stdout)
2492 except UnicodeEncodeError:
2499 except UnicodeEncodeError:
2493 print("------> " + cmd)
2500 print("------> " + cmd)
2494
2501
2495 #-------------------------------------------------------------------------
2502 #-------------------------------------------------------------------------
2496 # Things related to extracting values/expressions from kernel and user_ns
2503 # Things related to extracting values/expressions from kernel and user_ns
2497 #-------------------------------------------------------------------------
2504 #-------------------------------------------------------------------------
2498
2505
2499 def _user_obj_error(self):
2506 def _user_obj_error(self):
2500 """return simple exception dict
2507 """return simple exception dict
2501
2508
2502 for use in user_expressions
2509 for use in user_expressions
2503 """
2510 """
2504
2511
2505 etype, evalue, tb = self._get_exc_info()
2512 etype, evalue, tb = self._get_exc_info()
2506 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2513 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2507
2514
2508 exc_info = {
2515 exc_info = {
2509 u'status' : 'error',
2516 u'status' : 'error',
2510 u'traceback' : stb,
2517 u'traceback' : stb,
2511 u'ename' : unicode_type(etype.__name__),
2518 u'ename' : unicode_type(etype.__name__),
2512 u'evalue' : py3compat.safe_unicode(evalue),
2519 u'evalue' : py3compat.safe_unicode(evalue),
2513 }
2520 }
2514
2521
2515 return exc_info
2522 return exc_info
2516
2523
2517 def _format_user_obj(self, obj):
2524 def _format_user_obj(self, obj):
2518 """format a user object to display dict
2525 """format a user object to display dict
2519
2526
2520 for use in user_expressions
2527 for use in user_expressions
2521 """
2528 """
2522
2529
2523 data, md = self.display_formatter.format(obj)
2530 data, md = self.display_formatter.format(obj)
2524 value = {
2531 value = {
2525 'status' : 'ok',
2532 'status' : 'ok',
2526 'data' : data,
2533 'data' : data,
2527 'metadata' : md,
2534 'metadata' : md,
2528 }
2535 }
2529 return value
2536 return value
2530
2537
2531 def user_expressions(self, expressions):
2538 def user_expressions(self, expressions):
2532 """Evaluate a dict of expressions in the user's namespace.
2539 """Evaluate a dict of expressions in the user's namespace.
2533
2540
2534 Parameters
2541 Parameters
2535 ----------
2542 ----------
2536 expressions : dict
2543 expressions : dict
2537 A dict with string keys and string values. The expression values
2544 A dict with string keys and string values. The expression values
2538 should be valid Python expressions, each of which will be evaluated
2545 should be valid Python expressions, each of which will be evaluated
2539 in the user namespace.
2546 in the user namespace.
2540
2547
2541 Returns
2548 Returns
2542 -------
2549 -------
2543 A dict, keyed like the input expressions dict, with the rich mime-typed
2550 A dict, keyed like the input expressions dict, with the rich mime-typed
2544 display_data of each value.
2551 display_data of each value.
2545 """
2552 """
2546 out = {}
2553 out = {}
2547 user_ns = self.user_ns
2554 user_ns = self.user_ns
2548 global_ns = self.user_global_ns
2555 global_ns = self.user_global_ns
2549
2556
2550 for key, expr in iteritems(expressions):
2557 for key, expr in iteritems(expressions):
2551 try:
2558 try:
2552 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2559 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2553 except:
2560 except:
2554 value = self._user_obj_error()
2561 value = self._user_obj_error()
2555 out[key] = value
2562 out[key] = value
2556 return out
2563 return out
2557
2564
2558 #-------------------------------------------------------------------------
2565 #-------------------------------------------------------------------------
2559 # Things related to the running of code
2566 # Things related to the running of code
2560 #-------------------------------------------------------------------------
2567 #-------------------------------------------------------------------------
2561
2568
2562 def ex(self, cmd):
2569 def ex(self, cmd):
2563 """Execute a normal python statement in user namespace."""
2570 """Execute a normal python statement in user namespace."""
2564 with self.builtin_trap:
2571 with self.builtin_trap:
2565 exec(cmd, self.user_global_ns, self.user_ns)
2572 exec(cmd, self.user_global_ns, self.user_ns)
2566
2573
2567 def ev(self, expr):
2574 def ev(self, expr):
2568 """Evaluate python expression expr in user namespace.
2575 """Evaluate python expression expr in user namespace.
2569
2576
2570 Returns the result of evaluation
2577 Returns the result of evaluation
2571 """
2578 """
2572 with self.builtin_trap:
2579 with self.builtin_trap:
2573 return eval(expr, self.user_global_ns, self.user_ns)
2580 return eval(expr, self.user_global_ns, self.user_ns)
2574
2581
2575 def safe_execfile(self, fname, *where, **kw):
2582 def safe_execfile(self, fname, *where, **kw):
2576 """A safe version of the builtin execfile().
2583 """A safe version of the builtin execfile().
2577
2584
2578 This version will never throw an exception, but instead print
2585 This version will never throw an exception, but instead print
2579 helpful error messages to the screen. This only works on pure
2586 helpful error messages to the screen. This only works on pure
2580 Python files with the .py extension.
2587 Python files with the .py extension.
2581
2588
2582 Parameters
2589 Parameters
2583 ----------
2590 ----------
2584 fname : string
2591 fname : string
2585 The name of the file to be executed.
2592 The name of the file to be executed.
2586 where : tuple
2593 where : tuple
2587 One or two namespaces, passed to execfile() as (globals,locals).
2594 One or two namespaces, passed to execfile() as (globals,locals).
2588 If only one is given, it is passed as both.
2595 If only one is given, it is passed as both.
2589 exit_ignore : bool (False)
2596 exit_ignore : bool (False)
2590 If True, then silence SystemExit for non-zero status (it is always
2597 If True, then silence SystemExit for non-zero status (it is always
2591 silenced for zero status, as it is so common).
2598 silenced for zero status, as it is so common).
2592 raise_exceptions : bool (False)
2599 raise_exceptions : bool (False)
2593 If True raise exceptions everywhere. Meant for testing.
2600 If True raise exceptions everywhere. Meant for testing.
2594 shell_futures : bool (False)
2601 shell_futures : bool (False)
2595 If True, the code will share future statements with the interactive
2602 If True, the code will share future statements with the interactive
2596 shell. It will both be affected by previous __future__ imports, and
2603 shell. It will both be affected by previous __future__ imports, and
2597 any __future__ imports in the code will affect the shell. If False,
2604 any __future__ imports in the code will affect the shell. If False,
2598 __future__ imports are not shared in either direction.
2605 __future__ imports are not shared in either direction.
2599
2606
2600 """
2607 """
2601 kw.setdefault('exit_ignore', False)
2608 kw.setdefault('exit_ignore', False)
2602 kw.setdefault('raise_exceptions', False)
2609 kw.setdefault('raise_exceptions', False)
2603 kw.setdefault('shell_futures', False)
2610 kw.setdefault('shell_futures', False)
2604
2611
2605 fname = os.path.abspath(os.path.expanduser(fname))
2612 fname = os.path.abspath(os.path.expanduser(fname))
2606
2613
2607 # Make sure we can open the file
2614 # Make sure we can open the file
2608 try:
2615 try:
2609 with open(fname) as thefile:
2616 with open(fname) as thefile:
2610 pass
2617 pass
2611 except:
2618 except:
2612 warn('Could not open file <%s> for safe execution.' % fname)
2619 warn('Could not open file <%s> for safe execution.' % fname)
2613 return
2620 return
2614
2621
2615 # Find things also in current directory. This is needed to mimic the
2622 # Find things also in current directory. This is needed to mimic the
2616 # behavior of running a script from the system command line, where
2623 # behavior of running a script from the system command line, where
2617 # Python inserts the script's directory into sys.path
2624 # Python inserts the script's directory into sys.path
2618 dname = os.path.dirname(fname)
2625 dname = os.path.dirname(fname)
2619
2626
2620 with prepended_to_syspath(dname):
2627 with prepended_to_syspath(dname):
2621 try:
2628 try:
2622 glob, loc = (where + (None, ))[:2]
2629 glob, loc = (where + (None, ))[:2]
2623 py3compat.execfile(
2630 py3compat.execfile(
2624 fname, glob, loc,
2631 fname, glob, loc,
2625 self.compile if kw['shell_futures'] else None)
2632 self.compile if kw['shell_futures'] else None)
2626 except SystemExit as status:
2633 except SystemExit as status:
2627 # If the call was made with 0 or None exit status (sys.exit(0)
2634 # If the call was made with 0 or None exit status (sys.exit(0)
2628 # or sys.exit() ), don't bother showing a traceback, as both of
2635 # or sys.exit() ), don't bother showing a traceback, as both of
2629 # these are considered normal by the OS:
2636 # these are considered normal by the OS:
2630 # > python -c'import sys;sys.exit(0)'; echo $?
2637 # > python -c'import sys;sys.exit(0)'; echo $?
2631 # 0
2638 # 0
2632 # > python -c'import sys;sys.exit()'; echo $?
2639 # > python -c'import sys;sys.exit()'; echo $?
2633 # 0
2640 # 0
2634 # For other exit status, we show the exception unless
2641 # For other exit status, we show the exception unless
2635 # explicitly silenced, but only in short form.
2642 # explicitly silenced, but only in short form.
2636 if kw['raise_exceptions']:
2643 if kw['raise_exceptions']:
2637 raise
2644 raise
2638 if status.code and not kw['exit_ignore']:
2645 if status.code and not kw['exit_ignore']:
2639 self.showtraceback(exception_only=True)
2646 self.showtraceback(exception_only=True)
2640 except:
2647 except:
2641 if kw['raise_exceptions']:
2648 if kw['raise_exceptions']:
2642 raise
2649 raise
2643 # tb offset is 2 because we wrap execfile
2650 # tb offset is 2 because we wrap execfile
2644 self.showtraceback(tb_offset=2)
2651 self.showtraceback(tb_offset=2)
2645
2652
2646 def safe_execfile_ipy(self, fname, shell_futures=False):
2653 def safe_execfile_ipy(self, fname, shell_futures=False):
2647 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2654 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2648
2655
2649 Parameters
2656 Parameters
2650 ----------
2657 ----------
2651 fname : str
2658 fname : str
2652 The name of the file to execute. The filename must have a
2659 The name of the file to execute. The filename must have a
2653 .ipy or .ipynb extension.
2660 .ipy or .ipynb extension.
2654 shell_futures : bool (False)
2661 shell_futures : bool (False)
2655 If True, the code will share future statements with the interactive
2662 If True, the code will share future statements with the interactive
2656 shell. It will both be affected by previous __future__ imports, and
2663 shell. It will both be affected by previous __future__ imports, and
2657 any __future__ imports in the code will affect the shell. If False,
2664 any __future__ imports in the code will affect the shell. If False,
2658 __future__ imports are not shared in either direction.
2665 __future__ imports are not shared in either direction.
2659 """
2666 """
2660 fname = os.path.abspath(os.path.expanduser(fname))
2667 fname = os.path.abspath(os.path.expanduser(fname))
2661
2668
2662 # Make sure we can open the file
2669 # Make sure we can open the file
2663 try:
2670 try:
2664 with open(fname) as thefile:
2671 with open(fname) as thefile:
2665 pass
2672 pass
2666 except:
2673 except:
2667 warn('Could not open file <%s> for safe execution.' % fname)
2674 warn('Could not open file <%s> for safe execution.' % fname)
2668 return
2675 return
2669
2676
2670 # Find things also in current directory. This is needed to mimic the
2677 # Find things also in current directory. This is needed to mimic the
2671 # behavior of running a script from the system command line, where
2678 # behavior of running a script from the system command line, where
2672 # Python inserts the script's directory into sys.path
2679 # Python inserts the script's directory into sys.path
2673 dname = os.path.dirname(fname)
2680 dname = os.path.dirname(fname)
2674
2681
2675 def get_cells():
2682 def get_cells():
2676 """generator for sequence of code blocks to run"""
2683 """generator for sequence of code blocks to run"""
2677 if fname.endswith('.ipynb'):
2684 if fname.endswith('.ipynb'):
2678 from IPython.nbformat import read
2685 from IPython.nbformat import read
2679 with io_open(fname) as f:
2686 with io_open(fname) as f:
2680 nb = read(f, as_version=4)
2687 nb = read(f, as_version=4)
2681 if not nb.cells:
2688 if not nb.cells:
2682 return
2689 return
2683 for cell in nb.cells:
2690 for cell in nb.cells:
2684 if cell.cell_type == 'code':
2691 if cell.cell_type == 'code':
2685 yield cell.source
2692 yield cell.source
2686 else:
2693 else:
2687 with open(fname) as f:
2694 with open(fname) as f:
2688 yield f.read()
2695 yield f.read()
2689
2696
2690 with prepended_to_syspath(dname):
2697 with prepended_to_syspath(dname):
2691 try:
2698 try:
2692 for cell in get_cells():
2699 for cell in get_cells():
2693 # self.run_cell currently captures all exceptions
2700 # self.run_cell currently captures all exceptions
2694 # raised in user code. It would be nice if there were
2701 # raised in user code. It would be nice if there were
2695 # versions of run_cell that did raise, so
2702 # versions of run_cell that did raise, so
2696 # we could catch the errors.
2703 # we could catch the errors.
2697 self.run_cell(cell, silent=True, shell_futures=shell_futures)
2704 self.run_cell(cell, silent=True, shell_futures=shell_futures)
2698 except:
2705 except:
2699 self.showtraceback()
2706 self.showtraceback()
2700 warn('Unknown failure executing file: <%s>' % fname)
2707 warn('Unknown failure executing file: <%s>' % fname)
2701
2708
2702 def safe_run_module(self, mod_name, where):
2709 def safe_run_module(self, mod_name, where):
2703 """A safe version of runpy.run_module().
2710 """A safe version of runpy.run_module().
2704
2711
2705 This version will never throw an exception, but instead print
2712 This version will never throw an exception, but instead print
2706 helpful error messages to the screen.
2713 helpful error messages to the screen.
2707
2714
2708 `SystemExit` exceptions with status code 0 or None are ignored.
2715 `SystemExit` exceptions with status code 0 or None are ignored.
2709
2716
2710 Parameters
2717 Parameters
2711 ----------
2718 ----------
2712 mod_name : string
2719 mod_name : string
2713 The name of the module to be executed.
2720 The name of the module to be executed.
2714 where : dict
2721 where : dict
2715 The globals namespace.
2722 The globals namespace.
2716 """
2723 """
2717 try:
2724 try:
2718 try:
2725 try:
2719 where.update(
2726 where.update(
2720 runpy.run_module(str(mod_name), run_name="__main__",
2727 runpy.run_module(str(mod_name), run_name="__main__",
2721 alter_sys=True)
2728 alter_sys=True)
2722 )
2729 )
2723 except SystemExit as status:
2730 except SystemExit as status:
2724 if status.code:
2731 if status.code:
2725 raise
2732 raise
2726 except:
2733 except:
2727 self.showtraceback()
2734 self.showtraceback()
2728 warn('Unknown failure executing module: <%s>' % mod_name)
2735 warn('Unknown failure executing module: <%s>' % mod_name)
2729
2736
2730 def _run_cached_cell_magic(self, magic_name, line):
2737 def _run_cached_cell_magic(self, magic_name, line):
2731 """Special method to call a cell magic with the data stored in self.
2738 """Special method to call a cell magic with the data stored in self.
2732 """
2739 """
2733 cell = self._current_cell_magic_body
2740 cell = self._current_cell_magic_body
2734 self._current_cell_magic_body = None
2741 self._current_cell_magic_body = None
2735 return self.run_cell_magic(magic_name, line, cell)
2742 return self.run_cell_magic(magic_name, line, cell)
2736
2743
2737 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2744 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2738 """Run a complete IPython cell.
2745 """Run a complete IPython cell.
2739
2746
2740 Parameters
2747 Parameters
2741 ----------
2748 ----------
2742 raw_cell : str
2749 raw_cell : str
2743 The code (including IPython code such as %magic functions) to run.
2750 The code (including IPython code such as %magic functions) to run.
2744 store_history : bool
2751 store_history : bool
2745 If True, the raw and translated cell will be stored in IPython's
2752 If True, the raw and translated cell will be stored in IPython's
2746 history. For user code calling back into IPython's machinery, this
2753 history. For user code calling back into IPython's machinery, this
2747 should be set to False.
2754 should be set to False.
2748 silent : bool
2755 silent : bool
2749 If True, avoid side-effects, such as implicit displayhooks and
2756 If True, avoid side-effects, such as implicit displayhooks and
2750 and logging. silent=True forces store_history=False.
2757 and logging. silent=True forces store_history=False.
2751 shell_futures : bool
2758 shell_futures : bool
2752 If True, the code will share future statements with the interactive
2759 If True, the code will share future statements with the interactive
2753 shell. It will both be affected by previous __future__ imports, and
2760 shell. It will both be affected by previous __future__ imports, and
2754 any __future__ imports in the code will affect the shell. If False,
2761 any __future__ imports in the code will affect the shell. If False,
2755 __future__ imports are not shared in either direction.
2762 __future__ imports are not shared in either direction.
2756 """
2763 """
2757 if (not raw_cell) or raw_cell.isspace():
2764 if (not raw_cell) or raw_cell.isspace():
2758 return
2765 return
2759
2766
2760 if silent:
2767 if silent:
2761 store_history = False
2768 store_history = False
2762
2769
2763 self.events.trigger('pre_execute')
2770 self.events.trigger('pre_execute')
2764 if not silent:
2771 if not silent:
2765 self.events.trigger('pre_run_cell')
2772 self.events.trigger('pre_run_cell')
2766
2773
2767 # If any of our input transformation (input_transformer_manager or
2774 # If any of our input transformation (input_transformer_manager or
2768 # prefilter_manager) raises an exception, we store it in this variable
2775 # prefilter_manager) raises an exception, we store it in this variable
2769 # so that we can display the error after logging the input and storing
2776 # so that we can display the error after logging the input and storing
2770 # it in the history.
2777 # it in the history.
2771 preprocessing_exc_tuple = None
2778 preprocessing_exc_tuple = None
2772 try:
2779 try:
2773 # Static input transformations
2780 # Static input transformations
2774 cell = self.input_transformer_manager.transform_cell(raw_cell)
2781 cell = self.input_transformer_manager.transform_cell(raw_cell)
2775 except SyntaxError:
2782 except SyntaxError:
2776 preprocessing_exc_tuple = sys.exc_info()
2783 preprocessing_exc_tuple = sys.exc_info()
2777 cell = raw_cell # cell has to exist so it can be stored/logged
2784 cell = raw_cell # cell has to exist so it can be stored/logged
2778 else:
2785 else:
2779 if len(cell.splitlines()) == 1:
2786 if len(cell.splitlines()) == 1:
2780 # Dynamic transformations - only applied for single line commands
2787 # Dynamic transformations - only applied for single line commands
2781 with self.builtin_trap:
2788 with self.builtin_trap:
2782 try:
2789 try:
2783 # use prefilter_lines to handle trailing newlines
2790 # use prefilter_lines to handle trailing newlines
2784 # restore trailing newline for ast.parse
2791 # restore trailing newline for ast.parse
2785 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2792 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2786 except Exception:
2793 except Exception:
2787 # don't allow prefilter errors to crash IPython
2794 # don't allow prefilter errors to crash IPython
2788 preprocessing_exc_tuple = sys.exc_info()
2795 preprocessing_exc_tuple = sys.exc_info()
2789
2796
2790 # Store raw and processed history
2797 # Store raw and processed history
2791 if store_history:
2798 if store_history:
2792 self.history_manager.store_inputs(self.execution_count,
2799 self.history_manager.store_inputs(self.execution_count,
2793 cell, raw_cell)
2800 cell, raw_cell)
2794 if not silent:
2801 if not silent:
2795 self.logger.log(cell, raw_cell)
2802 self.logger.log(cell, raw_cell)
2796
2803
2797 # Display the exception if input processing failed.
2804 # Display the exception if input processing failed.
2798 if preprocessing_exc_tuple is not None:
2805 if preprocessing_exc_tuple is not None:
2799 self.showtraceback(preprocessing_exc_tuple)
2806 self.showtraceback(preprocessing_exc_tuple)
2800 if store_history:
2807 if store_history:
2801 self.execution_count += 1
2808 self.execution_count += 1
2802 return
2809 return
2803
2810
2804 # Our own compiler remembers the __future__ environment. If we want to
2811 # Our own compiler remembers the __future__ environment. If we want to
2805 # run code with a separate __future__ environment, use the default
2812 # run code with a separate __future__ environment, use the default
2806 # compiler
2813 # compiler
2807 compiler = self.compile if shell_futures else CachingCompiler()
2814 compiler = self.compile if shell_futures else CachingCompiler()
2808
2815
2809 with self.builtin_trap:
2816 with self.builtin_trap:
2810 cell_name = self.compile.cache(cell, self.execution_count)
2817 cell_name = self.compile.cache(cell, self.execution_count)
2811
2818
2812 with self.display_trap:
2819 with self.display_trap:
2813 # Compile to bytecode
2820 # Compile to bytecode
2814 try:
2821 try:
2815 code_ast = compiler.ast_parse(cell, filename=cell_name)
2822 code_ast = compiler.ast_parse(cell, filename=cell_name)
2816 except IndentationError:
2823 except IndentationError:
2817 self.showindentationerror()
2824 self.showindentationerror()
2818 if store_history:
2825 if store_history:
2819 self.execution_count += 1
2826 self.execution_count += 1
2820 return None
2827 return None
2821 except (OverflowError, SyntaxError, ValueError, TypeError,
2828 except (OverflowError, SyntaxError, ValueError, TypeError,
2822 MemoryError):
2829 MemoryError):
2823 self.showsyntaxerror()
2830 self.showsyntaxerror()
2824 if store_history:
2831 if store_history:
2825 self.execution_count += 1
2832 self.execution_count += 1
2826 return None
2833 return None
2827
2834
2828 # Apply AST transformations
2835 # Apply AST transformations
2829 try:
2836 try:
2830 code_ast = self.transform_ast(code_ast)
2837 code_ast = self.transform_ast(code_ast)
2831 except InputRejected:
2838 except InputRejected:
2832 self.showtraceback()
2839 self.showtraceback()
2833 if store_history:
2840 if store_history:
2834 self.execution_count += 1
2841 self.execution_count += 1
2835 return None
2842 return None
2836
2843
2837 # Execute the user code
2844 # Execute the user code
2838 interactivity = "none" if silent else self.ast_node_interactivity
2845 interactivity = "none" if silent else self.ast_node_interactivity
2839 self.run_ast_nodes(code_ast.body, cell_name,
2846 self.run_ast_nodes(code_ast.body, cell_name,
2840 interactivity=interactivity, compiler=compiler)
2847 interactivity=interactivity, compiler=compiler)
2841
2848
2842 self.events.trigger('post_execute')
2849 self.events.trigger('post_execute')
2843 if not silent:
2850 if not silent:
2844 self.events.trigger('post_run_cell')
2851 self.events.trigger('post_run_cell')
2845
2852
2846 if store_history:
2853 if store_history:
2847 # Write output to the database. Does nothing unless
2854 # Write output to the database. Does nothing unless
2848 # history output logging is enabled.
2855 # history output logging is enabled.
2849 self.history_manager.store_output(self.execution_count)
2856 self.history_manager.store_output(self.execution_count)
2850 # Each cell is a *single* input, regardless of how many lines it has
2857 # Each cell is a *single* input, regardless of how many lines it has
2851 self.execution_count += 1
2858 self.execution_count += 1
2852
2859
2853 def transform_ast(self, node):
2860 def transform_ast(self, node):
2854 """Apply the AST transformations from self.ast_transformers
2861 """Apply the AST transformations from self.ast_transformers
2855
2862
2856 Parameters
2863 Parameters
2857 ----------
2864 ----------
2858 node : ast.Node
2865 node : ast.Node
2859 The root node to be transformed. Typically called with the ast.Module
2866 The root node to be transformed. Typically called with the ast.Module
2860 produced by parsing user input.
2867 produced by parsing user input.
2861
2868
2862 Returns
2869 Returns
2863 -------
2870 -------
2864 An ast.Node corresponding to the node it was called with. Note that it
2871 An ast.Node corresponding to the node it was called with. Note that it
2865 may also modify the passed object, so don't rely on references to the
2872 may also modify the passed object, so don't rely on references to the
2866 original AST.
2873 original AST.
2867 """
2874 """
2868 for transformer in self.ast_transformers:
2875 for transformer in self.ast_transformers:
2869 try:
2876 try:
2870 node = transformer.visit(node)
2877 node = transformer.visit(node)
2871 except InputRejected:
2878 except InputRejected:
2872 # User-supplied AST transformers can reject an input by raising
2879 # User-supplied AST transformers can reject an input by raising
2873 # an InputRejected. Short-circuit in this case so that we
2880 # an InputRejected. Short-circuit in this case so that we
2874 # don't unregister the transform.
2881 # don't unregister the transform.
2875 raise
2882 raise
2876 except Exception:
2883 except Exception:
2877 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2884 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2878 self.ast_transformers.remove(transformer)
2885 self.ast_transformers.remove(transformer)
2879
2886
2880 if self.ast_transformers:
2887 if self.ast_transformers:
2881 ast.fix_missing_locations(node)
2888 ast.fix_missing_locations(node)
2882 return node
2889 return node
2883
2890
2884
2891
2885 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2892 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2886 compiler=compile):
2893 compiler=compile):
2887 """Run a sequence of AST nodes. The execution mode depends on the
2894 """Run a sequence of AST nodes. The execution mode depends on the
2888 interactivity parameter.
2895 interactivity parameter.
2889
2896
2890 Parameters
2897 Parameters
2891 ----------
2898 ----------
2892 nodelist : list
2899 nodelist : list
2893 A sequence of AST nodes to run.
2900 A sequence of AST nodes to run.
2894 cell_name : str
2901 cell_name : str
2895 Will be passed to the compiler as the filename of the cell. Typically
2902 Will be passed to the compiler as the filename of the cell. Typically
2896 the value returned by ip.compile.cache(cell).
2903 the value returned by ip.compile.cache(cell).
2897 interactivity : str
2904 interactivity : str
2898 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2905 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2899 run interactively (displaying output from expressions). 'last_expr'
2906 run interactively (displaying output from expressions). 'last_expr'
2900 will run the last node interactively only if it is an expression (i.e.
2907 will run the last node interactively only if it is an expression (i.e.
2901 expressions in loops or other blocks are not displayed. Other values
2908 expressions in loops or other blocks are not displayed. Other values
2902 for this parameter will raise a ValueError.
2909 for this parameter will raise a ValueError.
2903 compiler : callable
2910 compiler : callable
2904 A function with the same interface as the built-in compile(), to turn
2911 A function with the same interface as the built-in compile(), to turn
2905 the AST nodes into code objects. Default is the built-in compile().
2912 the AST nodes into code objects. Default is the built-in compile().
2906 """
2913 """
2907 if not nodelist:
2914 if not nodelist:
2908 return
2915 return
2909
2916
2910 if interactivity == 'last_expr':
2917 if interactivity == 'last_expr':
2911 if isinstance(nodelist[-1], ast.Expr):
2918 if isinstance(nodelist[-1], ast.Expr):
2912 interactivity = "last"
2919 interactivity = "last"
2913 else:
2920 else:
2914 interactivity = "none"
2921 interactivity = "none"
2915
2922
2916 if interactivity == 'none':
2923 if interactivity == 'none':
2917 to_run_exec, to_run_interactive = nodelist, []
2924 to_run_exec, to_run_interactive = nodelist, []
2918 elif interactivity == 'last':
2925 elif interactivity == 'last':
2919 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2926 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2920 elif interactivity == 'all':
2927 elif interactivity == 'all':
2921 to_run_exec, to_run_interactive = [], nodelist
2928 to_run_exec, to_run_interactive = [], nodelist
2922 else:
2929 else:
2923 raise ValueError("Interactivity was %r" % interactivity)
2930 raise ValueError("Interactivity was %r" % interactivity)
2924
2931
2925 exec_count = self.execution_count
2932 exec_count = self.execution_count
2926
2933
2927 try:
2934 try:
2928 for i, node in enumerate(to_run_exec):
2935 for i, node in enumerate(to_run_exec):
2929 mod = ast.Module([node])
2936 mod = ast.Module([node])
2930 code = compiler(mod, cell_name, "exec")
2937 code = compiler(mod, cell_name, "exec")
2931 if self.run_code(code):
2938 if self.run_code(code):
2932 return True
2939 return True
2933
2940
2934 for i, node in enumerate(to_run_interactive):
2941 for i, node in enumerate(to_run_interactive):
2935 mod = ast.Interactive([node])
2942 mod = ast.Interactive([node])
2936 code = compiler(mod, cell_name, "single")
2943 code = compiler(mod, cell_name, "single")
2937 if self.run_code(code):
2944 if self.run_code(code):
2938 return True
2945 return True
2939
2946
2940 # Flush softspace
2947 # Flush softspace
2941 if softspace(sys.stdout, 0):
2948 if softspace(sys.stdout, 0):
2942 print()
2949 print()
2943
2950
2944 except:
2951 except:
2945 # It's possible to have exceptions raised here, typically by
2952 # It's possible to have exceptions raised here, typically by
2946 # compilation of odd code (such as a naked 'return' outside a
2953 # compilation of odd code (such as a naked 'return' outside a
2947 # function) that did parse but isn't valid. Typically the exception
2954 # function) that did parse but isn't valid. Typically the exception
2948 # is a SyntaxError, but it's safest just to catch anything and show
2955 # is a SyntaxError, but it's safest just to catch anything and show
2949 # the user a traceback.
2956 # the user a traceback.
2950
2957
2951 # We do only one try/except outside the loop to minimize the impact
2958 # We do only one try/except outside the loop to minimize the impact
2952 # on runtime, and also because if any node in the node list is
2959 # on runtime, and also because if any node in the node list is
2953 # broken, we should stop execution completely.
2960 # broken, we should stop execution completely.
2954 self.showtraceback()
2961 self.showtraceback()
2955
2962
2956 return False
2963 return False
2957
2964
2958 def run_code(self, code_obj):
2965 def run_code(self, code_obj):
2959 """Execute a code object.
2966 """Execute a code object.
2960
2967
2961 When an exception occurs, self.showtraceback() is called to display a
2968 When an exception occurs, self.showtraceback() is called to display a
2962 traceback.
2969 traceback.
2963
2970
2964 Parameters
2971 Parameters
2965 ----------
2972 ----------
2966 code_obj : code object
2973 code_obj : code object
2967 A compiled code object, to be executed
2974 A compiled code object, to be executed
2968
2975
2969 Returns
2976 Returns
2970 -------
2977 -------
2971 False : successful execution.
2978 False : successful execution.
2972 True : an error occurred.
2979 True : an error occurred.
2973 """
2980 """
2974 # Set our own excepthook in case the user code tries to call it
2981 # Set our own excepthook in case the user code tries to call it
2975 # directly, so that the IPython crash handler doesn't get triggered
2982 # directly, so that the IPython crash handler doesn't get triggered
2976 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2983 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2977
2984
2978 # we save the original sys.excepthook in the instance, in case config
2985 # we save the original sys.excepthook in the instance, in case config
2979 # code (such as magics) needs access to it.
2986 # code (such as magics) needs access to it.
2980 self.sys_excepthook = old_excepthook
2987 self.sys_excepthook = old_excepthook
2981 outflag = 1 # happens in more places, so it's easier as default
2988 outflag = 1 # happens in more places, so it's easier as default
2982 try:
2989 try:
2983 try:
2990 try:
2984 self.hooks.pre_run_code_hook()
2991 self.hooks.pre_run_code_hook()
2985 #rprint('Running code', repr(code_obj)) # dbg
2992 #rprint('Running code', repr(code_obj)) # dbg
2986 exec(code_obj, self.user_global_ns, self.user_ns)
2993 exec(code_obj, self.user_global_ns, self.user_ns)
2987 finally:
2994 finally:
2988 # Reset our crash handler in place
2995 # Reset our crash handler in place
2989 sys.excepthook = old_excepthook
2996 sys.excepthook = old_excepthook
2990 except SystemExit:
2997 except SystemExit:
2991 self.showtraceback(exception_only=True)
2998 self.showtraceback(exception_only=True)
2992 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2999 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2993 except self.custom_exceptions:
3000 except self.custom_exceptions:
2994 etype, value, tb = sys.exc_info()
3001 etype, value, tb = sys.exc_info()
2995 self.CustomTB(etype, value, tb)
3002 self.CustomTB(etype, value, tb)
2996 except:
3003 except:
2997 self.showtraceback()
3004 self.showtraceback()
2998 else:
3005 else:
2999 outflag = 0
3006 outflag = 0
3000 return outflag
3007 return outflag
3001
3008
3002 # For backwards compatibility
3009 # For backwards compatibility
3003 runcode = run_code
3010 runcode = run_code
3004
3011
3005 #-------------------------------------------------------------------------
3012 #-------------------------------------------------------------------------
3006 # Things related to GUI support and pylab
3013 # Things related to GUI support and pylab
3007 #-------------------------------------------------------------------------
3014 #-------------------------------------------------------------------------
3008
3015
3009 def enable_gui(self, gui=None):
3016 def enable_gui(self, gui=None):
3010 raise NotImplementedError('Implement enable_gui in a subclass')
3017 raise NotImplementedError('Implement enable_gui in a subclass')
3011
3018
3012 def enable_matplotlib(self, gui=None):
3019 def enable_matplotlib(self, gui=None):
3013 """Enable interactive matplotlib and inline figure support.
3020 """Enable interactive matplotlib and inline figure support.
3014
3021
3015 This takes the following steps:
3022 This takes the following steps:
3016
3023
3017 1. select the appropriate eventloop and matplotlib backend
3024 1. select the appropriate eventloop and matplotlib backend
3018 2. set up matplotlib for interactive use with that backend
3025 2. set up matplotlib for interactive use with that backend
3019 3. configure formatters for inline figure display
3026 3. configure formatters for inline figure display
3020 4. enable the selected gui eventloop
3027 4. enable the selected gui eventloop
3021
3028
3022 Parameters
3029 Parameters
3023 ----------
3030 ----------
3024 gui : optional, string
3031 gui : optional, string
3025 If given, dictates the choice of matplotlib GUI backend to use
3032 If given, dictates the choice of matplotlib GUI backend to use
3026 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3033 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3027 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3034 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3028 matplotlib (as dictated by the matplotlib build-time options plus the
3035 matplotlib (as dictated by the matplotlib build-time options plus the
3029 user's matplotlibrc configuration file). Note that not all backends
3036 user's matplotlibrc configuration file). Note that not all backends
3030 make sense in all contexts, for example a terminal ipython can't
3037 make sense in all contexts, for example a terminal ipython can't
3031 display figures inline.
3038 display figures inline.
3032 """
3039 """
3033 from IPython.core import pylabtools as pt
3040 from IPython.core import pylabtools as pt
3034 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3041 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3035
3042
3036 if gui != 'inline':
3043 if gui != 'inline':
3037 # If we have our first gui selection, store it
3044 # If we have our first gui selection, store it
3038 if self.pylab_gui_select is None:
3045 if self.pylab_gui_select is None:
3039 self.pylab_gui_select = gui
3046 self.pylab_gui_select = gui
3040 # Otherwise if they are different
3047 # Otherwise if they are different
3041 elif gui != self.pylab_gui_select:
3048 elif gui != self.pylab_gui_select:
3042 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3049 print ('Warning: Cannot change to a different GUI toolkit: %s.'
3043 ' Using %s instead.' % (gui, self.pylab_gui_select))
3050 ' Using %s instead.' % (gui, self.pylab_gui_select))
3044 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3051 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3045
3052
3046 pt.activate_matplotlib(backend)
3053 pt.activate_matplotlib(backend)
3047 pt.configure_inline_support(self, backend)
3054 pt.configure_inline_support(self, backend)
3048
3055
3049 # Now we must activate the gui pylab wants to use, and fix %run to take
3056 # Now we must activate the gui pylab wants to use, and fix %run to take
3050 # plot updates into account
3057 # plot updates into account
3051 self.enable_gui(gui)
3058 self.enable_gui(gui)
3052 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3059 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3053 pt.mpl_runner(self.safe_execfile)
3060 pt.mpl_runner(self.safe_execfile)
3054
3061
3055 return gui, backend
3062 return gui, backend
3056
3063
3057 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3064 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3058 """Activate pylab support at runtime.
3065 """Activate pylab support at runtime.
3059
3066
3060 This turns on support for matplotlib, preloads into the interactive
3067 This turns on support for matplotlib, preloads into the interactive
3061 namespace all of numpy and pylab, and configures IPython to correctly
3068 namespace all of numpy and pylab, and configures IPython to correctly
3062 interact with the GUI event loop. The GUI backend to be used can be
3069 interact with the GUI event loop. The GUI backend to be used can be
3063 optionally selected with the optional ``gui`` argument.
3070 optionally selected with the optional ``gui`` argument.
3064
3071
3065 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3072 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3066
3073
3067 Parameters
3074 Parameters
3068 ----------
3075 ----------
3069 gui : optional, string
3076 gui : optional, string
3070 If given, dictates the choice of matplotlib GUI backend to use
3077 If given, dictates the choice of matplotlib GUI backend to use
3071 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3078 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3072 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3079 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3073 matplotlib (as dictated by the matplotlib build-time options plus the
3080 matplotlib (as dictated by the matplotlib build-time options plus the
3074 user's matplotlibrc configuration file). Note that not all backends
3081 user's matplotlibrc configuration file). Note that not all backends
3075 make sense in all contexts, for example a terminal ipython can't
3082 make sense in all contexts, for example a terminal ipython can't
3076 display figures inline.
3083 display figures inline.
3077 import_all : optional, bool, default: True
3084 import_all : optional, bool, default: True
3078 Whether to do `from numpy import *` and `from pylab import *`
3085 Whether to do `from numpy import *` and `from pylab import *`
3079 in addition to module imports.
3086 in addition to module imports.
3080 welcome_message : deprecated
3087 welcome_message : deprecated
3081 This argument is ignored, no welcome message will be displayed.
3088 This argument is ignored, no welcome message will be displayed.
3082 """
3089 """
3083 from IPython.core.pylabtools import import_pylab
3090 from IPython.core.pylabtools import import_pylab
3084
3091
3085 gui, backend = self.enable_matplotlib(gui)
3092 gui, backend = self.enable_matplotlib(gui)
3086
3093
3087 # We want to prevent the loading of pylab to pollute the user's
3094 # We want to prevent the loading of pylab to pollute the user's
3088 # namespace as shown by the %who* magics, so we execute the activation
3095 # namespace as shown by the %who* magics, so we execute the activation
3089 # code in an empty namespace, and we update *both* user_ns and
3096 # code in an empty namespace, and we update *both* user_ns and
3090 # user_ns_hidden with this information.
3097 # user_ns_hidden with this information.
3091 ns = {}
3098 ns = {}
3092 import_pylab(ns, import_all)
3099 import_pylab(ns, import_all)
3093 # warn about clobbered names
3100 # warn about clobbered names
3094 ignored = set(["__builtins__"])
3101 ignored = set(["__builtins__"])
3095 both = set(ns).intersection(self.user_ns).difference(ignored)
3102 both = set(ns).intersection(self.user_ns).difference(ignored)
3096 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3103 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3097 self.user_ns.update(ns)
3104 self.user_ns.update(ns)
3098 self.user_ns_hidden.update(ns)
3105 self.user_ns_hidden.update(ns)
3099 return gui, backend, clobbered
3106 return gui, backend, clobbered
3100
3107
3101 #-------------------------------------------------------------------------
3108 #-------------------------------------------------------------------------
3102 # Utilities
3109 # Utilities
3103 #-------------------------------------------------------------------------
3110 #-------------------------------------------------------------------------
3104
3111
3105 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3112 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3106 """Expand python variables in a string.
3113 """Expand python variables in a string.
3107
3114
3108 The depth argument indicates how many frames above the caller should
3115 The depth argument indicates how many frames above the caller should
3109 be walked to look for the local namespace where to expand variables.
3116 be walked to look for the local namespace where to expand variables.
3110
3117
3111 The global namespace for expansion is always the user's interactive
3118 The global namespace for expansion is always the user's interactive
3112 namespace.
3119 namespace.
3113 """
3120 """
3114 ns = self.user_ns.copy()
3121 ns = self.user_ns.copy()
3115 try:
3122 try:
3116 frame = sys._getframe(depth+1)
3123 frame = sys._getframe(depth+1)
3117 except ValueError:
3124 except ValueError:
3118 # This is thrown if there aren't that many frames on the stack,
3125 # This is thrown if there aren't that many frames on the stack,
3119 # e.g. if a script called run_line_magic() directly.
3126 # e.g. if a script called run_line_magic() directly.
3120 pass
3127 pass
3121 else:
3128 else:
3122 ns.update(frame.f_locals)
3129 ns.update(frame.f_locals)
3123
3130
3124 try:
3131 try:
3125 # We have to use .vformat() here, because 'self' is a valid and common
3132 # We have to use .vformat() here, because 'self' is a valid and common
3126 # name, and expanding **ns for .format() would make it collide with
3133 # name, and expanding **ns for .format() would make it collide with
3127 # the 'self' argument of the method.
3134 # the 'self' argument of the method.
3128 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3135 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3129 except Exception:
3136 except Exception:
3130 # if formatter couldn't format, just let it go untransformed
3137 # if formatter couldn't format, just let it go untransformed
3131 pass
3138 pass
3132 return cmd
3139 return cmd
3133
3140
3134 def mktempfile(self, data=None, prefix='ipython_edit_'):
3141 def mktempfile(self, data=None, prefix='ipython_edit_'):
3135 """Make a new tempfile and return its filename.
3142 """Make a new tempfile and return its filename.
3136
3143
3137 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3144 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3138 but it registers the created filename internally so ipython cleans it up
3145 but it registers the created filename internally so ipython cleans it up
3139 at exit time.
3146 at exit time.
3140
3147
3141 Optional inputs:
3148 Optional inputs:
3142
3149
3143 - data(None): if data is given, it gets written out to the temp file
3150 - data(None): if data is given, it gets written out to the temp file
3144 immediately, and the file is closed again."""
3151 immediately, and the file is closed again."""
3145
3152
3146 dirname = tempfile.mkdtemp(prefix=prefix)
3153 dirname = tempfile.mkdtemp(prefix=prefix)
3147 self.tempdirs.append(dirname)
3154 self.tempdirs.append(dirname)
3148
3155
3149 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3156 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3150 os.close(handle) # On Windows, there can only be one open handle on a file
3157 os.close(handle) # On Windows, there can only be one open handle on a file
3151 self.tempfiles.append(filename)
3158 self.tempfiles.append(filename)
3152
3159
3153 if data:
3160 if data:
3154 tmp_file = open(filename,'w')
3161 tmp_file = open(filename,'w')
3155 tmp_file.write(data)
3162 tmp_file.write(data)
3156 tmp_file.close()
3163 tmp_file.close()
3157 return filename
3164 return filename
3158
3165
3159 # TODO: This should be removed when Term is refactored.
3166 # TODO: This should be removed when Term is refactored.
3160 def write(self,data):
3167 def write(self,data):
3161 """Write a string to the default output"""
3168 """Write a string to the default output"""
3162 io.stdout.write(data)
3169 io.stdout.write(data)
3163
3170
3164 # TODO: This should be removed when Term is refactored.
3171 # TODO: This should be removed when Term is refactored.
3165 def write_err(self,data):
3172 def write_err(self,data):
3166 """Write a string to the default error output"""
3173 """Write a string to the default error output"""
3167 io.stderr.write(data)
3174 io.stderr.write(data)
3168
3175
3169 def ask_yes_no(self, prompt, default=None):
3176 def ask_yes_no(self, prompt, default=None):
3170 if self.quiet:
3177 if self.quiet:
3171 return True
3178 return True
3172 return ask_yes_no(prompt,default)
3179 return ask_yes_no(prompt,default)
3173
3180
3174 def show_usage(self):
3181 def show_usage(self):
3175 """Show a usage message"""
3182 """Show a usage message"""
3176 page.page(IPython.core.usage.interactive_usage)
3183 page.page(IPython.core.usage.interactive_usage)
3177
3184
3178 def extract_input_lines(self, range_str, raw=False):
3185 def extract_input_lines(self, range_str, raw=False):
3179 """Return as a string a set of input history slices.
3186 """Return as a string a set of input history slices.
3180
3187
3181 Parameters
3188 Parameters
3182 ----------
3189 ----------
3183 range_str : string
3190 range_str : string
3184 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3191 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3185 since this function is for use by magic functions which get their
3192 since this function is for use by magic functions which get their
3186 arguments as strings. The number before the / is the session
3193 arguments as strings. The number before the / is the session
3187 number: ~n goes n back from the current session.
3194 number: ~n goes n back from the current session.
3188
3195
3189 raw : bool, optional
3196 raw : bool, optional
3190 By default, the processed input is used. If this is true, the raw
3197 By default, the processed input is used. If this is true, the raw
3191 input history is used instead.
3198 input history is used instead.
3192
3199
3193 Notes
3200 Notes
3194 -----
3201 -----
3195
3202
3196 Slices can be described with two notations:
3203 Slices can be described with two notations:
3197
3204
3198 * ``N:M`` -> standard python form, means including items N...(M-1).
3205 * ``N:M`` -> standard python form, means including items N...(M-1).
3199 * ``N-M`` -> include items N..M (closed endpoint).
3206 * ``N-M`` -> include items N..M (closed endpoint).
3200 """
3207 """
3201 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3208 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3202 return "\n".join(x for _, _, x in lines)
3209 return "\n".join(x for _, _, x in lines)
3203
3210
3204 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3211 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3205 """Get a code string from history, file, url, or a string or macro.
3212 """Get a code string from history, file, url, or a string or macro.
3206
3213
3207 This is mainly used by magic functions.
3214 This is mainly used by magic functions.
3208
3215
3209 Parameters
3216 Parameters
3210 ----------
3217 ----------
3211
3218
3212 target : str
3219 target : str
3213
3220
3214 A string specifying code to retrieve. This will be tried respectively
3221 A string specifying code to retrieve. This will be tried respectively
3215 as: ranges of input history (see %history for syntax), url,
3222 as: ranges of input history (see %history for syntax), url,
3216 correspnding .py file, filename, or an expression evaluating to a
3223 correspnding .py file, filename, or an expression evaluating to a
3217 string or Macro in the user namespace.
3224 string or Macro in the user namespace.
3218
3225
3219 raw : bool
3226 raw : bool
3220 If true (default), retrieve raw history. Has no effect on the other
3227 If true (default), retrieve raw history. Has no effect on the other
3221 retrieval mechanisms.
3228 retrieval mechanisms.
3222
3229
3223 py_only : bool (default False)
3230 py_only : bool (default False)
3224 Only try to fetch python code, do not try alternative methods to decode file
3231 Only try to fetch python code, do not try alternative methods to decode file
3225 if unicode fails.
3232 if unicode fails.
3226
3233
3227 Returns
3234 Returns
3228 -------
3235 -------
3229 A string of code.
3236 A string of code.
3230
3237
3231 ValueError is raised if nothing is found, and TypeError if it evaluates
3238 ValueError is raised if nothing is found, and TypeError if it evaluates
3232 to an object of another type. In each case, .args[0] is a printable
3239 to an object of another type. In each case, .args[0] is a printable
3233 message.
3240 message.
3234 """
3241 """
3235 code = self.extract_input_lines(target, raw=raw) # Grab history
3242 code = self.extract_input_lines(target, raw=raw) # Grab history
3236 if code:
3243 if code:
3237 return code
3244 return code
3238 utarget = unquote_filename(target)
3245 utarget = unquote_filename(target)
3239 try:
3246 try:
3240 if utarget.startswith(('http://', 'https://')):
3247 if utarget.startswith(('http://', 'https://')):
3241 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3248 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3242 except UnicodeDecodeError:
3249 except UnicodeDecodeError:
3243 if not py_only :
3250 if not py_only :
3244 # Deferred import
3251 # Deferred import
3245 try:
3252 try:
3246 from urllib.request import urlopen # Py3
3253 from urllib.request import urlopen # Py3
3247 except ImportError:
3254 except ImportError:
3248 from urllib import urlopen
3255 from urllib import urlopen
3249 response = urlopen(target)
3256 response = urlopen(target)
3250 return response.read().decode('latin1')
3257 return response.read().decode('latin1')
3251 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3258 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3252
3259
3253 potential_target = [target]
3260 potential_target = [target]
3254 try :
3261 try :
3255 potential_target.insert(0,get_py_filename(target))
3262 potential_target.insert(0,get_py_filename(target))
3256 except IOError:
3263 except IOError:
3257 pass
3264 pass
3258
3265
3259 for tgt in potential_target :
3266 for tgt in potential_target :
3260 if os.path.isfile(tgt): # Read file
3267 if os.path.isfile(tgt): # Read file
3261 try :
3268 try :
3262 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3269 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3263 except UnicodeDecodeError :
3270 except UnicodeDecodeError :
3264 if not py_only :
3271 if not py_only :
3265 with io_open(tgt,'r', encoding='latin1') as f :
3272 with io_open(tgt,'r', encoding='latin1') as f :
3266 return f.read()
3273 return f.read()
3267 raise ValueError(("'%s' seem to be unreadable.") % target)
3274 raise ValueError(("'%s' seem to be unreadable.") % target)
3268 elif os.path.isdir(os.path.expanduser(tgt)):
3275 elif os.path.isdir(os.path.expanduser(tgt)):
3269 raise ValueError("'%s' is a directory, not a regular file." % target)
3276 raise ValueError("'%s' is a directory, not a regular file." % target)
3270
3277
3271 if search_ns:
3278 if search_ns:
3272 # Inspect namespace to load object source
3279 # Inspect namespace to load object source
3273 object_info = self.object_inspect(target, detail_level=1)
3280 object_info = self.object_inspect(target, detail_level=1)
3274 if object_info['found'] and object_info['source']:
3281 if object_info['found'] and object_info['source']:
3275 return object_info['source']
3282 return object_info['source']
3276
3283
3277 try: # User namespace
3284 try: # User namespace
3278 codeobj = eval(target, self.user_ns)
3285 codeobj = eval(target, self.user_ns)
3279 except Exception:
3286 except Exception:
3280 raise ValueError(("'%s' was not found in history, as a file, url, "
3287 raise ValueError(("'%s' was not found in history, as a file, url, "
3281 "nor in the user namespace.") % target)
3288 "nor in the user namespace.") % target)
3282
3289
3283 if isinstance(codeobj, string_types):
3290 if isinstance(codeobj, string_types):
3284 return codeobj
3291 return codeobj
3285 elif isinstance(codeobj, Macro):
3292 elif isinstance(codeobj, Macro):
3286 return codeobj.value
3293 return codeobj.value
3287
3294
3288 raise TypeError("%s is neither a string nor a macro." % target,
3295 raise TypeError("%s is neither a string nor a macro." % target,
3289 codeobj)
3296 codeobj)
3290
3297
3291 #-------------------------------------------------------------------------
3298 #-------------------------------------------------------------------------
3292 # Things related to IPython exiting
3299 # Things related to IPython exiting
3293 #-------------------------------------------------------------------------
3300 #-------------------------------------------------------------------------
3294 def atexit_operations(self):
3301 def atexit_operations(self):
3295 """This will be executed at the time of exit.
3302 """This will be executed at the time of exit.
3296
3303
3297 Cleanup operations and saving of persistent data that is done
3304 Cleanup operations and saving of persistent data that is done
3298 unconditionally by IPython should be performed here.
3305 unconditionally by IPython should be performed here.
3299
3306
3300 For things that may depend on startup flags or platform specifics (such
3307 For things that may depend on startup flags or platform specifics (such
3301 as having readline or not), register a separate atexit function in the
3308 as having readline or not), register a separate atexit function in the
3302 code that has the appropriate information, rather than trying to
3309 code that has the appropriate information, rather than trying to
3303 clutter
3310 clutter
3304 """
3311 """
3305 # Close the history session (this stores the end time and line count)
3312 # Close the history session (this stores the end time and line count)
3306 # this must be *before* the tempfile cleanup, in case of temporary
3313 # this must be *before* the tempfile cleanup, in case of temporary
3307 # history db
3314 # history db
3308 self.history_manager.end_session()
3315 self.history_manager.end_session()
3309
3316
3310 # Cleanup all tempfiles and folders left around
3317 # Cleanup all tempfiles and folders left around
3311 for tfile in self.tempfiles:
3318 for tfile in self.tempfiles:
3312 try:
3319 try:
3313 os.unlink(tfile)
3320 os.unlink(tfile)
3314 except OSError:
3321 except OSError:
3315 pass
3322 pass
3316
3323
3317 for tdir in self.tempdirs:
3324 for tdir in self.tempdirs:
3318 try:
3325 try:
3319 os.rmdir(tdir)
3326 os.rmdir(tdir)
3320 except OSError:
3327 except OSError:
3321 pass
3328 pass
3322
3329
3323 # Clear all user namespaces to release all references cleanly.
3330 # Clear all user namespaces to release all references cleanly.
3324 self.reset(new_session=False)
3331 self.reset(new_session=False)
3325
3332
3326 # Run user hooks
3333 # Run user hooks
3327 self.hooks.shutdown_hook()
3334 self.hooks.shutdown_hook()
3328
3335
3329 def cleanup(self):
3336 def cleanup(self):
3330 self.restore_sys_module_state()
3337 self.restore_sys_module_state()
3331
3338
3332
3339
3333 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3340 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3334 """An abstract base class for InteractiveShell."""
3341 """An abstract base class for InteractiveShell."""
3335
3342
3336 InteractiveShellABC.register(InteractiveShell)
3343 InteractiveShellABC.register(InteractiveShell)
@@ -1,360 +1,381 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Paging capabilities for IPython.core
3 Paging capabilities for IPython.core
4
4
5 Authors:
6
7 * Brian Granger
8 * Fernando Perez
9
10 Notes
5 Notes
11 -----
6 -----
12
7
13 For now this uses ipapi, so it can't be in IPython.utils. If we can get
8 For now this uses IPython hooks, so it can't be in IPython.utils. If we can get
14 rid of that dependency, we could move it there.
9 rid of that dependency, we could move it there.
15 -----
10 -----
16 """
11 """
17
12
18 #-----------------------------------------------------------------------------
13 # Copyright (c) IPython Development Team.
19 # Copyright (C) 2008-2011 The IPython Development Team
14 # Distributed under the terms of the Modified BSD License.
20 #
21 # Distributed under the terms of the BSD License. The full license is in
22 # the file COPYING, distributed as part of this software.
23 #-----------------------------------------------------------------------------
24
15
25 #-----------------------------------------------------------------------------
26 # Imports
27 #-----------------------------------------------------------------------------
28 from __future__ import print_function
16 from __future__ import print_function
29
17
30 import os
18 import os
31 import re
19 import re
32 import sys
20 import sys
33 import tempfile
21 import tempfile
34
22
35 from io import UnsupportedOperation
23 from io import UnsupportedOperation
36
24
37 from IPython import get_ipython
25 from IPython import get_ipython
26 from IPython.core.display import display
38 from IPython.core.error import TryNext
27 from IPython.core.error import TryNext
39 from IPython.utils.data import chop
28 from IPython.utils.data import chop
40 from IPython.utils import io
29 from IPython.utils import io
41 from IPython.utils.process import system
30 from IPython.utils.process import system
42 from IPython.utils.terminal import get_terminal_size
31 from IPython.utils.terminal import get_terminal_size
43 from IPython.utils import py3compat
32 from IPython.utils import py3compat
44
33
45
34
46 #-----------------------------------------------------------------------------
35 def display_page(strng, start=0, screen_lines=25):
47 # Classes and functions
36 """Just display, no paging. screen_lines is ignored."""
48 #-----------------------------------------------------------------------------
37 if isinstance(strng, dict):
38 data = strng
39 else:
40 if start:
41 strng = u'\n'.join(strng.splitlines()[start:])
42 data = {'text/plain': strng}
43 display(data, raw=True)
44
45
46 def as_hook(page_func):
47 """Wrap a pager func to strip the `self` arg
48
49 so it can be called as a hook.
50 """
51 return lambda self, *args, **kwargs: page_func(*args, **kwargs)
52
49
53
50 esc_re = re.compile(r"(\x1b[^m]+m)")
54 esc_re = re.compile(r"(\x1b[^m]+m)")
51
55
52 def page_dumb(strng, start=0, screen_lines=25):
56 def page_dumb(strng, start=0, screen_lines=25):
53 """Very dumb 'pager' in Python, for when nothing else works.
57 """Very dumb 'pager' in Python, for when nothing else works.
54
58
55 Only moves forward, same interface as page(), except for pager_cmd and
59 Only moves forward, same interface as page(), except for pager_cmd and
56 mode."""
60 mode."""
57
61
58 out_ln = strng.splitlines()[start:]
62 out_ln = strng.splitlines()[start:]
59 screens = chop(out_ln,screen_lines-1)
63 screens = chop(out_ln,screen_lines-1)
60 if len(screens) == 1:
64 if len(screens) == 1:
61 print(os.linesep.join(screens[0]), file=io.stdout)
65 print(os.linesep.join(screens[0]), file=io.stdout)
62 else:
66 else:
63 last_escape = ""
67 last_escape = ""
64 for scr in screens[0:-1]:
68 for scr in screens[0:-1]:
65 hunk = os.linesep.join(scr)
69 hunk = os.linesep.join(scr)
66 print(last_escape + hunk, file=io.stdout)
70 print(last_escape + hunk, file=io.stdout)
67 if not page_more():
71 if not page_more():
68 return
72 return
69 esc_list = esc_re.findall(hunk)
73 esc_list = esc_re.findall(hunk)
70 if len(esc_list) > 0:
74 if len(esc_list) > 0:
71 last_escape = esc_list[-1]
75 last_escape = esc_list[-1]
72 print(last_escape + os.linesep.join(screens[-1]), file=io.stdout)
76 print(last_escape + os.linesep.join(screens[-1]), file=io.stdout)
73
77
74 def _detect_screen_size(screen_lines_def):
78 def _detect_screen_size(screen_lines_def):
75 """Attempt to work out the number of lines on the screen.
79 """Attempt to work out the number of lines on the screen.
76
80
77 This is called by page(). It can raise an error (e.g. when run in the
81 This is called by page(). It can raise an error (e.g. when run in the
78 test suite), so it's separated out so it can easily be called in a try block.
82 test suite), so it's separated out so it can easily be called in a try block.
79 """
83 """
80 TERM = os.environ.get('TERM',None)
84 TERM = os.environ.get('TERM',None)
81 if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'):
85 if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'):
82 # curses causes problems on many terminals other than xterm, and
86 # curses causes problems on many terminals other than xterm, and
83 # some termios calls lock up on Sun OS5.
87 # some termios calls lock up on Sun OS5.
84 return screen_lines_def
88 return screen_lines_def
85
89
86 try:
90 try:
87 import termios
91 import termios
88 import curses
92 import curses
89 except ImportError:
93 except ImportError:
90 return screen_lines_def
94 return screen_lines_def
91
95
92 # There is a bug in curses, where *sometimes* it fails to properly
96 # There is a bug in curses, where *sometimes* it fails to properly
93 # initialize, and then after the endwin() call is made, the
97 # initialize, and then after the endwin() call is made, the
94 # terminal is left in an unusable state. Rather than trying to
98 # terminal is left in an unusable state. Rather than trying to
95 # check everytime for this (by requesting and comparing termios
99 # check everytime for this (by requesting and comparing termios
96 # flags each time), we just save the initial terminal state and
100 # flags each time), we just save the initial terminal state and
97 # unconditionally reset it every time. It's cheaper than making
101 # unconditionally reset it every time. It's cheaper than making
98 # the checks.
102 # the checks.
99 term_flags = termios.tcgetattr(sys.stdout)
103 term_flags = termios.tcgetattr(sys.stdout)
100
104
101 # Curses modifies the stdout buffer size by default, which messes
105 # Curses modifies the stdout buffer size by default, which messes
102 # up Python's normal stdout buffering. This would manifest itself
106 # up Python's normal stdout buffering. This would manifest itself
103 # to IPython users as delayed printing on stdout after having used
107 # to IPython users as delayed printing on stdout after having used
104 # the pager.
108 # the pager.
105 #
109 #
106 # We can prevent this by manually setting the NCURSES_NO_SETBUF
110 # We can prevent this by manually setting the NCURSES_NO_SETBUF
107 # environment variable. For more details, see:
111 # environment variable. For more details, see:
108 # http://bugs.python.org/issue10144
112 # http://bugs.python.org/issue10144
109 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
113 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
110 os.environ['NCURSES_NO_SETBUF'] = ''
114 os.environ['NCURSES_NO_SETBUF'] = ''
111
115
112 # Proceed with curses initialization
116 # Proceed with curses initialization
113 try:
117 try:
114 scr = curses.initscr()
118 scr = curses.initscr()
115 except AttributeError:
119 except AttributeError:
116 # Curses on Solaris may not be complete, so we can't use it there
120 # Curses on Solaris may not be complete, so we can't use it there
117 return screen_lines_def
121 return screen_lines_def
118
122
119 screen_lines_real,screen_cols = scr.getmaxyx()
123 screen_lines_real,screen_cols = scr.getmaxyx()
120 curses.endwin()
124 curses.endwin()
121
125
122 # Restore environment
126 # Restore environment
123 if NCURSES_NO_SETBUF is None:
127 if NCURSES_NO_SETBUF is None:
124 del os.environ['NCURSES_NO_SETBUF']
128 del os.environ['NCURSES_NO_SETBUF']
125 else:
129 else:
126 os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
130 os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
127
131
128 # Restore terminal state in case endwin() didn't.
132 # Restore terminal state in case endwin() didn't.
129 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
133 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
130 # Now we have what we needed: the screen size in rows/columns
134 # Now we have what we needed: the screen size in rows/columns
131 return screen_lines_real
135 return screen_lines_real
132 #print '***Screen size:',screen_lines_real,'lines x',\
136 #print '***Screen size:',screen_lines_real,'lines x',\
133 #screen_cols,'columns.' # dbg
137 #screen_cols,'columns.' # dbg
134
138
135 def page(strng, start=0, screen_lines=0, pager_cmd=None):
139 def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):
136 """Display a string, piping through a pager after a certain length.
140 """Display a string, piping through a pager after a certain length.
137
141
138 strng can be a mime-bundle dict, supplying multiple representations,
142 strng can be a mime-bundle dict, supplying multiple representations,
139 keyed by mime-type.
143 keyed by mime-type.
140
144
141 The screen_lines parameter specifies the number of *usable* lines of your
145 The screen_lines parameter specifies the number of *usable* lines of your
142 terminal screen (total lines minus lines you need to reserve to show other
146 terminal screen (total lines minus lines you need to reserve to show other
143 information).
147 information).
144
148
145 If you set screen_lines to a number <=0, page() will try to auto-determine
149 If you set screen_lines to a number <=0, page() will try to auto-determine
146 your screen size and will only use up to (screen_size+screen_lines) for
150 your screen size and will only use up to (screen_size+screen_lines) for
147 printing, paging after that. That is, if you want auto-detection but need
151 printing, paging after that. That is, if you want auto-detection but need
148 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
152 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
149 auto-detection without any lines reserved simply use screen_lines = 0.
153 auto-detection without any lines reserved simply use screen_lines = 0.
150
154
151 If a string won't fit in the allowed lines, it is sent through the
155 If a string won't fit in the allowed lines, it is sent through the
152 specified pager command. If none given, look for PAGER in the environment,
156 specified pager command. If none given, look for PAGER in the environment,
153 and ultimately default to less.
157 and ultimately default to less.
154
158
155 If no system pager works, the string is sent through a 'dumb pager'
159 If no system pager works, the string is sent through a 'dumb pager'
156 written in python, very simplistic.
160 written in python, very simplistic.
157 """
161 """
158
162
159 # for compatibility with mime-bundle form:
163 # for compatibility with mime-bundle form:
160 if isinstance(strng, dict):
164 if isinstance(strng, dict):
161 strng = strng['text/plain']
165 strng = strng['text/plain']
162
166
163 # Some routines may auto-compute start offsets incorrectly and pass a
167 # Some routines may auto-compute start offsets incorrectly and pass a
164 # negative value. Offset to 0 for robustness.
168 # negative value. Offset to 0 for robustness.
165 start = max(0, start)
169 start = max(0, start)
166
170
167 # first, try the hook
168 ip = get_ipython()
169 if ip:
170 try:
171 ip.hooks.show_in_pager(strng)
172 return
173 except TryNext:
174 pass
175
176 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
171 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
177 TERM = os.environ.get('TERM','dumb')
172 TERM = os.environ.get('TERM','dumb')
178 if TERM in ['dumb','emacs'] and os.name != 'nt':
173 if TERM in ['dumb','emacs'] and os.name != 'nt':
179 print(strng)
174 print(strng)
180 return
175 return
181 # chop off the topmost part of the string we don't want to see
176 # chop off the topmost part of the string we don't want to see
182 str_lines = strng.splitlines()[start:]
177 str_lines = strng.splitlines()[start:]
183 str_toprint = os.linesep.join(str_lines)
178 str_toprint = os.linesep.join(str_lines)
184 num_newlines = len(str_lines)
179 num_newlines = len(str_lines)
185 len_str = len(str_toprint)
180 len_str = len(str_toprint)
186
181
187 # Dumb heuristics to guesstimate number of on-screen lines the string
182 # Dumb heuristics to guesstimate number of on-screen lines the string
188 # takes. Very basic, but good enough for docstrings in reasonable
183 # takes. Very basic, but good enough for docstrings in reasonable
189 # terminals. If someone later feels like refining it, it's not hard.
184 # terminals. If someone later feels like refining it, it's not hard.
190 numlines = max(num_newlines,int(len_str/80)+1)
185 numlines = max(num_newlines,int(len_str/80)+1)
191
186
192 screen_lines_def = get_terminal_size()[1]
187 screen_lines_def = get_terminal_size()[1]
193
188
194 # auto-determine screen size
189 # auto-determine screen size
195 if screen_lines <= 0:
190 if screen_lines <= 0:
196 try:
191 try:
197 screen_lines += _detect_screen_size(screen_lines_def)
192 screen_lines += _detect_screen_size(screen_lines_def)
198 except (TypeError, UnsupportedOperation):
193 except (TypeError, UnsupportedOperation):
199 print(str_toprint, file=io.stdout)
194 print(str_toprint, file=io.stdout)
200 return
195 return
201
196
202 #print 'numlines',numlines,'screenlines',screen_lines # dbg
197 #print 'numlines',numlines,'screenlines',screen_lines # dbg
203 if numlines <= screen_lines :
198 if numlines <= screen_lines :
204 #print '*** normal print' # dbg
199 #print '*** normal print' # dbg
205 print(str_toprint, file=io.stdout)
200 print(str_toprint, file=io.stdout)
206 else:
201 else:
207 # Try to open pager and default to internal one if that fails.
202 # Try to open pager and default to internal one if that fails.
208 # All failure modes are tagged as 'retval=1', to match the return
203 # All failure modes are tagged as 'retval=1', to match the return
209 # value of a failed system command. If any intermediate attempt
204 # value of a failed system command. If any intermediate attempt
210 # sets retval to 1, at the end we resort to our own page_dumb() pager.
205 # sets retval to 1, at the end we resort to our own page_dumb() pager.
211 pager_cmd = get_pager_cmd(pager_cmd)
206 pager_cmd = get_pager_cmd(pager_cmd)
212 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
207 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
213 if os.name == 'nt':
208 if os.name == 'nt':
214 if pager_cmd.startswith('type'):
209 if pager_cmd.startswith('type'):
215 # The default WinXP 'type' command is failing on complex strings.
210 # The default WinXP 'type' command is failing on complex strings.
216 retval = 1
211 retval = 1
217 else:
212 else:
218 fd, tmpname = tempfile.mkstemp('.txt')
213 fd, tmpname = tempfile.mkstemp('.txt')
219 try:
214 try:
220 os.close(fd)
215 os.close(fd)
221 with open(tmpname, 'wt') as tmpfile:
216 with open(tmpname, 'wt') as tmpfile:
222 tmpfile.write(strng)
217 tmpfile.write(strng)
223 cmd = "%s < %s" % (pager_cmd, tmpname)
218 cmd = "%s < %s" % (pager_cmd, tmpname)
224 # tmpfile needs to be closed for windows
219 # tmpfile needs to be closed for windows
225 if os.system(cmd):
220 if os.system(cmd):
226 retval = 1
221 retval = 1
227 else:
222 else:
228 retval = None
223 retval = None
229 finally:
224 finally:
230 os.remove(tmpname)
225 os.remove(tmpname)
231 else:
226 else:
232 try:
227 try:
233 retval = None
228 retval = None
234 # if I use popen4, things hang. No idea why.
229 # if I use popen4, things hang. No idea why.
235 #pager,shell_out = os.popen4(pager_cmd)
230 #pager,shell_out = os.popen4(pager_cmd)
236 pager = os.popen(pager_cmd, 'w')
231 pager = os.popen(pager_cmd, 'w')
237 try:
232 try:
238 pager_encoding = pager.encoding or sys.stdout.encoding
233 pager_encoding = pager.encoding or sys.stdout.encoding
239 pager.write(py3compat.cast_bytes_py2(
234 pager.write(py3compat.cast_bytes_py2(
240 strng, encoding=pager_encoding))
235 strng, encoding=pager_encoding))
241 finally:
236 finally:
242 retval = pager.close()
237 retval = pager.close()
243 except IOError as msg: # broken pipe when user quits
238 except IOError as msg: # broken pipe when user quits
244 if msg.args == (32, 'Broken pipe'):
239 if msg.args == (32, 'Broken pipe'):
245 retval = None
240 retval = None
246 else:
241 else:
247 retval = 1
242 retval = 1
248 except OSError:
243 except OSError:
249 # Other strange problems, sometimes seen in Win2k/cygwin
244 # Other strange problems, sometimes seen in Win2k/cygwin
250 retval = 1
245 retval = 1
251 if retval is not None:
246 if retval is not None:
252 page_dumb(strng,screen_lines=screen_lines)
247 page_dumb(strng,screen_lines=screen_lines)
253
248
254
249
250 def page(data, start=0, screen_lines=0, pager_cmd=None):
251 """Display content in a pager, piping through a pager after a certain length.
252
253 data can be a mime-bundle dict, supplying multiple representations,
254 keyed by mime-type, or text.
255
256 Pager is dispatched via the `show_in_pager` IPython hook.
257 If no hook is registered, `pager_page` will be used.
258 """
259 # Some routines may auto-compute start offsets incorrectly and pass a
260 # negative value. Offset to 0 for robustness.
261 start = max(0, start)
262
263 # first, try the hook
264 ip = get_ipython()
265 if ip:
266 try:
267 ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines)
268 return
269 except TryNext:
270 pass
271
272 # fallback on default pager
273 return pager_page(data, start, screen_lines, pager_cmd)
274
275
255 def page_file(fname, start=0, pager_cmd=None):
276 def page_file(fname, start=0, pager_cmd=None):
256 """Page a file, using an optional pager command and starting line.
277 """Page a file, using an optional pager command and starting line.
257 """
278 """
258
279
259 pager_cmd = get_pager_cmd(pager_cmd)
280 pager_cmd = get_pager_cmd(pager_cmd)
260 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
281 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
261
282
262 try:
283 try:
263 if os.environ['TERM'] in ['emacs','dumb']:
284 if os.environ['TERM'] in ['emacs','dumb']:
264 raise EnvironmentError
285 raise EnvironmentError
265 system(pager_cmd + ' ' + fname)
286 system(pager_cmd + ' ' + fname)
266 except:
287 except:
267 try:
288 try:
268 if start > 0:
289 if start > 0:
269 start -= 1
290 start -= 1
270 page(open(fname).read(),start)
291 page(open(fname).read(),start)
271 except:
292 except:
272 print('Unable to show file',repr(fname))
293 print('Unable to show file',repr(fname))
273
294
274
295
275 def get_pager_cmd(pager_cmd=None):
296 def get_pager_cmd(pager_cmd=None):
276 """Return a pager command.
297 """Return a pager command.
277
298
278 Makes some attempts at finding an OS-correct one.
299 Makes some attempts at finding an OS-correct one.
279 """
300 """
280 if os.name == 'posix':
301 if os.name == 'posix':
281 default_pager_cmd = 'less -r' # -r for color control sequences
302 default_pager_cmd = 'less -r' # -r for color control sequences
282 elif os.name in ['nt','dos']:
303 elif os.name in ['nt','dos']:
283 default_pager_cmd = 'type'
304 default_pager_cmd = 'type'
284
305
285 if pager_cmd is None:
306 if pager_cmd is None:
286 try:
307 try:
287 pager_cmd = os.environ['PAGER']
308 pager_cmd = os.environ['PAGER']
288 except:
309 except:
289 pager_cmd = default_pager_cmd
310 pager_cmd = default_pager_cmd
290 return pager_cmd
311 return pager_cmd
291
312
292
313
293 def get_pager_start(pager, start):
314 def get_pager_start(pager, start):
294 """Return the string for paging files with an offset.
315 """Return the string for paging files with an offset.
295
316
296 This is the '+N' argument which less and more (under Unix) accept.
317 This is the '+N' argument which less and more (under Unix) accept.
297 """
318 """
298
319
299 if pager in ['less','more']:
320 if pager in ['less','more']:
300 if start:
321 if start:
301 start_string = '+' + str(start)
322 start_string = '+' + str(start)
302 else:
323 else:
303 start_string = ''
324 start_string = ''
304 else:
325 else:
305 start_string = ''
326 start_string = ''
306 return start_string
327 return start_string
307
328
308
329
309 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
330 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
310 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
331 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
311 import msvcrt
332 import msvcrt
312 def page_more():
333 def page_more():
313 """ Smart pausing between pages
334 """ Smart pausing between pages
314
335
315 @return: True if need print more lines, False if quit
336 @return: True if need print more lines, False if quit
316 """
337 """
317 io.stdout.write('---Return to continue, q to quit--- ')
338 io.stdout.write('---Return to continue, q to quit--- ')
318 ans = msvcrt.getwch()
339 ans = msvcrt.getwch()
319 if ans in ("q", "Q"):
340 if ans in ("q", "Q"):
320 result = False
341 result = False
321 else:
342 else:
322 result = True
343 result = True
323 io.stdout.write("\b"*37 + " "*37 + "\b"*37)
344 io.stdout.write("\b"*37 + " "*37 + "\b"*37)
324 return result
345 return result
325 else:
346 else:
326 def page_more():
347 def page_more():
327 ans = py3compat.input('---Return to continue, q to quit--- ')
348 ans = py3compat.input('---Return to continue, q to quit--- ')
328 if ans.lower().startswith('q'):
349 if ans.lower().startswith('q'):
329 return False
350 return False
330 else:
351 else:
331 return True
352 return True
332
353
333
354
334 def snip_print(str,width = 75,print_full = 0,header = ''):
355 def snip_print(str,width = 75,print_full = 0,header = ''):
335 """Print a string snipping the midsection to fit in width.
356 """Print a string snipping the midsection to fit in width.
336
357
337 print_full: mode control:
358 print_full: mode control:
338
359
339 - 0: only snip long strings
360 - 0: only snip long strings
340 - 1: send to page() directly.
361 - 1: send to page() directly.
341 - 2: snip long strings and ask for full length viewing with page()
362 - 2: snip long strings and ask for full length viewing with page()
342
363
343 Return 1 if snipping was necessary, 0 otherwise."""
364 Return 1 if snipping was necessary, 0 otherwise."""
344
365
345 if print_full == 1:
366 if print_full == 1:
346 page(header+str)
367 page(header+str)
347 return 0
368 return 0
348
369
349 print(header, end=' ')
370 print(header, end=' ')
350 if len(str) < width:
371 if len(str) < width:
351 print(str)
372 print(str)
352 snip = 0
373 snip = 0
353 else:
374 else:
354 whalf = int((width -5)/2)
375 whalf = int((width -5)/2)
355 print(str[:whalf] + ' <...> ' + str[-whalf:])
376 print(str[:whalf] + ' <...> ' + str[-whalf:])
356 snip = 1
377 snip = 1
357 if snip and print_full == 2:
378 if snip and print_full == 2:
358 if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
379 if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
359 page(str)
380 page(str)
360 return snip
381 return snip
@@ -1,48 +1,52 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """A payload based version of page."""
2 """A payload based version of page."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 import warnings
7 from IPython.core.getipython import get_ipython
8 from IPython.core.getipython import get_ipython
8
9
9 #-----------------------------------------------------------------------------
10 # Classes and functions
11 #-----------------------------------------------------------------------------
12
10
13 def page(strng, start=0, screen_lines=0, pager_cmd=None):
11 def page(strng, start=0, screen_lines=0, pager_cmd=None):
14 """Print a string, piping through a pager.
12 """Print a string, piping through a pager.
15
13
16 This version ignores the screen_lines and pager_cmd arguments and uses
14 This version ignores the screen_lines and pager_cmd arguments and uses
17 IPython's payload system instead.
15 IPython's payload system instead.
18
16
19 Parameters
17 Parameters
20 ----------
18 ----------
21 strng : str or mime-dict
19 strng : str or mime-dict
22 Text to page, or a mime-type keyed dict of already formatted data.
20 Text to page, or a mime-type keyed dict of already formatted data.
23
21
24 start : int
22 start : int
25 Starting line at which to place the display.
23 Starting line at which to place the display.
26 """
24 """
27
25
28 # Some routines may auto-compute start offsets incorrectly and pass a
26 # Some routines may auto-compute start offsets incorrectly and pass a
29 # negative value. Offset to 0 for robustness.
27 # negative value. Offset to 0 for robustness.
30 start = max(0, start)
28 start = max(0, start)
31 shell = get_ipython()
29 shell = get_ipython()
32
30
33 if isinstance(strng, dict):
31 if isinstance(strng, dict):
34 data = strng
32 data = strng
35 else:
33 else:
36 data = {'text/plain' : strng}
34 data = {'text/plain' : strng}
37 payload = dict(
35 payload = dict(
38 source='page',
36 source='page',
39 data=data,
37 data=data,
40 start=start,
38 start=start,
41 )
39 )
42 shell.payload_manager.write_payload(payload)
40 shell.payload_manager.write_payload(payload)
43
41
44
42
45 def install_payload_page():
43 def install_payload_page():
46 """Install this version of page as IPython.core.page.page."""
44 """DEPRECATED, use show_in_pager hook
45
46 Install this version of page as IPython.core.page.page.
47 """
48 warnings.warn("""install_payload_page is deprecated.
49 Use `ip.set_hook('show_in_pager, page.as_hook(payloadpage.page))`
50 """)
47 from IPython.core import page as corepage
51 from IPython.core import page as corepage
48 corepage.page = page
52 corepage.page = page
@@ -1,488 +1,487 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 import payloadpage
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 .session import Session
52 from .session import Session
53
53
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55 # Functions and classes
55 # Functions and classes
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57
57
58 class ZMQDisplayPublisher(DisplayPublisher):
58 class ZMQDisplayPublisher(DisplayPublisher):
59 """A display publisher that publishes data using a ZeroMQ PUB socket."""
59 """A display publisher that publishes data using a ZeroMQ PUB socket."""
60
60
61 session = Instance(Session)
61 session = Instance(Session)
62 pub_socket = Instance(SocketABC)
62 pub_socket = Instance(SocketABC)
63 parent_header = Dict({})
63 parent_header = Dict({})
64 topic = CBytes(b'display_data')
64 topic = CBytes(b'display_data')
65
65
66 def set_parent(self, parent):
66 def set_parent(self, parent):
67 """Set the parent for outbound messages."""
67 """Set the parent for outbound messages."""
68 self.parent_header = extract_header(parent)
68 self.parent_header = extract_header(parent)
69
69
70 def _flush_streams(self):
70 def _flush_streams(self):
71 """flush IO Streams prior to display"""
71 """flush IO Streams prior to display"""
72 sys.stdout.flush()
72 sys.stdout.flush()
73 sys.stderr.flush()
73 sys.stderr.flush()
74
74
75 def publish(self, data, metadata=None, source=None):
75 def publish(self, data, metadata=None, source=None):
76 self._flush_streams()
76 self._flush_streams()
77 if metadata is None:
77 if metadata is None:
78 metadata = {}
78 metadata = {}
79 self._validate_data(data, metadata)
79 self._validate_data(data, metadata)
80 content = {}
80 content = {}
81 content['data'] = encode_images(data)
81 content['data'] = encode_images(data)
82 content['metadata'] = metadata
82 content['metadata'] = metadata
83 self.session.send(
83 self.session.send(
84 self.pub_socket, u'display_data', json_clean(content),
84 self.pub_socket, u'display_data', json_clean(content),
85 parent=self.parent_header, ident=self.topic,
85 parent=self.parent_header, ident=self.topic,
86 )
86 )
87
87
88 def clear_output(self, wait=False):
88 def clear_output(self, wait=False):
89 content = dict(wait=wait)
89 content = dict(wait=wait)
90 self._flush_streams()
90 self._flush_streams()
91 self.session.send(
91 self.session.send(
92 self.pub_socket, u'clear_output', content,
92 self.pub_socket, u'clear_output', content,
93 parent=self.parent_header, ident=self.topic,
93 parent=self.parent_header, ident=self.topic,
94 )
94 )
95
95
96 @magics_class
96 @magics_class
97 class KernelMagics(Magics):
97 class KernelMagics(Magics):
98 #------------------------------------------------------------------------
98 #------------------------------------------------------------------------
99 # Magic overrides
99 # Magic overrides
100 #------------------------------------------------------------------------
100 #------------------------------------------------------------------------
101 # 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
102 # 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
103 # 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
104 # class, or that are unique to it.
104 # class, or that are unique to it.
105
105
106 _find_edit_target = CodeMagics._find_edit_target
106 _find_edit_target = CodeMagics._find_edit_target
107
107
108 @skip_doctest
108 @skip_doctest
109 @line_magic
109 @line_magic
110 def edit(self, parameter_s='', last_call=['','']):
110 def edit(self, parameter_s='', last_call=['','']):
111 """Bring up an editor and execute the resulting code.
111 """Bring up an editor and execute the resulting code.
112
112
113 Usage:
113 Usage:
114 %edit [options] [args]
114 %edit [options] [args]
115
115
116 %edit runs an external text editor. You will need to set the command for
116 %edit runs an external text editor. You will need to set the command for
117 this editor via the ``TerminalInteractiveShell.editor`` option in your
117 this editor via the ``TerminalInteractiveShell.editor`` option in your
118 configuration file before it will work.
118 configuration file before it will work.
119
119
120 This command allows you to conveniently edit multi-line code right in
120 This command allows you to conveniently edit multi-line code right in
121 your IPython session.
121 your IPython session.
122
122
123 If called without arguments, %edit opens up an empty editor with a
123 If called without arguments, %edit opens up an empty editor with a
124 temporary file and will execute the contents of this file when you
124 temporary file and will execute the contents of this file when you
125 close it (don't forget to save it!).
125 close it (don't forget to save it!).
126
126
127 Options:
127 Options:
128
128
129 -n <number>
129 -n <number>
130 Open the editor at a specified line number. By default, the IPython
130 Open the editor at a specified line number. By default, the IPython
131 editor hook uses the unix syntax 'editor +N filename', but you can
131 editor hook uses the unix syntax 'editor +N filename', but you can
132 configure this by providing your own modified hook if your favorite
132 configure this by providing your own modified hook if your favorite
133 editor supports line-number specifications with a different syntax.
133 editor supports line-number specifications with a different syntax.
134
134
135 -p
135 -p
136 Call the editor with the same data as the previous time it was used,
136 Call the editor with the same data as the previous time it was used,
137 regardless of how long ago (in your current session) it was.
137 regardless of how long ago (in your current session) it was.
138
138
139 -r
139 -r
140 Use 'raw' input. This option only applies to input taken from the
140 Use 'raw' input. This option only applies to input taken from the
141 user's history. By default, the 'processed' history is used, so that
141 user's history. By default, the 'processed' history is used, so that
142 magics are loaded in their transformed version to valid Python. If
142 magics are loaded in their transformed version to valid Python. If
143 this option is given, the raw input as typed as the command line is
143 this option is given, the raw input as typed as the command line is
144 used instead. When you exit the editor, it will be executed by
144 used instead. When you exit the editor, it will be executed by
145 IPython's own processor.
145 IPython's own processor.
146
146
147 Arguments:
147 Arguments:
148
148
149 If arguments are given, the following possibilites exist:
149 If arguments are given, the following possibilites exist:
150
150
151 - The arguments are numbers or pairs of colon-separated numbers (like
151 - The arguments are numbers or pairs of colon-separated numbers (like
152 1 4:8 9). These are interpreted as lines of previous input to be
152 1 4:8 9). These are interpreted as lines of previous input to be
153 loaded into the editor. The syntax is the same of the %macro command.
153 loaded into the editor. The syntax is the same of the %macro command.
154
154
155 - If the argument doesn't start with a number, it is evaluated as a
155 - If the argument doesn't start with a number, it is evaluated as a
156 variable and its contents loaded into the editor. You can thus edit
156 variable and its contents loaded into the editor. You can thus edit
157 any string which contains python code (including the result of
157 any string which contains python code (including the result of
158 previous edits).
158 previous edits).
159
159
160 - If the argument is the name of an object (other than a string),
160 - If the argument is the name of an object (other than a string),
161 IPython will try to locate the file where it was defined and open the
161 IPython will try to locate the file where it was defined and open the
162 editor at the point where it is defined. You can use ``%edit function``
162 editor at the point where it is defined. You can use ``%edit function``
163 to load an editor exactly at the point where 'function' is defined,
163 to load an editor exactly at the point where 'function' is defined,
164 edit it and have the file be executed automatically.
164 edit it and have the file be executed automatically.
165
165
166 If the object is a macro (see %macro for details), this opens up your
166 If the object is a macro (see %macro for details), this opens up your
167 specified editor with a temporary file containing the macro's data.
167 specified editor with a temporary file containing the macro's data.
168 Upon exit, the macro is reloaded with the contents of the file.
168 Upon exit, the macro is reloaded with the contents of the file.
169
169
170 Note: opening at an exact line is only supported under Unix, and some
170 Note: opening at an exact line is only supported under Unix, and some
171 editors (like kedit and gedit up to Gnome 2.8) do not understand the
171 editors (like kedit and gedit up to Gnome 2.8) do not understand the
172 '+NUMBER' parameter necessary for this feature. Good editors like
172 '+NUMBER' parameter necessary for this feature. Good editors like
173 (X)Emacs, vi, jed, pico and joe all do.
173 (X)Emacs, vi, jed, pico and joe all do.
174
174
175 - If the argument is not found as a variable, IPython will look for a
175 - If the argument is not found as a variable, IPython will look for a
176 file with that name (adding .py if necessary) and load it into the
176 file with that name (adding .py if necessary) and load it into the
177 editor. It will execute its contents with execfile() when you exit,
177 editor. It will execute its contents with execfile() when you exit,
178 loading any code in the file into your interactive namespace.
178 loading any code in the file into your interactive namespace.
179
179
180 Unlike in the terminal, this is designed to use a GUI editor, and we do
180 Unlike in the terminal, this is designed to use a GUI editor, and we do
181 not know when it has closed. So the file you edit will not be
181 not know when it has closed. So the file you edit will not be
182 automatically executed or printed.
182 automatically executed or printed.
183
183
184 Note that %edit is also available through the alias %ed.
184 Note that %edit is also available through the alias %ed.
185 """
185 """
186
186
187 opts,args = self.parse_options(parameter_s,'prn:')
187 opts,args = self.parse_options(parameter_s,'prn:')
188
188
189 try:
189 try:
190 filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
190 filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
191 except MacroToEdit as e:
191 except MacroToEdit as e:
192 # TODO: Implement macro editing over 2 processes.
192 # TODO: Implement macro editing over 2 processes.
193 print("Macro editing not yet implemented in 2-process model.")
193 print("Macro editing not yet implemented in 2-process model.")
194 return
194 return
195
195
196 # Make sure we send to the client an absolute path, in case the working
196 # Make sure we send to the client an absolute path, in case the working
197 # directory of client and kernel don't match
197 # directory of client and kernel don't match
198 filename = os.path.abspath(filename)
198 filename = os.path.abspath(filename)
199
199
200 payload = {
200 payload = {
201 'source' : 'edit_magic',
201 'source' : 'edit_magic',
202 'filename' : filename,
202 'filename' : filename,
203 'line_number' : lineno
203 'line_number' : lineno
204 }
204 }
205 self.shell.payload_manager.write_payload(payload)
205 self.shell.payload_manager.write_payload(payload)
206
206
207 # A few magics that are adapted to the specifics of using pexpect and a
207 # A few magics that are adapted to the specifics of using pexpect and a
208 # remote terminal
208 # remote terminal
209
209
210 @line_magic
210 @line_magic
211 def clear(self, arg_s):
211 def clear(self, arg_s):
212 """Clear the terminal."""
212 """Clear the terminal."""
213 if os.name == 'posix':
213 if os.name == 'posix':
214 self.shell.system("clear")
214 self.shell.system("clear")
215 else:
215 else:
216 self.shell.system("cls")
216 self.shell.system("cls")
217
217
218 if os.name == 'nt':
218 if os.name == 'nt':
219 # This is the usual name in windows
219 # This is the usual name in windows
220 cls = line_magic('cls')(clear)
220 cls = line_magic('cls')(clear)
221
221
222 # Terminal pagers won't work over pexpect, but we do have our own pager
222 # Terminal pagers won't work over pexpect, but we do have our own pager
223
223
224 @line_magic
224 @line_magic
225 def less(self, arg_s):
225 def less(self, arg_s):
226 """Show a file through the pager.
226 """Show a file through the pager.
227
227
228 Files ending in .py are syntax-highlighted."""
228 Files ending in .py are syntax-highlighted."""
229 if not arg_s:
229 if not arg_s:
230 raise UsageError('Missing filename.')
230 raise UsageError('Missing filename.')
231
231
232 cont = open(arg_s).read()
232 cont = open(arg_s).read()
233 if arg_s.endswith('.py'):
233 if arg_s.endswith('.py'):
234 cont = self.shell.pycolorize(openpy.read_py_file(arg_s, skip_encoding_cookie=False))
234 cont = self.shell.pycolorize(openpy.read_py_file(arg_s, skip_encoding_cookie=False))
235 else:
235 else:
236 cont = open(arg_s).read()
236 cont = open(arg_s).read()
237 page.page(cont)
237 page.page(cont)
238
238
239 more = line_magic('more')(less)
239 more = line_magic('more')(less)
240
240
241 # Man calls a pager, so we also need to redefine it
241 # Man calls a pager, so we also need to redefine it
242 if os.name == 'posix':
242 if os.name == 'posix':
243 @line_magic
243 @line_magic
244 def man(self, arg_s):
244 def man(self, arg_s):
245 """Find the man page for the given command and display in pager."""
245 """Find the man page for the given command and display in pager."""
246 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
246 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
247 split=False))
247 split=False))
248
248
249 @line_magic
249 @line_magic
250 def connect_info(self, arg_s):
250 def connect_info(self, arg_s):
251 """Print information for connecting other clients to this kernel
251 """Print information for connecting other clients to this kernel
252
252
253 It will print the contents of this session's connection file, as well as
253 It will print the contents of this session's connection file, as well as
254 shortcuts for local clients.
254 shortcuts for local clients.
255
255
256 In the simplest case, when called from the most recently launched kernel,
256 In the simplest case, when called from the most recently launched kernel,
257 secondary clients can be connected, simply with:
257 secondary clients can be connected, simply with:
258
258
259 $> ipython <app> --existing
259 $> ipython <app> --existing
260
260
261 """
261 """
262
262
263 from IPython.core.application import BaseIPythonApplication as BaseIPApp
263 from IPython.core.application import BaseIPythonApplication as BaseIPApp
264
264
265 if BaseIPApp.initialized():
265 if BaseIPApp.initialized():
266 app = BaseIPApp.instance()
266 app = BaseIPApp.instance()
267 security_dir = app.profile_dir.security_dir
267 security_dir = app.profile_dir.security_dir
268 profile = app.profile
268 profile = app.profile
269 else:
269 else:
270 profile = 'default'
270 profile = 'default'
271 security_dir = ''
271 security_dir = ''
272
272
273 try:
273 try:
274 connection_file = get_connection_file()
274 connection_file = get_connection_file()
275 info = get_connection_info(unpack=False)
275 info = get_connection_info(unpack=False)
276 except Exception as e:
276 except Exception as e:
277 error("Could not get connection info: %r" % e)
277 error("Could not get connection info: %r" % e)
278 return
278 return
279
279
280 # add profile flag for non-default profile
280 # add profile flag for non-default profile
281 profile_flag = "--profile %s" % profile if profile != 'default' else ""
281 profile_flag = "--profile %s" % profile if profile != 'default' else ""
282
282
283 # if it's in the security dir, truncate to basename
283 # if it's in the security dir, truncate to basename
284 if security_dir == os.path.dirname(connection_file):
284 if security_dir == os.path.dirname(connection_file):
285 connection_file = os.path.basename(connection_file)
285 connection_file = os.path.basename(connection_file)
286
286
287
287
288 print (info + '\n')
288 print (info + '\n')
289 print ("Paste the above JSON into a file, and connect with:\n"
289 print ("Paste the above JSON into a file, and connect with:\n"
290 " $> ipython <app> --existing <file>\n"
290 " $> ipython <app> --existing <file>\n"
291 "or, if you are local, you can connect with just:\n"
291 "or, if you are local, you can connect with just:\n"
292 " $> ipython <app> --existing {0} {1}\n"
292 " $> ipython <app> --existing {0} {1}\n"
293 "or even just:\n"
293 "or even just:\n"
294 " $> ipython <app> --existing {1}\n"
294 " $> ipython <app> --existing {1}\n"
295 "if this is the most recent IPython session you have started.".format(
295 "if this is the most recent IPython session you have started.".format(
296 connection_file, profile_flag
296 connection_file, profile_flag
297 )
297 )
298 )
298 )
299
299
300 @line_magic
300 @line_magic
301 def qtconsole(self, arg_s):
301 def qtconsole(self, arg_s):
302 """Open a qtconsole connected to this kernel.
302 """Open a qtconsole connected to this kernel.
303
303
304 Useful for connecting a qtconsole to running notebooks, for better
304 Useful for connecting a qtconsole to running notebooks, for better
305 debugging.
305 debugging.
306 """
306 """
307
307
308 # %qtconsole should imply bind_kernel for engines:
308 # %qtconsole should imply bind_kernel for engines:
309 try:
309 try:
310 from IPython.parallel import bind_kernel
310 from IPython.parallel import bind_kernel
311 except ImportError:
311 except ImportError:
312 # technically possible, because parallel has higher pyzmq min-version
312 # technically possible, because parallel has higher pyzmq min-version
313 pass
313 pass
314 else:
314 else:
315 bind_kernel()
315 bind_kernel()
316
316
317 try:
317 try:
318 p = connect_qtconsole(argv=arg_split(arg_s, os.name=='posix'))
318 p = connect_qtconsole(argv=arg_split(arg_s, os.name=='posix'))
319 except Exception as e:
319 except Exception as e:
320 error("Could not start qtconsole: %r" % e)
320 error("Could not start qtconsole: %r" % e)
321 return
321 return
322
322
323 @line_magic
323 @line_magic
324 def autosave(self, arg_s):
324 def autosave(self, arg_s):
325 """Set the autosave interval in the notebook (in seconds).
325 """Set the autosave interval in the notebook (in seconds).
326
326
327 The default value is 120, or two minutes.
327 The default value is 120, or two minutes.
328 ``%autosave 0`` will disable autosave.
328 ``%autosave 0`` will disable autosave.
329
329
330 This magic only has an effect when called from the notebook interface.
330 This magic only has an effect when called from the notebook interface.
331 It has no effect when called in a startup file.
331 It has no effect when called in a startup file.
332 """
332 """
333
333
334 try:
334 try:
335 interval = int(arg_s)
335 interval = int(arg_s)
336 except ValueError:
336 except ValueError:
337 raise UsageError("%%autosave requires an integer, got %r" % arg_s)
337 raise UsageError("%%autosave requires an integer, got %r" % arg_s)
338
338
339 # javascript wants milliseconds
339 # javascript wants milliseconds
340 milliseconds = 1000 * interval
340 milliseconds = 1000 * interval
341 display(Javascript("IPython.notebook.set_autosave_interval(%i)" % milliseconds),
341 display(Javascript("IPython.notebook.set_autosave_interval(%i)" % milliseconds),
342 include=['application/javascript']
342 include=['application/javascript']
343 )
343 )
344 if interval:
344 if interval:
345 print("Autosaving every %i seconds" % interval)
345 print("Autosaving every %i seconds" % interval)
346 else:
346 else:
347 print("Autosave disabled")
347 print("Autosave disabled")
348
348
349
349
350 class ZMQInteractiveShell(InteractiveShell):
350 class ZMQInteractiveShell(InteractiveShell):
351 """A subclass of InteractiveShell for ZMQ."""
351 """A subclass of InteractiveShell for ZMQ."""
352
352
353 displayhook_class = Type(ZMQShellDisplayHook)
353 displayhook_class = Type(ZMQShellDisplayHook)
354 display_pub_class = Type(ZMQDisplayPublisher)
354 display_pub_class = Type(ZMQDisplayPublisher)
355 data_pub_class = Type(ZMQDataPublisher)
355 data_pub_class = Type(ZMQDataPublisher)
356 kernel = Any()
356 kernel = Any()
357 parent_header = Any()
357 parent_header = Any()
358
358
359 def _banner1_default(self):
359 def _banner1_default(self):
360 return default_gui_banner
360 return default_gui_banner
361
361
362 # Override the traitlet in the parent class, because there's no point using
362 # Override the traitlet in the parent class, because there's no point using
363 # readline for the kernel. Can be removed when the readline code is moved
363 # readline for the kernel. Can be removed when the readline code is moved
364 # to the terminal frontend.
364 # to the terminal frontend.
365 colors_force = CBool(True)
365 colors_force = CBool(True)
366 readline_use = CBool(False)
366 readline_use = CBool(False)
367 # autoindent has no meaning in a zmqshell, and attempting to enable it
367 # autoindent has no meaning in a zmqshell, and attempting to enable it
368 # will print a warning in the absence of readline.
368 # will print a warning in the absence of readline.
369 autoindent = CBool(False)
369 autoindent = CBool(False)
370
370
371 exiter = Instance(ZMQExitAutocall)
371 exiter = Instance(ZMQExitAutocall)
372 def _exiter_default(self):
372 def _exiter_default(self):
373 return ZMQExitAutocall(self)
373 return ZMQExitAutocall(self)
374
374
375 def _exit_now_changed(self, name, old, new):
375 def _exit_now_changed(self, name, old, new):
376 """stop eventloop when exit_now fires"""
376 """stop eventloop when exit_now fires"""
377 if new:
377 if new:
378 loop = ioloop.IOLoop.instance()
378 loop = ioloop.IOLoop.instance()
379 loop.add_timeout(time.time()+0.1, loop.stop)
379 loop.add_timeout(time.time()+0.1, loop.stop)
380
380
381 keepkernel_on_exit = None
381 keepkernel_on_exit = None
382
382
383 # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no
383 # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no
384 # interactive input being read; we provide event loop support in ipkernel
384 # interactive input being read; we provide event loop support in ipkernel
385 @staticmethod
385 @staticmethod
386 def enable_gui(gui):
386 def enable_gui(gui):
387 from .eventloops import enable_gui as real_enable_gui
387 from .eventloops import enable_gui as real_enable_gui
388 try:
388 try:
389 real_enable_gui(gui)
389 real_enable_gui(gui)
390 except ValueError as e:
390 except ValueError as e:
391 raise UsageError("%s" % e)
391 raise UsageError("%s" % e)
392
392
393 def init_environment(self):
393 def init_environment(self):
394 """Configure the user's environment.
394 """Configure the user's environment."""
395
396 """
397 env = os.environ
395 env = os.environ
398 # These two ensure 'ls' produces nice coloring on BSD-derived systems
396 # These two ensure 'ls' produces nice coloring on BSD-derived systems
399 env['TERM'] = 'xterm-color'
397 env['TERM'] = 'xterm-color'
400 env['CLICOLOR'] = '1'
398 env['CLICOLOR'] = '1'
401 # Since normal pagers don't work at all (over pexpect we don't have
399 # Since normal pagers don't work at all (over pexpect we don't have
402 # single-key control of the subprocess), try to disable paging in
400 # single-key control of the subprocess), try to disable paging in
403 # subprocesses as much as possible.
401 # subprocesses as much as possible.
404 env['PAGER'] = 'cat'
402 env['PAGER'] = 'cat'
405 env['GIT_PAGER'] = 'cat'
403 env['GIT_PAGER'] = 'cat'
406
404
407 # And install the payload version of page.
405 def init_hooks(self):
408 install_payload_page()
406 super(ZMQInteractiveShell, self).init_hooks()
409
407 self.set_hook('show_in_pager', page.as_hook(payloadpage.page), 99)
408
410 def ask_exit(self):
409 def ask_exit(self):
411 """Engage the exit actions."""
410 """Engage the exit actions."""
412 self.exit_now = (not self.keepkernel_on_exit)
411 self.exit_now = (not self.keepkernel_on_exit)
413 payload = dict(
412 payload = dict(
414 source='ask_exit',
413 source='ask_exit',
415 keepkernel=self.keepkernel_on_exit,
414 keepkernel=self.keepkernel_on_exit,
416 )
415 )
417 self.payload_manager.write_payload(payload)
416 self.payload_manager.write_payload(payload)
418
417
419 def _showtraceback(self, etype, evalue, stb):
418 def _showtraceback(self, etype, evalue, stb):
420 # try to preserve ordering of tracebacks and print statements
419 # try to preserve ordering of tracebacks and print statements
421 sys.stdout.flush()
420 sys.stdout.flush()
422 sys.stderr.flush()
421 sys.stderr.flush()
423
422
424 exc_content = {
423 exc_content = {
425 u'traceback' : stb,
424 u'traceback' : stb,
426 u'ename' : unicode_type(etype.__name__),
425 u'ename' : unicode_type(etype.__name__),
427 u'evalue' : py3compat.safe_unicode(evalue),
426 u'evalue' : py3compat.safe_unicode(evalue),
428 }
427 }
429
428
430 dh = self.displayhook
429 dh = self.displayhook
431 # Send exception info over pub socket for other clients than the caller
430 # Send exception info over pub socket for other clients than the caller
432 # to pick up
431 # to pick up
433 topic = None
432 topic = None
434 if dh.topic:
433 if dh.topic:
435 topic = dh.topic.replace(b'execute_result', b'error')
434 topic = dh.topic.replace(b'execute_result', b'error')
436
435
437 exc_msg = dh.session.send(dh.pub_socket, u'error', json_clean(exc_content), dh.parent_header, ident=topic)
436 exc_msg = dh.session.send(dh.pub_socket, u'error', json_clean(exc_content), dh.parent_header, ident=topic)
438
437
439 # FIXME - Hack: store exception info in shell object. Right now, the
438 # FIXME - Hack: store exception info in shell object. Right now, the
440 # caller is reading this info after the fact, we need to fix this logic
439 # caller is reading this info after the fact, we need to fix this logic
441 # to remove this hack. Even uglier, we need to store the error status
440 # to remove this hack. Even uglier, we need to store the error status
442 # here, because in the main loop, the logic that sets it is being
441 # here, because in the main loop, the logic that sets it is being
443 # skipped because runlines swallows the exceptions.
442 # skipped because runlines swallows the exceptions.
444 exc_content[u'status'] = u'error'
443 exc_content[u'status'] = u'error'
445 self._reply_content = exc_content
444 self._reply_content = exc_content
446 # /FIXME
445 # /FIXME
447
446
448 return exc_content
447 return exc_content
449
448
450 def set_next_input(self, text, replace=False):
449 def set_next_input(self, text, replace=False):
451 """Send the specified text to the frontend to be presented at the next
450 """Send the specified text to the frontend to be presented at the next
452 input cell."""
451 input cell."""
453 payload = dict(
452 payload = dict(
454 source='set_next_input',
453 source='set_next_input',
455 text=text,
454 text=text,
456 replace=replace,
455 replace=replace,
457 )
456 )
458 self.payload_manager.write_payload(payload)
457 self.payload_manager.write_payload(payload)
459
458
460 def set_parent(self, parent):
459 def set_parent(self, parent):
461 """Set the parent header for associating output with its triggering input"""
460 """Set the parent header for associating output with its triggering input"""
462 self.parent_header = parent
461 self.parent_header = parent
463 self.displayhook.set_parent(parent)
462 self.displayhook.set_parent(parent)
464 self.display_pub.set_parent(parent)
463 self.display_pub.set_parent(parent)
465 self.data_pub.set_parent(parent)
464 self.data_pub.set_parent(parent)
466 try:
465 try:
467 sys.stdout.set_parent(parent)
466 sys.stdout.set_parent(parent)
468 except AttributeError:
467 except AttributeError:
469 pass
468 pass
470 try:
469 try:
471 sys.stderr.set_parent(parent)
470 sys.stderr.set_parent(parent)
472 except AttributeError:
471 except AttributeError:
473 pass
472 pass
474
473
475 def get_parent(self):
474 def get_parent(self):
476 return self.parent_header
475 return self.parent_header
477
476
478 #-------------------------------------------------------------------------
477 #-------------------------------------------------------------------------
479 # Things related to magics
478 # Things related to magics
480 #-------------------------------------------------------------------------
479 #-------------------------------------------------------------------------
481
480
482 def init_magics(self):
481 def init_magics(self):
483 super(ZMQInteractiveShell, self).init_magics()
482 super(ZMQInteractiveShell, self).init_magics()
484 self.register_magics(KernelMagics)
483 self.register_magics(KernelMagics)
485 self.magics_manager.register_alias('ed', 'edit')
484 self.magics_manager.register_alias('ed', 'edit')
486
485
487
486
488 InteractiveShellABC.register(ZMQInteractiveShell)
487 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now