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