##// END OF EJS Templates
Pass parent to child for configuration to propagate
Matthias Bussonnier -
r22943:3e97b06a
parent child
Show More
@@ -1,3229 +1,3229
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 import warnings
28 import warnings
29 from io import open as io_open
29 from io import open as io_open
30
30
31 from pickleshare import PickleShareDB
31 from pickleshare import PickleShareDB
32
32
33 from traitlets.config.configurable import SingletonConfigurable
33 from traitlets.config.configurable import SingletonConfigurable
34 from IPython.core import oinspect
34 from IPython.core import oinspect
35 from IPython.core import magic
35 from IPython.core import magic
36 from IPython.core import page
36 from IPython.core import page
37 from IPython.core import prefilter
37 from IPython.core import prefilter
38 from IPython.core import shadowns
38 from IPython.core import shadowns
39 from IPython.core import ultratb
39 from IPython.core import ultratb
40 from IPython.core.alias import Alias, AliasManager
40 from IPython.core.alias import Alias, AliasManager
41 from IPython.core.autocall import ExitAutocall
41 from IPython.core.autocall import ExitAutocall
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.events import EventManager, available_events
43 from IPython.core.events import EventManager, available_events
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 from IPython.core.debugger import Pdb
45 from IPython.core.debugger import Pdb
46 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.display_trap import DisplayTrap
47 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displayhook import DisplayHook
48 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.displaypub import DisplayPublisher
49 from IPython.core.error import InputRejected, UsageError
49 from IPython.core.error import InputRejected, UsageError
50 from IPython.core.extensions import ExtensionManager
50 from IPython.core.extensions import ExtensionManager
51 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.history import HistoryManager
52 from IPython.core.history import HistoryManager
53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
54 from IPython.core.logger import Logger
54 from IPython.core.logger import Logger
55 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
56 from IPython.core.payload import PayloadManager
56 from IPython.core.payload import PayloadManager
57 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.prefilter import PrefilterManager
58 from IPython.core.profiledir import ProfileDir
58 from IPython.core.profiledir import ProfileDir
59 from IPython.core.usage import default_banner
59 from IPython.core.usage import default_banner
60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
61 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils import py3compat
63 from IPython.utils import py3compat
64 from IPython.utils import openpy
64 from IPython.utils import openpy
65 from IPython.utils.decorators import undoc
65 from IPython.utils.decorators import undoc
66 from IPython.utils.io import ask_yes_no
66 from IPython.utils.io import ask_yes_no
67 from IPython.utils.ipstruct import Struct
67 from IPython.utils.ipstruct import Struct
68 from IPython.paths import get_ipython_dir
68 from IPython.paths import get_ipython_dir
69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
70 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 with_metaclass, iteritems)
72 with_metaclass, iteritems)
73 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 from IPython.utils.tempdir import TemporaryDirectory
76 from IPython.utils.tempdir import TemporaryDirectory
77 from traitlets import (
77 from traitlets import (
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 observe, default,
79 observe, default,
80 )
80 )
81 from warnings import warn
81 from warnings import warn
82 from logging import error
82 from logging import error
83 import IPython.core.hooks
83 import IPython.core.hooks
84
84
85 # NoOpContext is deprecated, but ipykernel imports it from here.
85 # NoOpContext is deprecated, but ipykernel imports it from here.
86 # See https://github.com/ipython/ipykernel/issues/157
86 # See https://github.com/ipython/ipykernel/issues/157
87 from IPython.utils.contexts import NoOpContext
87 from IPython.utils.contexts import NoOpContext
88
88
89 try:
89 try:
90 import docrepr.sphinxify as sphx
90 import docrepr.sphinxify as sphx
91
91
92 def sphinxify(doc):
92 def sphinxify(doc):
93 with TemporaryDirectory() as dirname:
93 with TemporaryDirectory() as dirname:
94 return {
94 return {
95 'text/html': sphx.sphinxify(doc, dirname),
95 'text/html': sphx.sphinxify(doc, dirname),
96 'text/plain': doc
96 'text/plain': doc
97 }
97 }
98 except ImportError:
98 except ImportError:
99 sphinxify = None
99 sphinxify = None
100
100
101
101
102 class ProvisionalWarning(DeprecationWarning):
102 class ProvisionalWarning(DeprecationWarning):
103 """
103 """
104 Warning class for unstable features
104 Warning class for unstable features
105 """
105 """
106 pass
106 pass
107
107
108 #-----------------------------------------------------------------------------
108 #-----------------------------------------------------------------------------
109 # Globals
109 # Globals
110 #-----------------------------------------------------------------------------
110 #-----------------------------------------------------------------------------
111
111
112 # compiled regexps for autoindent management
112 # compiled regexps for autoindent management
113 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
113 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
114
114
115 #-----------------------------------------------------------------------------
115 #-----------------------------------------------------------------------------
116 # Utilities
116 # Utilities
117 #-----------------------------------------------------------------------------
117 #-----------------------------------------------------------------------------
118
118
119 @undoc
119 @undoc
120 def softspace(file, newvalue):
120 def softspace(file, newvalue):
121 """Copied from code.py, to remove the dependency"""
121 """Copied from code.py, to remove the dependency"""
122
122
123 oldvalue = 0
123 oldvalue = 0
124 try:
124 try:
125 oldvalue = file.softspace
125 oldvalue = file.softspace
126 except AttributeError:
126 except AttributeError:
127 pass
127 pass
128 try:
128 try:
129 file.softspace = newvalue
129 file.softspace = newvalue
130 except (AttributeError, TypeError):
130 except (AttributeError, TypeError):
131 # "attribute-less object" or "read-only attributes"
131 # "attribute-less object" or "read-only attributes"
132 pass
132 pass
133 return oldvalue
133 return oldvalue
134
134
135 @undoc
135 @undoc
136 def no_op(*a, **kw): pass
136 def no_op(*a, **kw): pass
137
137
138
138
139 class SpaceInInput(Exception): pass
139 class SpaceInInput(Exception): pass
140
140
141
141
142 def get_default_colors():
142 def get_default_colors():
143 "DEPRECATED"
143 "DEPRECATED"
144 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
144 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
145 DeprecationWarning, stacklevel=2)
145 DeprecationWarning, stacklevel=2)
146 return 'Neutral'
146 return 'Neutral'
147
147
148
148
149 class SeparateUnicode(Unicode):
149 class SeparateUnicode(Unicode):
150 r"""A Unicode subclass to validate separate_in, separate_out, etc.
150 r"""A Unicode subclass to validate separate_in, separate_out, etc.
151
151
152 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
152 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
153 """
153 """
154
154
155 def validate(self, obj, value):
155 def validate(self, obj, value):
156 if value == '0': value = ''
156 if value == '0': value = ''
157 value = value.replace('\\n','\n')
157 value = value.replace('\\n','\n')
158 return super(SeparateUnicode, self).validate(obj, value)
158 return super(SeparateUnicode, self).validate(obj, value)
159
159
160
160
161 @undoc
161 @undoc
162 class DummyMod(object):
162 class DummyMod(object):
163 """A dummy module used for IPython's interactive module when
163 """A dummy module used for IPython's interactive module when
164 a namespace must be assigned to the module's __dict__."""
164 a namespace must be assigned to the module's __dict__."""
165 pass
165 pass
166
166
167
167
168 class ExecutionResult(object):
168 class ExecutionResult(object):
169 """The result of a call to :meth:`InteractiveShell.run_cell`
169 """The result of a call to :meth:`InteractiveShell.run_cell`
170
170
171 Stores information about what took place.
171 Stores information about what took place.
172 """
172 """
173 execution_count = None
173 execution_count = None
174 error_before_exec = None
174 error_before_exec = None
175 error_in_exec = None
175 error_in_exec = None
176 result = None
176 result = None
177
177
178 @property
178 @property
179 def success(self):
179 def success(self):
180 return (self.error_before_exec is None) and (self.error_in_exec is None)
180 return (self.error_before_exec is None) and (self.error_in_exec is None)
181
181
182 def raise_error(self):
182 def raise_error(self):
183 """Reraises error if `success` is `False`, otherwise does nothing"""
183 """Reraises error if `success` is `False`, otherwise does nothing"""
184 if self.error_before_exec is not None:
184 if self.error_before_exec is not None:
185 raise self.error_before_exec
185 raise self.error_before_exec
186 if self.error_in_exec is not None:
186 if self.error_in_exec is not None:
187 raise self.error_in_exec
187 raise self.error_in_exec
188
188
189 def __repr__(self):
189 def __repr__(self):
190 if sys.version_info > (3,):
190 if sys.version_info > (3,):
191 name = self.__class__.__qualname__
191 name = self.__class__.__qualname__
192 else:
192 else:
193 name = self.__class__.__name__
193 name = self.__class__.__name__
194 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
194 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
195 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
195 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
196
196
197
197
198 class InteractiveShell(SingletonConfigurable):
198 class InteractiveShell(SingletonConfigurable):
199 """An enhanced, interactive shell for Python."""
199 """An enhanced, interactive shell for Python."""
200
200
201 _instance = None
201 _instance = None
202
202
203 ast_transformers = List([], help=
203 ast_transformers = List([], help=
204 """
204 """
205 A list of ast.NodeTransformer subclass instances, which will be applied
205 A list of ast.NodeTransformer subclass instances, which will be applied
206 to user input before code is run.
206 to user input before code is run.
207 """
207 """
208 ).tag(config=True)
208 ).tag(config=True)
209
209
210 autocall = Enum((0,1,2), default_value=0, help=
210 autocall = Enum((0,1,2), default_value=0, help=
211 """
211 """
212 Make IPython automatically call any callable object even if you didn't
212 Make IPython automatically call any callable object even if you didn't
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 automatically. The value can be '0' to disable the feature, '1' for
214 automatically. The value can be '0' to disable the feature, '1' for
215 'smart' autocall, where it is not applied if there are no more
215 'smart' autocall, where it is not applied if there are no more
216 arguments on the line, and '2' for 'full' autocall, where all callable
216 arguments on the line, and '2' for 'full' autocall, where all callable
217 objects are automatically called (even if no arguments are present).
217 objects are automatically called (even if no arguments are present).
218 """
218 """
219 ).tag(config=True)
219 ).tag(config=True)
220 # TODO: remove all autoindent logic and put into frontends.
220 # TODO: remove all autoindent logic and put into frontends.
221 # We can't do this yet because even runlines uses the autoindent.
221 # We can't do this yet because even runlines uses the autoindent.
222 autoindent = Bool(True, help=
222 autoindent = Bool(True, help=
223 """
223 """
224 Autoindent IPython code entered interactively.
224 Autoindent IPython code entered interactively.
225 """
225 """
226 ).tag(config=True)
226 ).tag(config=True)
227
227
228 automagic = Bool(True, help=
228 automagic = Bool(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 ).tag(config=True)
232 ).tag(config=True)
233
233
234 banner1 = Unicode(default_banner,
234 banner1 = Unicode(default_banner,
235 help="""The part of the banner to be printed before the profile"""
235 help="""The part of the banner to be printed before the profile"""
236 ).tag(config=True)
236 ).tag(config=True)
237 banner2 = Unicode('',
237 banner2 = Unicode('',
238 help="""The part of the banner to be printed after the profile"""
238 help="""The part of the banner to be printed after the profile"""
239 ).tag(config=True)
239 ).tag(config=True)
240
240
241 cache_size = Integer(1000, help=
241 cache_size = Integer(1000, help=
242 """
242 """
243 Set the size of the output cache. The default is 1000, you can
243 Set the size of the output cache. The default is 1000, you can
244 change it permanently in your config file. Setting it to 0 completely
244 change it permanently in your config file. Setting it to 0 completely
245 disables the caching system, and the minimum value accepted is 20 (if
245 disables the caching system, and the minimum value accepted is 20 (if
246 you provide a value less than 20, it is reset to 0 and a warning is
246 you provide a value less than 20, it is reset to 0 and a warning is
247 issued). This limit is defined because otherwise you'll spend more
247 issued). This limit is defined because otherwise you'll spend more
248 time re-flushing a too small cache than working
248 time re-flushing a too small cache than working
249 """
249 """
250 ).tag(config=True)
250 ).tag(config=True)
251 color_info = Bool(True, help=
251 color_info = Bool(True, help=
252 """
252 """
253 Use colors for displaying information about objects. Because this
253 Use colors for displaying information about objects. Because this
254 information is passed through a pager (like 'less'), and some pagers
254 information is passed through a pager (like 'less'), and some pagers
255 get confused with color codes, this capability can be turned off.
255 get confused with color codes, this capability can be turned off.
256 """
256 """
257 ).tag(config=True)
257 ).tag(config=True)
258 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
258 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
259 default_value='Neutral',
259 default_value='Neutral',
260 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
260 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
261 ).tag(config=True)
261 ).tag(config=True)
262 debug = Bool(False).tag(config=True)
262 debug = Bool(False).tag(config=True)
263 disable_failing_post_execute = Bool(False,
263 disable_failing_post_execute = Bool(False,
264 help="Don't call post-execute functions that have failed in the past."
264 help="Don't call post-execute functions that have failed in the past."
265 ).tag(config=True)
265 ).tag(config=True)
266 display_formatter = Instance(DisplayFormatter, allow_none=True)
266 display_formatter = Instance(DisplayFormatter, allow_none=True)
267 displayhook_class = Type(DisplayHook)
267 displayhook_class = Type(DisplayHook)
268 display_pub_class = Type(DisplayPublisher)
268 display_pub_class = Type(DisplayPublisher)
269
269
270 sphinxify_docstring = Bool(False, help=
270 sphinxify_docstring = Bool(False, help=
271 """
271 """
272 Enables rich html representation of docstrings. (This requires the
272 Enables rich html representation of docstrings. (This requires the
273 docrepr module).
273 docrepr module).
274 """).tag(config=True)
274 """).tag(config=True)
275
275
276 @observe("sphinxify_docstring")
276 @observe("sphinxify_docstring")
277 def _sphinxify_docstring_changed(self, change):
277 def _sphinxify_docstring_changed(self, change):
278 if change['new']:
278 if change['new']:
279 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
279 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
280
280
281 enable_html_pager = Bool(False, help=
281 enable_html_pager = Bool(False, help=
282 """
282 """
283 (Provisional API) enables html representation in mime bundles sent
283 (Provisional API) enables html representation in mime bundles sent
284 to pagers.
284 to pagers.
285 """).tag(config=True)
285 """).tag(config=True)
286
286
287 @observe("enable_html_pager")
287 @observe("enable_html_pager")
288 def _enable_html_pager_changed(self, change):
288 def _enable_html_pager_changed(self, change):
289 if change['new']:
289 if change['new']:
290 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
290 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
291
291
292 data_pub_class = None
292 data_pub_class = None
293
293
294 exit_now = Bool(False)
294 exit_now = Bool(False)
295 exiter = Instance(ExitAutocall)
295 exiter = Instance(ExitAutocall)
296 @default('exiter')
296 @default('exiter')
297 def _exiter_default(self):
297 def _exiter_default(self):
298 return ExitAutocall(self)
298 return ExitAutocall(self)
299 # Monotonically increasing execution counter
299 # Monotonically increasing execution counter
300 execution_count = Integer(1)
300 execution_count = Integer(1)
301 filename = Unicode("<ipython console>")
301 filename = Unicode("<ipython console>")
302 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
302 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
303
303
304 # Input splitter, to transform input line by line and detect when a block
304 # Input splitter, to transform input line by line and detect when a block
305 # is ready to be executed.
305 # is ready to be executed.
306 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
306 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
307 (), {'line_input_checker': True})
307 (), {'line_input_checker': True})
308
308
309 # This InputSplitter instance is used to transform completed cells before
309 # This InputSplitter instance is used to transform completed cells before
310 # running them. It allows cell magics to contain blank lines.
310 # running them. It allows cell magics to contain blank lines.
311 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
311 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
312 (), {'line_input_checker': False})
312 (), {'line_input_checker': False})
313
313
314 logstart = Bool(False, help=
314 logstart = Bool(False, help=
315 """
315 """
316 Start logging to the default log file in overwrite mode.
316 Start logging to the default log file in overwrite mode.
317 Use `logappend` to specify a log file to **append** logs to.
317 Use `logappend` to specify a log file to **append** logs to.
318 """
318 """
319 ).tag(config=True)
319 ).tag(config=True)
320 logfile = Unicode('', help=
320 logfile = Unicode('', help=
321 """
321 """
322 The name of the logfile to use.
322 The name of the logfile to use.
323 """
323 """
324 ).tag(config=True)
324 ).tag(config=True)
325 logappend = Unicode('', help=
325 logappend = Unicode('', help=
326 """
326 """
327 Start logging to the given file in append mode.
327 Start logging to the given file in append mode.
328 Use `logfile` to specify a log file to **overwrite** logs to.
328 Use `logfile` to specify a log file to **overwrite** logs to.
329 """
329 """
330 ).tag(config=True)
330 ).tag(config=True)
331 object_info_string_level = Enum((0,1,2), default_value=0,
331 object_info_string_level = Enum((0,1,2), default_value=0,
332 ).tag(config=True)
332 ).tag(config=True)
333 pdb = Bool(False, help=
333 pdb = Bool(False, help=
334 """
334 """
335 Automatically call the pdb debugger after every exception.
335 Automatically call the pdb debugger after every exception.
336 """
336 """
337 ).tag(config=True)
337 ).tag(config=True)
338 display_page = Bool(False,
338 display_page = Bool(False,
339 help="""If True, anything that would be passed to the pager
339 help="""If True, anything that would be passed to the pager
340 will be displayed as regular output instead."""
340 will be displayed as regular output instead."""
341 ).tag(config=True)
341 ).tag(config=True)
342
342
343 # deprecated prompt traits:
343 # deprecated prompt traits:
344
344
345 prompt_in1 = Unicode('In [\\#]: ',
345 prompt_in1 = Unicode('In [\\#]: ',
346 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
346 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
347 ).tag(config=True)
347 ).tag(config=True)
348 prompt_in2 = Unicode(' .\\D.: ',
348 prompt_in2 = Unicode(' .\\D.: ',
349 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
349 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
350 ).tag(config=True)
350 ).tag(config=True)
351 prompt_out = Unicode('Out[\\#]: ',
351 prompt_out = Unicode('Out[\\#]: ',
352 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
352 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
353 ).tag(config=True)
353 ).tag(config=True)
354 prompts_pad_left = Bool(True,
354 prompts_pad_left = Bool(True,
355 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
355 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
356 ).tag(config=True)
356 ).tag(config=True)
357
357
358 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
358 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
359 def _prompt_trait_changed(self, change):
359 def _prompt_trait_changed(self, change):
360 name = change['name']
360 name = change['name']
361 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
361 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
362 name=name)
362 name=name)
363 )
363 )
364 # protect against weird cases where self.config may not exist:
364 # protect against weird cases where self.config may not exist:
365
365
366 show_rewritten_input = Bool(True,
366 show_rewritten_input = Bool(True,
367 help="Show rewritten input, e.g. for autocall."
367 help="Show rewritten input, e.g. for autocall."
368 ).tag(config=True)
368 ).tag(config=True)
369
369
370 quiet = Bool(False).tag(config=True)
370 quiet = Bool(False).tag(config=True)
371
371
372 history_length = Integer(10000,
372 history_length = Integer(10000,
373 help='Total length of command history'
373 help='Total length of command history'
374 ).tag(config=True)
374 ).tag(config=True)
375
375
376 history_load_length = Integer(1000, help=
376 history_load_length = Integer(1000, help=
377 """
377 """
378 The number of saved history entries to be loaded
378 The number of saved history entries to be loaded
379 into the history buffer at startup.
379 into the history buffer at startup.
380 """
380 """
381 ).tag(config=True)
381 ).tag(config=True)
382
382
383 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
383 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
384 default_value='last_expr',
384 default_value='last_expr',
385 help="""
385 help="""
386 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
386 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
387 run interactively (displaying output from expressions)."""
387 run interactively (displaying output from expressions)."""
388 ).tag(config=True)
388 ).tag(config=True)
389
389
390 # TODO: this part of prompt management should be moved to the frontends.
390 # TODO: this part of prompt management should be moved to the frontends.
391 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
391 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
392 separate_in = SeparateUnicode('\n').tag(config=True)
392 separate_in = SeparateUnicode('\n').tag(config=True)
393 separate_out = SeparateUnicode('').tag(config=True)
393 separate_out = SeparateUnicode('').tag(config=True)
394 separate_out2 = SeparateUnicode('').tag(config=True)
394 separate_out2 = SeparateUnicode('').tag(config=True)
395 wildcards_case_sensitive = Bool(True).tag(config=True)
395 wildcards_case_sensitive = Bool(True).tag(config=True)
396 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
396 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
397 default_value='Context').tag(config=True)
397 default_value='Context').tag(config=True)
398
398
399 # Subcomponents of InteractiveShell
399 # Subcomponents of InteractiveShell
400 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
400 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
401 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
401 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
402 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
402 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
403 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
403 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
404 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
404 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
405 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
405 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
406 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
406 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
407 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
407 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
408
408
409 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
409 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
410 @property
410 @property
411 def profile(self):
411 def profile(self):
412 if self.profile_dir is not None:
412 if self.profile_dir is not None:
413 name = os.path.basename(self.profile_dir.location)
413 name = os.path.basename(self.profile_dir.location)
414 return name.replace('profile_','')
414 return name.replace('profile_','')
415
415
416
416
417 # Private interface
417 # Private interface
418 _post_execute = Dict()
418 _post_execute = Dict()
419
419
420 # Tracks any GUI loop loaded for pylab
420 # Tracks any GUI loop loaded for pylab
421 pylab_gui_select = None
421 pylab_gui_select = None
422
422
423 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
423 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
424
424
425 def __init__(self, ipython_dir=None, profile_dir=None,
425 def __init__(self, ipython_dir=None, profile_dir=None,
426 user_module=None, user_ns=None,
426 user_module=None, user_ns=None,
427 custom_exceptions=((), None), **kwargs):
427 custom_exceptions=((), None), **kwargs):
428
428
429 # This is where traits with a config_key argument are updated
429 # This is where traits with a config_key argument are updated
430 # from the values on config.
430 # from the values on config.
431 super(InteractiveShell, self).__init__(**kwargs)
431 super(InteractiveShell, self).__init__(**kwargs)
432 if 'PromptManager' in self.config:
432 if 'PromptManager' in self.config:
433 warn('As of IPython 5.0 `PromptManager` config will have no effect'
433 warn('As of IPython 5.0 `PromptManager` config will have no effect'
434 ' and has been replaced by TerminalInteractiveShell.prompts_class')
434 ' and has been replaced by TerminalInteractiveShell.prompts_class')
435 self.configurables = [self]
435 self.configurables = [self]
436
436
437 # These are relatively independent and stateless
437 # These are relatively independent and stateless
438 self.init_ipython_dir(ipython_dir)
438 self.init_ipython_dir(ipython_dir)
439 self.init_profile_dir(profile_dir)
439 self.init_profile_dir(profile_dir)
440 self.init_instance_attrs()
440 self.init_instance_attrs()
441 self.init_environment()
441 self.init_environment()
442
442
443 # Check if we're in a virtualenv, and set up sys.path.
443 # Check if we're in a virtualenv, and set up sys.path.
444 self.init_virtualenv()
444 self.init_virtualenv()
445
445
446 # Create namespaces (user_ns, user_global_ns, etc.)
446 # Create namespaces (user_ns, user_global_ns, etc.)
447 self.init_create_namespaces(user_module, user_ns)
447 self.init_create_namespaces(user_module, user_ns)
448 # This has to be done after init_create_namespaces because it uses
448 # This has to be done after init_create_namespaces because it uses
449 # something in self.user_ns, but before init_sys_modules, which
449 # something in self.user_ns, but before init_sys_modules, which
450 # is the first thing to modify sys.
450 # is the first thing to modify sys.
451 # TODO: When we override sys.stdout and sys.stderr before this class
451 # TODO: When we override sys.stdout and sys.stderr before this class
452 # is created, we are saving the overridden ones here. Not sure if this
452 # is created, we are saving the overridden ones here. Not sure if this
453 # is what we want to do.
453 # is what we want to do.
454 self.save_sys_module_state()
454 self.save_sys_module_state()
455 self.init_sys_modules()
455 self.init_sys_modules()
456
456
457 # While we're trying to have each part of the code directly access what
457 # While we're trying to have each part of the code directly access what
458 # it needs without keeping redundant references to objects, we have too
458 # it needs without keeping redundant references to objects, we have too
459 # much legacy code that expects ip.db to exist.
459 # much legacy code that expects ip.db to exist.
460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
461
461
462 self.init_history()
462 self.init_history()
463 self.init_encoding()
463 self.init_encoding()
464 self.init_prefilter()
464 self.init_prefilter()
465
465
466 self.init_syntax_highlighting()
466 self.init_syntax_highlighting()
467 self.init_hooks()
467 self.init_hooks()
468 self.init_events()
468 self.init_events()
469 self.init_pushd_popd_magic()
469 self.init_pushd_popd_magic()
470 self.init_user_ns()
470 self.init_user_ns()
471 self.init_logger()
471 self.init_logger()
472 self.init_builtins()
472 self.init_builtins()
473
473
474 # The following was in post_config_initialization
474 # The following was in post_config_initialization
475 self.init_inspector()
475 self.init_inspector()
476 self.raw_input_original = input
476 self.raw_input_original = input
477 self.init_completer()
477 self.init_completer()
478 # TODO: init_io() needs to happen before init_traceback handlers
478 # TODO: init_io() needs to happen before init_traceback handlers
479 # because the traceback handlers hardcode the stdout/stderr streams.
479 # because the traceback handlers hardcode the stdout/stderr streams.
480 # This logic in in debugger.Pdb and should eventually be changed.
480 # This logic in in debugger.Pdb and should eventually be changed.
481 self.init_io()
481 self.init_io()
482 self.init_traceback_handlers(custom_exceptions)
482 self.init_traceback_handlers(custom_exceptions)
483 self.init_prompts()
483 self.init_prompts()
484 self.init_display_formatter()
484 self.init_display_formatter()
485 self.init_display_pub()
485 self.init_display_pub()
486 self.init_data_pub()
486 self.init_data_pub()
487 self.init_displayhook()
487 self.init_displayhook()
488 self.init_magics()
488 self.init_magics()
489 self.init_alias()
489 self.init_alias()
490 self.init_logstart()
490 self.init_logstart()
491 self.init_pdb()
491 self.init_pdb()
492 self.init_extension_manager()
492 self.init_extension_manager()
493 self.init_payload()
493 self.init_payload()
494 self.init_deprecation_warnings()
494 self.init_deprecation_warnings()
495 self.hooks.late_startup_hook()
495 self.hooks.late_startup_hook()
496 self.events.trigger('shell_initialized', self)
496 self.events.trigger('shell_initialized', self)
497 atexit.register(self.atexit_operations)
497 atexit.register(self.atexit_operations)
498
498
499 def get_ipython(self):
499 def get_ipython(self):
500 """Return the currently running IPython instance."""
500 """Return the currently running IPython instance."""
501 return self
501 return self
502
502
503 #-------------------------------------------------------------------------
503 #-------------------------------------------------------------------------
504 # Trait changed handlers
504 # Trait changed handlers
505 #-------------------------------------------------------------------------
505 #-------------------------------------------------------------------------
506 @observe('ipython_dir')
506 @observe('ipython_dir')
507 def _ipython_dir_changed(self, change):
507 def _ipython_dir_changed(self, change):
508 ensure_dir_exists(change['new'])
508 ensure_dir_exists(change['new'])
509
509
510 def set_autoindent(self,value=None):
510 def set_autoindent(self,value=None):
511 """Set the autoindent flag.
511 """Set the autoindent flag.
512
512
513 If called with no arguments, it acts as a toggle."""
513 If called with no arguments, it acts as a toggle."""
514 if value is None:
514 if value is None:
515 self.autoindent = not self.autoindent
515 self.autoindent = not self.autoindent
516 else:
516 else:
517 self.autoindent = value
517 self.autoindent = value
518
518
519 #-------------------------------------------------------------------------
519 #-------------------------------------------------------------------------
520 # init_* methods called by __init__
520 # init_* methods called by __init__
521 #-------------------------------------------------------------------------
521 #-------------------------------------------------------------------------
522
522
523 def init_ipython_dir(self, ipython_dir):
523 def init_ipython_dir(self, ipython_dir):
524 if ipython_dir is not None:
524 if ipython_dir is not None:
525 self.ipython_dir = ipython_dir
525 self.ipython_dir = ipython_dir
526 return
526 return
527
527
528 self.ipython_dir = get_ipython_dir()
528 self.ipython_dir = get_ipython_dir()
529
529
530 def init_profile_dir(self, profile_dir):
530 def init_profile_dir(self, profile_dir):
531 if profile_dir is not None:
531 if profile_dir is not None:
532 self.profile_dir = profile_dir
532 self.profile_dir = profile_dir
533 return
533 return
534 self.profile_dir =\
534 self.profile_dir =\
535 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
535 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
536
536
537 def init_instance_attrs(self):
537 def init_instance_attrs(self):
538 self.more = False
538 self.more = False
539
539
540 # command compiler
540 # command compiler
541 self.compile = CachingCompiler()
541 self.compile = CachingCompiler()
542
542
543 # Make an empty namespace, which extension writers can rely on both
543 # Make an empty namespace, which extension writers can rely on both
544 # existing and NEVER being used by ipython itself. This gives them a
544 # existing and NEVER being used by ipython itself. This gives them a
545 # convenient location for storing additional information and state
545 # convenient location for storing additional information and state
546 # their extensions may require, without fear of collisions with other
546 # their extensions may require, without fear of collisions with other
547 # ipython names that may develop later.
547 # ipython names that may develop later.
548 self.meta = Struct()
548 self.meta = Struct()
549
549
550 # Temporary files used for various purposes. Deleted at exit.
550 # Temporary files used for various purposes. Deleted at exit.
551 self.tempfiles = []
551 self.tempfiles = []
552 self.tempdirs = []
552 self.tempdirs = []
553
553
554 # keep track of where we started running (mainly for crash post-mortem)
554 # keep track of where we started running (mainly for crash post-mortem)
555 # This is not being used anywhere currently.
555 # This is not being used anywhere currently.
556 self.starting_dir = py3compat.getcwd()
556 self.starting_dir = py3compat.getcwd()
557
557
558 # Indentation management
558 # Indentation management
559 self.indent_current_nsp = 0
559 self.indent_current_nsp = 0
560
560
561 # Dict to track post-execution functions that have been registered
561 # Dict to track post-execution functions that have been registered
562 self._post_execute = {}
562 self._post_execute = {}
563
563
564 def init_environment(self):
564 def init_environment(self):
565 """Any changes we need to make to the user's environment."""
565 """Any changes we need to make to the user's environment."""
566 pass
566 pass
567
567
568 def init_encoding(self):
568 def init_encoding(self):
569 # Get system encoding at startup time. Certain terminals (like Emacs
569 # Get system encoding at startup time. Certain terminals (like Emacs
570 # under Win32 have it set to None, and we need to have a known valid
570 # under Win32 have it set to None, and we need to have a known valid
571 # encoding to use in the raw_input() method
571 # encoding to use in the raw_input() method
572 try:
572 try:
573 self.stdin_encoding = sys.stdin.encoding or 'ascii'
573 self.stdin_encoding = sys.stdin.encoding or 'ascii'
574 except AttributeError:
574 except AttributeError:
575 self.stdin_encoding = 'ascii'
575 self.stdin_encoding = 'ascii'
576
576
577
577
578 @observe('colors')
578 @observe('colors')
579 def init_syntax_highlighting(self, changes=None):
579 def init_syntax_highlighting(self, changes=None):
580 # Python source parser/formatter for syntax highlighting
580 # Python source parser/formatter for syntax highlighting
581 pyformat = PyColorize.Parser(style=self.colors).format
581 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
582 self.pycolorize = lambda src: pyformat(src,'str')
582 self.pycolorize = lambda src: pyformat(src,'str')
583
583
584 def refresh_style(self):
584 def refresh_style(self):
585 # No-op here, used in subclass
585 # No-op here, used in subclass
586 pass
586 pass
587
587
588 def init_pushd_popd_magic(self):
588 def init_pushd_popd_magic(self):
589 # for pushd/popd management
589 # for pushd/popd management
590 self.home_dir = get_home_dir()
590 self.home_dir = get_home_dir()
591
591
592 self.dir_stack = []
592 self.dir_stack = []
593
593
594 def init_logger(self):
594 def init_logger(self):
595 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
595 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
596 logmode='rotate')
596 logmode='rotate')
597
597
598 def init_logstart(self):
598 def init_logstart(self):
599 """Initialize logging in case it was requested at the command line.
599 """Initialize logging in case it was requested at the command line.
600 """
600 """
601 if self.logappend:
601 if self.logappend:
602 self.magic('logstart %s append' % self.logappend)
602 self.magic('logstart %s append' % self.logappend)
603 elif self.logfile:
603 elif self.logfile:
604 self.magic('logstart %s' % self.logfile)
604 self.magic('logstart %s' % self.logfile)
605 elif self.logstart:
605 elif self.logstart:
606 self.magic('logstart')
606 self.magic('logstart')
607
607
608 def