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