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